Preface

This developer guide comes directly from the docs directory of the Codename One Git repository. The documentation is written in AsciiDoc and published from the main branch to several targets.

Where else to look

This guide is the conceptual and tutorial reference. These resources cover the rest:

Authors

This document includes content from the following contributors and from earlier community wiki edits:

Rights & Licensing

You may copy, redistribute, or print this document without prior permission from Codename One. You may not charge for the document itself, but charging for printing costs remains permitted.

If you print or reproduce sections and make changes, state that the result is a modified copy. Also link to the original source at https://www.codenameone.com/developer-guide/.

Conventions

This guide uses several notations for tips and further guidance.

When additional information breaks from the current tutorial flow, use a sidebar like this:

Sidebar

Dig deeper into details that don’t quite fit the current flow. Sidebars cover important detours. You can skip them while reading and return to them later.

Here are common conventions for highlighting notes:

This is an important note
This is a helpful tip
This is a general informational note. It may be interesting, but it isn’t crucial.
This is a warning. Pay attention to it.

This convention is used when referring to a button or widget to press in the UI. For example, press the button labeled Press Here.

Quotes appear as follows:

This is a quote

— By Author

Bold provides light emphasis for a specific word or two within a sentence.

Getting started

1. Introduction

Codename One is a Write Once Run Anywhere mobile development platform for Java/Kotlin developers. It fits into modern Maven-capable IDEs such as IntelliJ IDEA, NetBeans, VS Code, and Eclipse, and you can also drive it entirely from the command line.

Codename One’s mission statement is:

Unify the complex and fragmented task of mobile device programming into a single set of tools, APIs and services. As a result create a more manageable approach to mobile application development without sacrificing the power/control given to developers.

This brings that old "Write Once Run Anywhere" (WORA) Java mantra to mobile devices without dumbing it down to the lowest common denominator.

The things that make Codename One stand out from other tools in this field are:

  • Write Once Run Anywhere support with no special hardware requirements and 100% code reuse

  • Compiles Java/Kotlin into native code for iOS, Android and even JavaScript/PWA

  • Open Source and Free with commercial backing/support

  • Easy to use with 100% portable Drag GUI builder

  • Full access to underlying native OS capabilities using the native OS programming language (for example: Objective-C) without compromising portability

  • Provides full control over every pixel on the screen

  • Lets you use native widgets (views) and mix them with Codename One components within the same hierarchy (heavyweight/lightweight mixing)

  • Supports seamless Continuous Integration out of the box

Codename One can trace its roots to the open source LWUIT project started at Sun Microsystem in 2007 by Chen Fishbein (co-founder of Codename One). It has been under constant development for over a decade.

1.1. Build cloud

The build cloud approach to mobile development is one of the things that makes Codename One stand out. iOS native development requires a Mac with Xcode. Windows native development requires a Windows machine. To make matters worse, Apple, Google, and Microsoft change their tools.

That makes it hard to keep up.

When you develop an app in Codename One, use the built-in simulator for running and debugging. When you want to build a native app, use the build cloud, where Macs build the native iOS apps and Windows machines build the native Windows apps. This works seamlessly and makes Codename One apps native because the native platform compiles them. For example, iOS builds use Macs running Xcode, the native Apple tool, to build the app.

Codename One doesn’t send source code to the build cloud, compiled bytecode!

1.1.1. Why build servers

The build servers can build native iOS apps without a Mac and native Windows apps without a Windows machine. They remove the need to install and update complex toolchains and simplify the process of building a native app to a right click.

Even though the build servers streamline delivery, Codename One also supports fully local builds. You can install the toolchain on your own hardware and follow the workflows in Chapter 2, Maven Project Workflow and Chapter 133, Working with Codename One sources to compile, package, and test apps without leaving your desktop environment.

For example, because native iOS applications require a Mac with a recent version of Xcode, Codename One maintains such machines in the cloud. When developers send an iOS build, that Mac generates C source code using ParparVM, then compiles the C source code using Xcode and signs the resulting binary using Xcode. You can install the binary on your device or build a distribution binary for the App Store. Since C code is generated, your app is also future-proof against changes from Apple. You can also inject Objective-C native code into the app while keeping it 100% portable thanks to Codename One’s native interfaces capability.

Subscribers can receive the C source code back using the include-sources feature of Codename One and use those sources for benchmarking and debugging on devices.

The same is true for most other platforms. On Android and Java SE, Codename One runs the standard Java code, unchanged.

Java Language Level Support

Historically, Java 8 syntax was supported through Retrolambda on the Codename One servers. It translated bytecode to Java 5 syntax using a server-based processor built on Retroweaver and custom code. This architecture was transparent to developers because the build servers abstract most of the painful differences between devices.

Today Codename One supports Java 25 level bytecode in ParparVM and Android supports Java 17 level bytecode natively. This lets Codename One support Java 17 seamlessly, and newer versions enable Java 25 level support through client side bytecode mutation.

1.1.2. How does Codename One work

Codename One uses a SaaS-based approach so the information in this appendix might (and probably will) change in the future to accommodate improved architectures. This appendix includes this information for reference, you don’t need to understand this to follow the content of the book…​

Since Android is already based on Java, Codename One is already native to Android and works with the Android VM (ART/Dalvik).

On iOS, Codename One built and open-sourced ParparVM, which is a conservative VM. ParparVM features a concurrent, non-blocking GC and is written entirely in Java/C. ParparVM is a transpiler that generates C source code matching the given Java bytecode. This means that an Xcode project is generated and compiled on the build servers. It’s as if you hand-coded a native app and is thus future-proof against changes that Apple introduces. For example, Apple migrated to 64-bit, then introduced bitcode, then withdrew bitcode again. ParparVM needed no modifications for any of those changes.

Codename One translates the bytecode to C, which is faster than Swift/Objective-C. The port code that invokes iOS APIs is hand coded in Objective-C

Codename One earlier offered a UWP (Universal Windows Platform) target based on iKVM. That target was discontinued in release 7.0.229 and is preserved as historical context in older documentation and blog posts.

JavaScript build targets translate the bytecode statically with ParparVM, the same translator that generates the C sources for iOS. Cloud builds keep the original TeaVM-based compiler as a compatibility fallback, which you select with the javascript.port build hint. To support the complex UI Codename One uses the HTML5 Canvas API which allows absolute flexibility for building applications.

Desktop builds are packaged on the same cloud machines, a Mac for the macOS installer and a Windows machine for the Windows one. The build originally used javapackager, which was abandoned because it couldn’t package a ZuluFX runtime reliably; installers are now produced directly with third-party packaging tools.

How one set of Java sources reaches each platform
Figure 1. What each target does with the same bytecode
Lightweight architecture

What makes Codename One stand out is the approach it takes to UI: “lightweight architecture.”

Lightweight architecture is the “not so secrete sauce” to Codename One’s portability. Essentially it means all the components/widgets in Codename One are written in Java. Thus their behavior is consistent across all platforms and they’re fully customizable from the developer code as they don’t rely on OS internal semantics. This allows developers to preview the application accurately in the simulators and GUI builders.

One of the big accomplishments in Codename One is its unique ability to embed “heavyweight” widgets into place among the “lightweights.” This is crucial for apps such as Uber where the cars and widgets on top are implemented as Codename One components yet below them, you have the native map component.

Codename One achieves fast performance by drawing using the native gaming APIs of most platforms for example: Metal on iOS. The core technologies behind Codename One are all open source including most of the stuff developed by Codename One itself, for example: ParparVM but also the full library, platform ports, designer tool, device skins etc.

Lightweight Architecture Origin

Lightweight components date back to Smalltalk frameworks, this notion was popularized in the Java world by Swing. Swing was the main source of inspiration to Codename One’s predecessor LWUIT. Many frameworks took this approach over the years including JavaFX and most recently Ionic in the JavaScript world.

Why ParparVM

On iOS, Codename One uses ParparVM which translates Java bytecode to C code and boasts a non-blocking GC. This VM is fully open source in the Codename One git repository. In the past Codename One used XMLVM to generate native code similarly, but the XMLVM solution was too generic for the needs of Codename One. ParparVM boasts a unique architecture of translating code to C (similarly to XMLVM), because of that Codename One is the only solution of its kind that can guarantee future iOS compatibility since the officially supported iOS toolchain is always used instead of undocumented behaviors.

XMLVM could guarantee that as well, but it’s no longer maintained and lacked the API layer support

The key advantages of ParparVM over other approaches are:

  • Truly Native: since code is translated to C rather than directly to ARM or LLVM code, the app is "more native." It uses the official tools and approaches from Apple and can gain from their advancements. For example: bitcode changes or profiling toolchain.

  • Smaller Class Library: ParparVM includes a small segment of the full JavaAPI’s resulting in final binaries that are smaller than the alternatives by orders of size. This maps directly to performance and memory overhead.

  • Simple and Extensible: to work with ParparVM you need a basic understanding of C. Unlike other tools that require deep understanding of ARM assembly and LLVM bitcode. This is crucial for the fast-moving world of mobile development, as Apple changes things left and right, you need a more agile VM.

Historical windows ports

Codename One experimented with many Windows ports over the years, including the legacy Windows Phone target and a later UWP (Universal Windows Platform) target based on iKVM.

The UWP target was discontinued in release 7.0.229 and is no longer part of the supported build targets. Older references to it in historical material are retained for archival context.
JavaScript port

The JavaScript port of Codename One uses ParparVM to translate Java bytecode into JavaScript. Cloud builds retain the original TeaVM-based builder as a compatibility fallback, selected with the public javascript.port=teavm build hint.

The JavaScript port allows unmodified Codename One applications to run within a desktop or mobile browser. The port itself is based on the HTML5 Canvas API, which provides a pixel-perfect implementation of the Codename One API.

The JavaScript port is available to all Codename One users.
Desktop and Android

The other ports of Codename One use the VMs available on the host machines and environments to execute the runtime. Historically, Retrolambda was used to provide Java 8 language features portably.

The Android port uses the native Android tools, including the Gradle build environment, in the latest versions.

The desktop port creates a standard Java SE application, which is packaged with the JRE and an installer.

The Desktop port is available to pro grade subscribers of Codename One

1.2. History

LWUIT App Screenshot
Figure 2. LWUIT App Screenshot circa 2007

Codename One was started by Chen Fishbein and Shai Almog who authored the Open Source LWUIT project at Sun Microsystems (circa 2007). The LWUIT project aimed to solve the fragmentation within J2ME/Blackberry devices by creating a higher standard of user interface than the common baseline at the time. LWUIT received critical acclaim and traction within many industries but was limited by the declining feature phone market. It was forked by many companies including Nokia. It was used as the base standard for DTV in Brazil. Another fork has brought a LWUIT into high-end cars from Toyota and other companies. This fork later adapted Codename One as well.

In 2012 Shai and Chen formed Codename One as they left Oracle. The project has taken many of the basic concepts developed within the LWUIT project and adapted them to the smartphone world which is still experiencing similar issues to the device fragmentation of the old J2ME phones.

1.3. Core concepts of mobile programming

Before you proceed, this section explains some universal core concepts of mobile programming that might not be intuitive. These are universal concepts that apply to mobile programming regardless of the tools you’re using.

You can skip this section if you feel you’re familiar enough with the core problems/issues in mobile app development.

1.3.1. Density

Density is also known as DPI (Dots Per Inch) or PPI (pixels or points per inch). Density is confusing, unintuitive and might collide with common sense. For example, an iPhone 7 plus has a resolution of 1080x1920 pixels and a PPI of 401 for a 5-inch screen. But, an iPad 4 has 1536x2048 pixels with a PPI of 264 on a 9.7 inch screen…​ Smaller devices can have higher resolutions!

As the following figure shows, if a Pixel 2 XL had pixels the size of an iPad, it would have been twice the size of that iPad. While in reality, it’s half the height of the iPad!

Device Density vs Resolution
Figure 3. Device Density vs. Resolution

Differences in density can be extreme. A second generation iPad has 132 PPI, where modern phones have PPI that’s over 600 dpi.

Low resolution images on high PPI devices will look either small or pixelated. High resolution images on low PPI devices will look huge, overscaled (artifacts) and will consume too much memory.

How the Same Image Looks in Different Devices
Figure 4. How the Same Image Looks in Different Devices

The exact same image will look different on each device, sometimes to a comical effect. One of the solutions for this problem is multi-images. All OS’s support the ability to define different images for various densities. Chapter 2 discusses multi-images later in detail.

This also highlights the need for working with measurements other than pixels. Codename One supports millimeters (or dips) as a unit of measurement. This is highly convenient and is a better representation of size when dealing with mobile devices.

However, there is a bigger conceptual issue involved. You need to build a UI that adapts to the wide differences in form factors. You might have fewer pixels on an iPad, but because of its physical size, you would expect the app to cram more information into that space so the app won’t feel like a blown-up phone application. Many strategies to address that, but one of the first steps is in the layout managers.

Chapter 2 discusses the layout managers in depth, but the core concept is that they decide where a UI element is placed based on generic logic. That way, the user interface can adapt automatically to the huge variance in display size and density.

1.3.2. Touch interface

The fact that mobile devices use a touch interface today isn’t news…​ However, the implications of that aren’t obvious to some developers.

UI elements need to be finger sized and spaced. Otherwise, you risk the “fat finger” effect. That means spacing should be in millimeters and not in pixels due to device density.

Scrolling poses another challenge in touch-based interfaces. In desktop applications, it’s common to nest scrollable items. For example, in touch interfaces, the scrolling gesture doesn’t allow such a nuance. Furthermore, scrolling on both the horizontal and vertical axis (side scrolling) can be inconvenient in touch-based interfaces.

1.3.3. Device fragmentation

Some developers single out this wide range of resolutions and densities as “device fragmentation.” While it does contribute to development complexity, it isn’t a challenging problem to overcome.

Densities aren’t the cause of device fragmentation. Device fragmentation is caused by many OS versions with different behaviors. This is clear on Android and relates to the slow rollout of Android vendor versions compared to Google rollout. A new release reaches only a small fraction of devices in its first year, and handsets several major versions behind stay in circulation long after their vendor stops shipping updates for them.

This makes QA difficult as the disparity between these versions is pretty big. It’s hard to get all device manufacturers aligned, so this problem will probably remain in the foreseeable future despite everything.

1.3.4. Performance

Besides the obvious need for performance and smooth animation within a mobile app, there are a couple of performance related issues that might not be intuitive to new developers: size and power.

App size

Apps are installed and managed through stores. This poses some restrictions about what an app can do. However, it also creates a huge opportunity. Stores manage automatic update and to some degree the marketing/monetization of the app.

A good mobile app is updated once a month and sometimes even once a week. Since the app downloads automatically from the store, this can be a huge benefit:

  • Existing users are reminded of the app and get new features instantly

  • New users notice the app featured on a “what’s new” list

If an app is big, it might not update over a cellular network connection. Google and Apple have restrictions on automatic updates over cellular networks to preserve battery life and data plans. A large app might negatively impact users perception of the app and trigger uninstalls for example, when a phone is low on available space.

Power drain

Desktop developers think about power usage within their apps. In mobile development, this is a crucial concept. Modern device OSes have tools that highlight misbehaving applications, and this can lead to bad reviews.

Code that loops forever while waiting for input will block the CPU from sleeping and drain the battery.

Worse. Mobile OSes kill applications that drain the battery. If the app is draining the battery and is minimized, (for example, during an incoming call) the app could be killed. This will impact app performance and usability.

1.3.5. Sandbox and permissions

Apps installed on the device are "sandboxed" to a specific area so they won’t harm the device or its functionality. The filesystem of mobile applications is restricted so one application can’t access the files of another application. Things that most developers take for granted on the desktop such as a "file picker" or accessing the image folder don’t work on devices!

This means that when your application works on a file, it belongs to your application. To share the file with a different application, you need to ask the operating system to do that for you.

Furthermore, some features require a "permission" prompt and sometimes require special flags in system files. Apps need to request permission to use sensitive capabilities, for example, Camera, Contacts etc.
Historically, Android developers declared required permissions for an app and the user was prompted with permissions during installation. Android 6 adopted the approach used by iOS of prompting the user for permission when accessing a feature.

This means that in runtime a user might revoke a permission. A good example for an Uber app is the location permission. If a user revokes that permission, the app might lose its location.

1.4. Installing Codename One

Codename One supports JDK 11 through 25 for running the simulator and the desktop ("Run as desktop app") target. Eclipse Temurin (https://adoptium.net) is the easiest way to install a supported JDK.

Codename One projects are built with Maven. Typical Maven targets such as package, clean and install work out of the box, but the Codename One integrations that ship with each IDE provide dedicated Run and Build actions for a smoother workflow.

To create a new Codename One project visit https://www.codenameone.com/initializr/ and generate a starter project, or run the Codename One Application Project Archetype (cn1app-archetype) directly on the command line:

mvn archetype:generate \
  -DarchetypeGroupId=com.codenameone \
  -DarchetypeArtifactId=cn1app-archetype \
  -DarchetypeVersion=LATEST \
  -DgroupId=YOUR_GROUP_ID \
  -DartifactId=YOUR_ARTIFACT_ID \
  -Dversion=1.0-SNAPSHOT \
  -DmainName=YOUR_MAIN_NAME \
  -DinteractiveMode=false

This command generates a project in the current directory. The folder name matches the artifactId value. For example, specifying -DartifactId=myapp produces a project inside a new myapp directory.

Import the generated Maven project into your preferred IDE and use the Codename One Run in Simulator task from the IDE toolbar or Run/Debug buttons:

  • IntelliJ IDEA: use File > Open on the project directory, then choose the Codename One Run in Simulator action from the toolbar or standard Run/Debug controls.

  • NetBeans: use File > Open Project, select the generated Maven project, and rely on the Codename One toolbar actions to run and debug the simulator.

  • VS Code: install the Java and Codename One extensions, open the folder, and trigger the Run in Simulator task from the command palette or the Run/Debug buttons.

  • Eclipse: use File > Import > Existing Maven Projects, then use the Codename One launch shortcuts provided by the plugin for simulator and build tasks.

  • Command line: invoke Maven goals directly whenever you need to integrate with CI/CD pipelines or scripting.

For deeper coverage of the Maven goals, project structure, and automation tasks, continue with Chapter 2, Maven Project Workflow.

Arbitrary Maven dependencies probably won’t work for Codename One. Many dependencies assume a full JDK which Codename One can’t provide and they often assume functionality that might not be available for example: reflection, Spring, etc.
Legacy onboarding resources

Legacy Ant-based project instructions remain available for teams maintaining older codebases. New projects should follow the Maven workflows described in this guide.

1.4.1. Important notes for new projects

Before you get to the code there are few important things you need to understand about Codename One applications.

  • App Name - This is the name of the app and the main class, it’s important to get this right as it’s hard to change this value later

  • Package Name - it’s crucial you get this value right. Besides the difficulty of changing this after the fact, once an app is submitted to iTunes/Google Play with a specific package name this can’t be changed! See the sidebar Picking a Package Name.

  • Theme - Codename One ships with various built-in themes; for simplicity recommend Native as it’s a minimal starting point

Picking a Package Name

Apple, Google and Microsoft identify applications based on their package names. If you use a domain that you don’t own it’s possible that someone else will use that domain and collide with you. In fact some developers left the default com.mycompany domain in place all the way into production sometimes.

This can cause difficulties when submitting to Apple, Google, or Microsoft. Submitting to one of them is no guarantee of success when submitting to another.

To come up with the right package name use a reverse domain notation. If your website is goodstuff.co.uk your package name should start with uk.co.goodstuff. Follow these guidelines for package names:

  • Lower Case - some OSes are case-sensitive and handling a mistake in case is painful. The Java convention is lower case; stick to that

  • Avoid Dash and Underscore - You can’t use a dash character (-) for a package name in Java. Underscore (_) doesn’t work for iOS. If you want more than one word just use a deeper package e.g.: com.mydomain.deeper.meaningful.name

  • Obey Java Rules - A package name can’t start with a number so you can’t use com.mydomain.1sler. You should avoid using Java keywords like this, if etc.

  • Avoid Top Level - instead of using uk.co.goodstuff use uk.co.goodstuff.myapp. That would allow you to have more than one app on a domain

1.4.2. Runtime

Once Maven is set up you can run the HelloWorld application by selecting the Codename One Run in Simulator task from the IDE run menu. The Codename One simulator launches and you can use its menus to control and inspect details related to the device. You can rotate it, determine its location in the world, monitor networking calls etc.

With the Skins menu you can download device skins to see how your app will look on different devices.

Some skins are bigger than the screen size, uncheck the Scrollable flag in the Simulator menu to handle them more effectively

Use your IDEs Debug button with the Run in Simulator task to launch the simulator under the debugger.

Simulator vs. Emulator

Codename One ships with a simulator similarly to the iOS toolchain which also has a simulator. Android ships with an emulator. Emulators go further. They create a virtual machine that’s compatible with the device CPU and then boot the full mobile OS within that environment. This provides a proper runtime environment but is slow.

Simulators rely on the fact that OSes are similar and so they leave the low-level details in place and just map the API behavior. Since Codename One relies on Java it can start simulating on top of the virtual machine on the desktop. That provides several advantages including fast development cycles and full support for all the development tools/debuggers you can use on the desktop.

Emulators make sense for developers who want to build OS level services for example, screensavers or low-level services. Standard applications are better served by simulators.

1.4.3. The source code of the hello world app

After clicking finish in the new project wizard you have a HelloWorld project with a few default settings. The following sections break the class down to small pieces and explain each piece starting with the enclosing class:

Listing 1. HelloWorld Class
public class HelloWorld extends Lifecycle {                             (1)

    @Override
    public void runApp() {                                              (2)
        Form hi = new Form("Hi World", BoxLayout.y());                  (3)
        Button helloButton = new Button("Hello World");
        hi.add(helloButton);
        helloButton.addActionListener(e -> hello());
        hi.getToolbar().addMaterialCommandToSideMenu("Hello Command",
                FontImage.MATERIAL_CHECK, 4, e -> hello());             (4)
        hi.show();
    }

    private void hello() {
        Dialog.show("Hello Codename One", "Welcome to Codename One", "OK", null);
    }
}
1This is the main class and the entry point to the app. It has no main method: the platform calls into Lifecycle, which calls you back.
2runApp() is where the app builds its first screen. Lifecycle calls it from start(), so this is the one method a new project overrides.
3Form is the “top level” UI element in Codename One. Only one is shown at a time and everything on the screen is a child of it. BoxLayout.y() stacks the children from the top down, and a theme decides how they look.
4The Toolbar carries the title bar and the side menu. The generated project puts the same action in both places so there is an example of each.

The four platform callbacks the Application Lifecycle Sidebar describes are already implemented for you by Lifecycle, which is why the generated class carries none of them:

  • init(Object) sets the network thread count, installs the theme, turns on the global Toolbar, binds crash protection through Log.bindCrashProtection and registers a network error listener, in that order.

  • start() calls runApp() on a cold start. On a warm start it re-shows the Form the user was looking at when the app was suspended, so returning to an app lands the user back where they were.

  • stop() remembers that Form, disposing a Dialog first so the app doesn’t come back to a modal.

  • destroy() does nothing by default.

Some complex ideas appear within this short snippet that this chapter addresses later when talking about layout. The gist of it’s that you create and show a Form, the top level UI element that takes over the whole screen. You add UI elements to it, here a Button that opens a Dialog when tapped, and the BoxLayout arranges them from top to bottom. The same action is attached to the side menu through the Toolbar, so the starter shows both ways of triggering one piece of code.

Application Lifecycle

A few years ago Romain Guy (a senior Google Android engineer) was on stage at the Google IO conference. He asked for a show of hands of people who understand the Activity lifecycle (Activity is like a Codename One main class). He then proceeded to jokingly call the audience members who lifted their hands “liars” claiming that after all his years in Google he still doesn’t understand it…​

Lifecycle seems simple on the surface but hides a lot of nuance. Android’s lifecycle is ridiculously complex. Codename One tries to simplify this and also make it portable. Sometimes complexity leaks out and the nuances can be difficult to deal with.

Explained an application has three states:

  • Foreground - it’s running and in the foreground which means the user can physically interact with the app

  • Suspended - the app isn’t in the foreground, it’s either paused or has a background process running

  • Not Running - the app was never launched, was killed or crashed

The lifecycle is the process of transitioning between these 3 states and the callbacks invoked when such a transition occurs. The first time you launch the app you start from a “Cold Start” (Not Running State) but on later launches the app is started from the "Warm Start" (Suspended State).

Codename One Application Lifecycle
Figure 5. Codename One Application Lifecycle

Codename One has four standard callback methods in the lifecycle API:

  • init(Object) - is invoked when the app is first launched from a Not Running state.

  • start() - is invoked for two separate cases. After start() is finished the app transitions to the Foreground state.

    • Following init(Object) in case of a cold start. Cold start refers to starting the app from a Not Running state.

    • When the app is restored from Suspended state. In this case init(Object) isn’t invoked

  • stop() - is invoked when the app is minimized for example, when switching to a different app. After stop() is finished the app transitions to the Suspended state.

  • destroy() - is invoked when the app is destroyed for example, killed by a user in the task manager. After destroy() is finished the app is no longer running hence it’s in the Not Running state.

destroy() is optional there is no guarantee that it will be invoked. It should be used only as a last resort

Override one when you need to run code at that point. What the super call protects differs by callback: in init it’s the whole list above, in start it’s the only thing that puts a Form on screen, and in stop it’s the record of which Form to come back to. destroy is empty, so super there is optional:

Listing 2. Overriding a lifecycle callback
public class HelloWorld extends Lifecycle {
    private TextArea editor;

    @Override
    public void init(Object context) {
        super.init(context);                                            (1)
        Log.p("app starting");
    }

    @Override
    public void stop() {
        saveDraft();                                                    (2)
        super.stop();
    }

    @Override
    public void runApp() {
        editor = new TextArea(Preferences.get("draft", ""));            (3)
        Form hi = new Form("Hi World", BoxLayout.y());
        hi.add(editor);
        hi.show();
    }

    private void saveDraft() {
        Preferences.set("draft", editor.getText());
    }
}
1Without this none of the five things init does happen, most visibly the theme, so the app comes up unstyled.
2Called as the app is suspended, which is the moment to persist anything the user would hate to lose.
3The other half of that: runApp puts the saved draft back, so the pair survives the app being killed while suspended.

That’s it. You should now have a general sense of the code. It’s time to run on the device.

1.4.4. Building and deploying on devices

Codename One Settings
Figure 6. Codename One Settings

Use the standalone Codename One Settings editor to configure the application title, version, package, icon, build hints, and extensions. Launch it from the Maven project root:

mvn cn1:settings

Use the standalone Certificate Wizard for signing assets. Monitor Codename One Cloud builds and subscription information on the Codename One website.

Signing/Certificates

All the modern mobile platforms require signed applications but they all take radically different approaches when implementing it.

Signing is a process that marks your final application for the device with a special value. This value (signature) is a value that you can generate based on the content of the application and your certificate. Effectively it guarantees the app came from you. This blocks a 3rd party from signing their apps and posing as you to the App Store or to the user. It’s a crucial security layer.

A certificate is the tool you use for signing. Think of it as a mathematical rubber stamp that generates a different value each time. Unlike a rubber stamp a signature can’t be forged!

Signing on Android
Backup your Android certificate and save its password!
If you lose your Android certificate you won’t be able to update your app

Android uses a self-signed certificate approach. You can generate a certificate by describing who you’re and picking a password!

Anyone can do that. For example, once a certificate is published it can’t be replaced…​

If this wasn’t the case someone else could push an “upgrade” to your app. Once an app is submitted with a certificate to Google Play this app can’t be updated with any other certificate.

With that in mind generating an Android certificate is trivial.

The following chart illustrates a process that’s identical on all IDEs
android certificate generator
Figure 7. Process of Certificate Generation for Android
Your certificate will generate into the file Keychain.ks in your home directory
Make sure to back that up and the password as losing these can have dire consequences
Should You Use a Different Certificate for Each App?

In theory yes. In practice it’s a pain…​ Keeping multiple certificates and managing them is a pain so you often just use one.

The drawback of this approach occurs when you’re building an app for someone else or want to sell the app. Giving away your certificate is akin to giving away your house keys. It makes sense to have separate certificates for each app.

Signing and provisioning iOS

Code signing for iOS relies on Apple as the certificate authority. This is something that doesn’t exist on Android. iOS also requires provisioning as part of the certificate process and separates the process for development/release.

First, the good news:

  • Losing an iOS certificate is no big deal - in fact you revoke them often with no impact on shipping apps

  • Codename One has a wizard that hides most of the pain related to iOS signing

In iOS Apple issues the certificates for your applications. That way the certificate is trusted by Apple and is assigned to your Apple iOS developer account. One important caveat applies: You need an iOS Developer Account and Apple charges a 99USD Annual fee for that.

The fee and the requirement have been part of the iOS developer program since it was introduced. Check Apple’s developer site for the current price.

Apple also requires a “provisioning profile” which is a special file bound to your certificate and app. This file describes some details about the app to the iOS installation process. One of the details it includes during development is the list of permitted devices.

The 4 files Required for iOS Signing and Provisioning
Figure 8. The Four Files Required for iOS Signing and Provisioning

You need 4 files for signing. Two certificates and two provisioning profiles:

  1. Production: The production certificate/provisioning pair is used for builds that are uploaded to iTunes

  2. Development: The development certificate/provisioning is used to install on your development devices

The standalone Certificate Wizard can automatically create these files and configure the current Maven project.

Run the wizard from the project directory:

mvn cn1:certificatewizard

After storing an App Store Connect API key, click Auto Setup in the toolbar. The wizard reads the project package and display name, creates or reuses the Bundle ID with push enabled, creates/reuses development and App Store signing assets, and writes the debug/release signing settings back into codenameone_settings.properties.

Certificate wizard overview with mocked signing assets
Figure 9. Certificate wizard overview with mocked signing assets
Certificate wizard profiles screen with mocked values
Figure 10. Certificate wizard profiles screen with mocked values

If you have more than one project you should use the same iOS P12 certificate files in all the projects and regenerate the provisioning. In this situation the Certificate Wizard asks you if you want to revoke the existing certificate which you shouldn’t revoke in such a case. You can update the provisioning profile in Apple’s iOS developer website.

One important aspect of provisioning on iOS is the device list in the provisioning step. Apple allows you to install the app on 100 devices during development. This blocks developers from skipping the App Store altogether. It’s important you list the correct UDID for the device in the list otherwise install will fail.

Many apps and tools offer the UDID of the device, but they aren’t necessarily reliable and might give a fake number!

The UDID section of the signing chapter covers the reliable ways to read that value.

Ad hoc provisioning allows 1000 beta testers for your application but it’s a more complex process that you won’t discuss here although it’s supported by Codename One
Build and install

Before you continue with the build you should sign up at https://www.codenameone.com/build-server.html where you can soon follow the progress of your builds. You need a Codename One account to build for the device.

Now that you have certificates, a device build is a single Maven goal. From the project’s root directory run mvn cn1:buildAndroid for Android, or mvn cn1:buildIos for an iOS debug build. Each one packages the app, sends it to the Codename One build servers and reports where the result lands.

Run these from the root, not from a module. The build goals skip any project that isn’t the execution root, so mvn -pl common cn1:buildAndroid prints “Skipping execution for non-root project” and then reports success without building anything.
The first time you send a build you will be prompted for the email and password you provided when signing up for Codename One

Once you send a build you should see the results in the build server page:

Build Results
Figure 11. Build Results
On iOS make sure you use Safari when installing, as 3rd party browsers might have issues

Once you go through those steps you should have the HelloWorld app running on your device. This process is non-trivial when starting so if you run into difficulties don’t despair and seek help at the discussion forum (https://www.codenameone.com/discussion-forum/) or stack overflow (https://stackoverflow.com/questions/tagged/codenameone). Once you go through signing and installation, it becomes easier.

You can also install the application either by emailing the installation link to your account (using the e-mail Link button)

You can also download the binaries to upload them to the appstores.

1.5. Kotlin

Codename One started before Kotlin became public. Kotlin has since shown itself as an interesting option for developers within the Android community. With that in mind, Codename One added support for Kotlin.

To use Kotlin with Codename One you can create a kotlin directory next to the java directory under the common/src/main directory. Kotlin code that resides there can work as usual and interact with the Java code.

Please notice the following:

  • Don’t use the project conversion tools or accept the warning that the project isn’t a Kotlin project. You do your own build process

  • Warnings and errors aren’t listed and builds that claim to have errors might pass

1.5.1. Hello Kotlin

Due to the way Kotlin works you can create a regular Java project and convert sources to Kotlin. You can mix Java and Kotlin code without a problem and Codename One would "work."

The Java source it converts from is the class shown in the walkthrough above: a Lifecycle subclass overriding runApp().

When you select that file and select the menu option Code → Convert Java file to Kotlin File you should get a familiar structure. The problem is that there are two bugs in the automatic conversion…​ That’s the code for Kotlin behaves differently from standard Java.

The first problem is that Kotlin classes are final unless declared otherwise so you need to add the open keyword before the class declaration.

This is essential as the build server will fail with weird errors related to instanceof.

This applies to the main class of the project, other classes in Codename One can remain final

The second problem only bites if you override init(Object), which the generated class doesn’t. Kotlin treats arguments as non-null by default, and the context passed to init can be null, so an override has to accept it as fun init(context: Any?) or it fails with an exception.

Once all that’s in place Kotlin should work. This should be possible for more JVM languages in the future.

2. Maven Project Workflow

Codename One uses Maven as the standard way to create, run, and maintain applications. This chapter consolidates the workflow guidance that used to live in the standalone Maven manual so the developer guide provides a single source of truth for building apps, updating projects, and managing add-ons.

2.1. Introduction

Codename One uses Maven as its primary build tool. This guide aims to be the definitive source of information for this project structure.

2.1.1. Conventions

The instructions throughout this chapter provide parallel guidance for the supported development environments. Each subsection heading identifies the target tooling so you can follow the directions that match your workflow:

  • Command Line (CLI): Focused on running Maven from a terminal. The commands use a Unix-style shell syntax; adapt the examples for Windows when necessary.

  • IntelliJ IDEA: Step-by-step directions for working inside IntelliJ.

  • NetBeans: Equivalent instructions tailored to NetBeans.

  • Eclipse: Maven-based guidance for Eclipse users.

When you reach environment-specific sections later in the guide, follow the subsection corresponding to your preferred tools.

2.2. Getting started

2.2.1. Prerequisites

Codename One supports JDK 11 through 25 for running the simulator and the "Run as desktop app" target. Eclipse Temurin is the easiest source of a supported JDK on macOS, Windows, and Linux.

After installing the JDK, point JAVA_HOME at it and confirm with:

java -version
mvn -v

Both should report Java 11 or newer. The Codename One Maven plugin checks the runtime JDK version when you invoke mvn cn1:run or mvn cn1:debug and fails fast with a friendly message if it’s older than 11. Build-only goals (such as -Pexecutable-jar) still work on older JDKs.

2.2.2. Creating a new project

Codename One initializr

The easiest way to create a new project is to use the Codename One initializr.

codenameone initializr screenshot

This tool will allow you to choose from a growing selection of project templates, and download a starter project that you can open in your preferred IDE (IntelliJ IDEA, NetBeans, etc.), or build directly on the command-line using Maven.

The initializr also offers Gradle as the build tool. A Gradle project is a single directory with a one-line settings file, and it gets native or backend directories only once it needs them. See Chapter 3, Gradle project workflow for when to choose it and how it maps to the Maven workflow in this chapter.

The following tutorials provide step-by-step instructions for getting started with bare-bones app templates. Those tutorials are a better starting place for Codename One development than this manual, as they’re written in tutorial form.

Java Getting Started Tutorial:

Kotlin Getting Started Tutorial:

Generating a new project from the command-line
Configuring the Codename One repository

Codename One releases are published to the Codename One Maven repository at https://repo.codenameone.com/maven2, not to Maven Central. A generated project declares that repository in its own pom.xml, so once you have a project nothing further is needed.

The commands in this section run before there is a project, so Maven has no pom.xml to read the repository from and searches only Maven Central. Central still serves every version published before the move, so these commands keep working, but they can’t see a release published after it. Add the repository to your Maven settings once, in ~/.m2/settings.xml (%USERPROFILE%\.m2\settings.xml on Windows), and they can:

<settings>
    <profiles>
        <profile>
            <id>codenameone</id>
            <repositories>
                <repository>
                    <id>codenameone</id>
                    <url>https://repo.codenameone.com/maven2</url>
                    <releases><enabled>true</enabled></releases>
                    <snapshots><enabled>false</enabled></snapshots>
                </repository>
            </repositories>
            <pluginRepositories>
                <pluginRepository>
                    <id>codenameone-plugins</id>
                    <url>https://repo.codenameone.com/maven2</url>
                    <releases><enabled>true</enabled></releases>
                    <snapshots><enabled>false</enabled></snapshots>
                </pluginRepository>
            </pluginRepositories>
        </profile>
    </profiles>
    <activeProfiles>
        <activeProfile>codenameone</activeProfile>
    </activeProfiles>
</settings>

Both lists are needed. Maven resolves ordinary dependencies through <repositories> and build plugins through <pluginRepositories>, and the commands below invoke the Codename One plugin directly, which is the second list.

Codename One Initializr needs none of this. It builds the project on the server and hands you one that already declares the repository.
Bare-bones Java project

If you prefer to generate your projects directly on the command-line, you can use the Section A.1, “Codename One application project archetype (cn1app-archetype)” to generate the project directly on the command-line:

mvn archetype:generate \
  -DarchetypeGroupId=com.codenameone \
  -DarchetypeArtifactId=cn1app-archetype \
  -DarchetypeVersion=LATEST \
  -DgroupId=YOUR_GROUP_ID \
  -DartifactId=YOUR_ARTIFACT_ID \
  -Dversion=1.0-SNAPSHOT \
  -DmainName=YOUR_MAIN_NAME \
  -DinteractiveMode=false

This will generate a project in the current directory. The project’s directory will have the same name as the artifact ID you specified here. For example, If your command had -DartifactId=myapp, then the project will be located in a newly created directory named "myapp."

If you haven’t used Maven archetypes before, this snippet may be confusing. See Introduction to Maven Archetypes to get up to speed.
-DarchetypeVersion=LATEST resolves against whichever repositories Maven knows about. Without the settings from Section 2.2.2.2.1, “Configuring the Codename One repository”, Maven Central is the only one, so the newest archetype it can offer is the last one published before the move. The generated project is still correct — it declares the Codename One repository, so mvn cn1:update moves it to a current release — but configuring the repository first gets you there directly.

This command uses the Section A.1, “Codename One application project archetype (cn1app-archetype)” which has the following Maven coordinates:

<dependency>
  <groupId>com.codenameone</groupId>
  <artifactId>cn1app-archetype</artifactId>
  <version>LATEST</version>
  <type>maven-archetype</type>
</dependency>

This archetype generates a bare-bones Java project (the same one described in Getting Started with the Bare-bones Java App Template).

View the source of the cn1app-archetype project here.

You can learn more about using the archetype in the appendix.

Project templates

The bare-bones Kotlin App project template is an alternative starter project that uses Kotlin as the primary language instead of Java. It’s built on the cn1app-archetype at its core, but it includes some more configuration settings and sources to change the template. You can use such templates as starter projects by using the generate-app-project goal of the Codename One Maven plugin.

Here is an example which generates a project based on the bare-bones Kotlin template:

mvn com.codenameone:codenameone-maven-plugin:{cn1-plugin-release-version}:generate-app-project \
  -DarchetypeGroupId=$archetypeGroupId \
  -DarchetypeArtifactId=$archetypeArtifactId \
  -DarchetypeVersion=$archetypeVersion \
  -DartifactId=$artifactId \
  -DgroupId=$groupId \
  -Dversion=$version \
  -DmainName=$mainName \
  -DinteractiveMode=false \
  -DsourceProject=/path/to/kotlin-example-app
This command is formatted for the bash prompt (for example, Linux or Mac). It will work on Windows also if you use bash. If you’re on Windows and are using PowerShell or the regular command prompt, then you’ll need to modify the command slightly. In particular, the entire command would need to be on a single line. (Remove the '\' at the end of each line, and merge lines together, with space between the command-line flags)

Like the archetype:generate goal, this will create the project in a directory named after your specified artifact ID. For example, If your command included -DartifactId=myapp, then the project would be in a newly created directory named "myapp."

Some notes here:

  1. The com.codenameone:codenameone-maven-plugin:7.0.210:generate-app-project argument is the fully qualified goal name for the generate-app-project. This is necessary since you aren’t running this goal in the context of any existing project. You should adjust the version number (7.0.210) to reflect the latest available Codename One version, listed as <release> in the repository metadata. Because there is no project here, Maven finds that version only if you have configured the Codename One repository in your Maven settings.

  2. The archetypeGroupId, archetypeArtifactId, and archetypeVersion parameters are the same as when using the archetype:generate goal, and they will (almost) always refer to the Section A.1, “Codename One application project archetype (cn1app-archetype)”.

  3. The groupId, artifactId, and version work the same as for the archetype:generate goal. That’s, that they specify the coordinates for your newly created project.

  4. The mainName specifies the Main class name for your app. This is the class name, and shouldn’t include the full package. For example, MyApp, not "com.example.MyApp"

  5. The sourceProject property is the path to the "template" project. In this case, you will assume that you’ve cloned the bare-bones Kotlin project template repository at /path/to/kotlin-example-app.

A project template isn’t much different than a regular project. The template can be either a legacy Ant project, or a new Maven project. In fact, this goal is the same one you would use to migrate a legacy Ant project to use the new Maven project structure.

See Section 2.4, “Creating project templates” for instructions on building your own project templates.

2.2.3. Migrating an existing project

If you have an existing Codename One application project that uses the old Ant project structure, you can use the generate-app-project goal to migrate the project over to maven. This goal doesn’t make any changes to the Ant project. It creates a new Maven project and copies over all the project sources and libraries, reorganized to fit the new project structure.

A minimal invocation of this goal would look like:

# Specify your the version of the codenameone-maven-plugin.
# Find the latest version at
# https://search.maven.org/search?q=a:codenameone-maven-plugin
CN1VERSION={cn1-plugin-release-version}
mvn com.codenameone:codenameone-maven-plugin:$CN1VERSION:generate-app-project \
  -DgroupId=YOUR_GROUP_ID \
  -DartifactId=YOUR_ARTIFACT_ID \
  -DsourceProject=/path/to/your/project \
  -Dcn1Version=$CN1VERSION
This command is formatted for the bash prompt (for example, Linux or Mac). It will work on Windows also if you use bash. If you’re on Windows and are using PowerShell or the regular command prompt, then you’ll need to modify the command slightly. In particular, the entire command would need to be on a single line. (Remove the '\' at the end of each line, and merge lines together, with space between the command-line flags)

This will generate the new project in the current directory inside a folder named after the artifactId parameter.

After building the project, try running it to make sure that the migration worked. For example, Assuming that your artifactId was myapp:

Command line
cd myapp
./run.sh
On Windows it would be run.bat instead of run.sh.

If All goes well, your app should open in the Codename One simulator.

IntelliJ IDEA

Open the myapp folder in IntelliJ. Then press the "Run" intellij run icon button in the upper right of the toolbar.

If All goes well, your app should open in the Codename One simulator.

NetBeans
Before opening the project in NetBeans, be sure to copy the files in the tools/netbeans directory into the root directory. These are necessary for NetBeans to run, build, and debug the project.

Open the myapp folder as a project in NetBeans. Then press the "Run" netbeans run icon button on the toolbar.

If all goes well it should open in the Codename One simulator.

Eclipse IDE

Open Eclipse, and select "File" > "Import…​"

eclipse file menu import

In the Import dialog, expand Maven, select Existing Maven Projects, and press Next.

eclipse import dialog

In the next panel, press the Browse button, and, in the file dialog, select the "myapp" directory, and press Next.

eclipse import browse dialog

The next panel should look like the one below. Make sure all the projects are "checked," and press Finish.

eclipse import list projects dialog

Almost there, but not quite…​

Next you need to import the Eclipse launch configurations located inside the tools/eclipse directory.

Select File > Import…​ again, but this time, in the Import dialog, select Run/Debug > Launch Configurations and click Next.

eclipse import launch configurations dialog

In the next panel, press Browse…​ then select the tools/eclipse directory.

eclipse launch configurations file dialog

Then check the eclipse option, and press Finish

eclipse import launch configurations finish

The "Run" button menu should now include options for all the major build targets. You can see them by pressing on the Run button in the toolbar:

eclipse run button dropdown

Select the MyApp - Run Simulator option from this menu.

If all goes well it should open in the Codename One simulator.

Example: Migrating kitchen sink app

Consider a concrete example, now. Download the KitchenSink Ant project from here and extract it.

The following is a bash script that uses curl to download this project as a zip file, and then converts it to a fully functional Maven project:

CN1_VERSION={cn1-plugin-release-version}
curl -L https://github.com/codenameone/KitchenSink/archive/v1.0-cn7.0.11.zip > master.zip
unzip master.zip
rm master.zip
mvn com.codenameone:codenameone-maven-plugin:${CN1_VERSION}:generate-app-project \
  -DarchetypeGroupId=com.codename1 \
  -DarchetypeArtifactId=cn1app-archetype \
  -DarchetypeVersion=${CN1_VERSION} \
  -DartifactId=kitchensink \
  -DgroupId=com.example \
  -Dversion=1.0-SNAPSHOT \
  -DinteractiveMode=false \
  -DsourceProject=KitchenSink-1.0-cn7.0.11
This command is formatted for the bash prompt (for example, Linux or Mac). It will work on Windows also if you use bash. If you’re on Windows and are using PowerShell or the regular command prompt, then you’ll need to modify the command slightly. In particular, the entire command would need to be on a single line. (Remove the '\' at the end of each line, and merge lines together, with space between the command-line flags)

This will generate the maven project in a directory named "kitchensink" in the current working directory because of the -DartifactId=kitchensink directory.

2.2.4. Adding project dependencies

For the easiest and recommended approach to adding dependencies to your project, skip to Section 2.2.4.5, “Managing add-ons in Codename One Settings”.

One of the reasons to use Maven as the build tool is because it makes the management of project dependencies almost trivial. If the library you want to add is on Maven central, then you can copy and paste its <dependency> snippet into your pom.xml file and you’re good to go. Maven does the rest.

See Introduction to the Dependency Mechanism on the Maven website for a gentle, but comprehensive introduction to Maven dependencies.

With Codename One projects, there are a few caveats (see Section 2.2.4.4, “The compliance check”), and a few added niceties that make it easier to find and install add-on libraries in your project (see Section 2.2.4.5, “Managing add-ons in Codename One Settings”).

Which pom.xml to add the <dependency> snippet to

Suppose you have a Maven <dependency> snippet that you’ve copied from Maven central, and it’s burning a hole in your clipboard while you’re trying to figure out where to paste it into your project. Codename One application projects are multi-module projects, so they have more than one pom.xml file: the root one, the common module’s, and one per platform module the project has. A project generated with the defaults has no platform modules (see Section A.1.1, “Projects without platform modules”).

Question: Which pom.xml file should you paste the snippet into?

Answer: common/pom.xml (almost always).

The "common" module is where all your Codename One application resides. It houses your Java and Kotlin files, your CSS files, your GUI builder files, your Codename One configuration files (that is, codenameone_settings.properties). Pretty much everything. The things you’d place in the other modules (for example, Java SE, ios, etc.) are your platform-specific native interface implementations; And in many applications you won’t need any of that.

When adding dependencies into your app, you’ll therefore almost always place them inside the pom.xml file for the "common" module.

You can add dependencies without editing XML by launching Codename One Settings with mvn cn1:settings. See Section 2.2.4.5, “Managing add-ons in Codename One Settings”.
When to use the "other" pom.xml Files

The instructions say that you almost always add dependencies in the common/pom.xml file. What are the other modules' pom.xml files for, and when do you need to change them, or add dependencies to them?

Here’s an overview:

%PROJECT_ROOT%/pom.xml

The root pom.xml file is the parent module of all other modules. Anything you add here will be inherited by all the modules. It can be helpful to use <dependencyManagement> and <pluginManagement> sections in this file to merge versions for dependencies and plugins project-wide. This is also a good place to add project meta-data like <developers>, <scm>.

javase/pom.xml (when the project has a javase module)

Any dependencies that are only required for native implementations on the Java SE platform can be added here. Dependencies added to this project aren’t subject to the compliance check.

Additionally, this module handles the build toolchain for the Java SE platform. This includes Mac and Windows Desktop builds, as well as Java SE desktop builds. If you want to customize the build workflow for any of these targets, you would do so by adding plugin executions in this pom.xml file.

android, ios, win, linux, and javascript (when the project has them)

These modules don’t use Maven for their dependencies (Android may deserve a small asterisk here, but that’s complicated), so the primary thing you’d want to change in these pom.xml files are the build toolchain for those targets. For example, you might add plugin executions for your CI workflow on builds targeting these particular platforms.

A project without these modules builds every platform from the common module. To customize one platform’s build, add its module: a <platform>/pom.xml copied from a project generated with -DplatformModules=all. The common module stops building that platform as soon as the module exists.

Example: Adding Google Maps dependency via Maven central

Add the GoogleMaps library to your app as a maven dependency.

As described in the GoogleMaps cn1lib README, the dependency snippet is:

<dependency>
  <groupId>com.codenameone</groupId>
  <artifactId>googlemaps-lib</artifactId>
  <version>1.0.1</version>
  <type>pom</type>
</dependency>

You should, but, look on Maven central to see what the latest version number is, and substitute that version into the <version> tag of the snippet.

Copy and paste this snippet into the <dependencies> section of your common/pom.xml file. And save it.

The common/pom.xml file has a lot of existing configuration in it, and it may not be clear, on first glance, where the <dependencies> tag is located. A simple "find" for <dependencies> may also lead you astray, since there are a few <profile> tags which also include <dependencies> sections.

The correct <dependencies> section, is located near the top of the file. You can identify it because it will include the following comment:

<!-- INJECT DEPENDENCIES -->

This is a special marker that’s used by some Codename One tooling to help it locate the optimal place to inject dependencies.

Don’t REMOVE THIS COMMENT. Just add your dependency snippet somewhere before or after it.

Compatibility with Codename One

You can paste any Maven dependency snippet you like into your project, but libraries that haven’t been specifically developed for Codename One might not be compatible. See Appendix C, API. If you’re unsure whether a library is compatible, you could add the dependency and try to use it in your app. If it isn’t compatible, it will fail when you try to build the app, during the compliance check.

The easiest way to find Codename One libraries is to use the Extensions view in Codename One Settings. These libraries were built specifically for Codename One. Settings warns before installing catalog entries known to target older Codename One releases.

The compliance check

All application code in the common module of your Codename One project must be compatible with Codename One. This includes all dependencies. When you build your project, it will perform a compliance check to ensure that no code uses unsupported APIs. (See Appendix C, API).

If the compliance check fails (that is, the app uses unsupported APIs), the build will fail. The error log should provide some clues about where the offending code resides.

Managing add-ons in Codename One Settings

Launch Codename One Settings from the project root, then select Extensions in the left navigation rail:

mvn cn1:settings
Codename One Settings Extensions view

As an example, install the "Google Maps" library.

Type Maps in the search field and locate Codename One Google Native, the Google Maps library.

Click Install or Download, depending on how the catalog entry is distributed.

Settings shows progress while it installs the extension. For an installed extension, click the same action area and confirm Uninstall to remove it.

How Codename One Settings handles Maven dependencies

Many extensions listed in Settings are deployed as cn1lib bundles. Others are deployed on Maven Central and could be installed by adding a snippet to pom.xml (as described in Section 2.2.4.2, “Example: Adding Google Maps dependency via Maven central”).

Settings shields you from the details of how it installs extensions. For extensions deployed on Maven Central, it adds the dependency directly to your project’s common/pom.xml. For extensions distributed as cn1lib bundles, it uses the install-cn1lib Maven goal.

You shouldn’t need to worry about this, as it happens seamlessly. If you’re curious, you can look at the <dependencies> section of your common/pom.xml file to see the added <dependency> tag after you install an extension.

If the Settings window opens blank

Settings is a Codename One app hosted in a native window, so a window that opens but shows nothing can come from the window layer, the display scale, the theme, or font loading. Capture the render state and attach it to a bug report rather than guessing:

mvn cn1:settings -Dsettings.diagnostics=cn1-settings-diagnostics.txt

The file records the OS and JDK, the HiDPI scale the JVM reports, the window and canvas geometry, the size Codename One laid the form out at, and the colours and font metrics resolved for the theme. Add -Dsettings.screenshot=shot.png to also write the window contents; a second shot.onscreen.png captures the pixels actually on screen, which can differ from the offscreen paint. The launch log is at ~/.codenameoneSettings/settings.log.

Installing legacy cn1libs

The recommended approach for installing add-ons is to use Codename One Settings or add the Maven dependency to common/pom.xml. In some situations neither method is available. For example, you might have a legacy cn1lib file that isn’t listed in the extension catalog or deployed to Maven Central.

In cases like this you can use the install-cn1lib Maven goal to install it as follows:

mvn cn1:install-cn1lib -Dfile=/path/to/yourlibrary.cn1lib

2.3. Updating Codename One

Codename One releases new versions weekly to the Codename One Maven repository. It’s recommended that you stay up to date with the latest version as much as possible to ensure compatibility with the Codename One build server, which is always running the latest version.

You can use the update goal to update both the Codename One libraries, and the Codename One dependencies in your project.

For example:

mvn cn:update

CLI

Or you can use the run.sh/run.bat script to run this goal as follows:

./run.sh update
Use run.bat update instead on Windows

IntelliJ

Or you can click on the "Configuration" menu, and select "Tools" > "Update Codename One" as shown here:

intellij update codenameone

Then press the Run button.

NetBeans

Or you can right-click on the project in the project inspector, and select "Run Maven" > "Update Codename One" as shown here:

netbeans update codenameone

Then press the Run button.

Manually updating the pom.xml file

You can also update your Codename One dependencies manually by modifying the cn1.version and cn1.plugin.version properties defined in your project’s pom.xml file.

For example, Open the pom.xml file, and look for the following:

<cn1.plugin.version>7.0.210</cn1.plugin.version>
<cn1.version>7.0.210</cn1.version>

Change these values to reflect the latest version of the codenameone-maven-plugin, listed as <release> in the repository metadata. The update goal reads the same metadata and edits both properties for you.

Updating the cn1.plugin.version and cn1.version properties manually will update the Maven dependencies for your project but it won’t update the other Codename One tools such as the GUI builder, and the Build Server Client, which are managed outside of Maven. You should use the Section B.23, “Update Codename One (update)” as described at the beginning of this section to perform a "full" update.

2.4. Creating project templates

A project template is a Codename One application project that can be used as a starting point for building a Codename One application. Codename One initializr uses project templates to generate starter projects for Codename One applications. You can also use the Section B.5, “Generate app project (generate-app-project)” goal to generate starter projects from templates directly in Maven.

Any Codename One project can be converted into a project template.

2.4.1. Converting a Codename One application project into a project template

If you have an existing maven Codename One application project, you can convert it into a project template by adding a file named generate-app-project.rpf in the root directory of the project.

The contents of this file should look like:

template.mainName=$YOUR_PROJECT_MAIN_NAME
template.packageName=$YOUR_PROJECT_PACKAGE_NAME

[dependencies]
====
... YOUR PROJECT MAVEN DEPENDENCIES ...
====

[parentDependencies]
====
... YOUR PARENT PROJECT MAVEN DEPENDENCIES ...
====

Where you make the following substitutions:

$YOUR_PROJECT_MAIN_NAME

This should be the value of the codename1.mainName property in the project’s codenameone_settings.properties file.

$YOUR_PROJECT_PACKAGE_NAME

This should be the value of the codename1.packageName property in the project’s codenameone_settings.properties file.

…​ YOUR PROJECT MAVEN DEPENDENCIES…​

Paste any maven dependencies that the project requires into this section. These will be injected into the <dependencies> section of the common/pom.xml file.

…​ YOUR PARENT PROJECT MAVEN DEPENDENCIES…​

Paste any maven dependencies that the parent project requires into this section. These will be injected into the <dependencies> section of the pom.xml file.

See Section B.5.4.2, “Sample generate-app-project.rpf file” for a more concrete example of the generate-app-project.rpf.

2.4.2. Test your project template

You can test your project template by using it as the sourceProject parameter for the generate-app-project goal. See Section B.5, “Generate app project (generate-app-project)”.

2.5. Codename One libraries

A Codename One Library (cn1lib) is a module that can be distributed and added to Codename One applications to add functionality. It can be distributed as a self-contained bundle (a file with the.cn1lib extension), or deployed on Maven central to be included in application projects as a pom dependency.

A cn1lib may contain any of the following:

  1. Cross-platform Java classes.

  2. Native code that targets specific platforms.

  3. Build hints, which will affect how projects will be built that include this library. These can contain things like Gradle dependencies on Android, Cocoapods dependencies on iOS, and other hints to affect the build-server process.

  4. CSS files.

.cn1lib vs .jar

You may be wondering why the .cn1lib format is even necessary. Why not just distribute libraries as .jar files? The .cn1lib format offers several advantages over the plain .jar format:

  1. cn1libs can contain platform-specific native sources that make use of native APIs on the various platforms. For example, they can contain Objective-C code which will be compiled on the build server when deploying on iOS.

  2. Codename One library projects perform a compliance check at the time that the library is compiled to ensure it only uses supported Codename One APIs. This provides a sort of "certification" that the library will be compatible with Codename One application projects.

  3. Codename One libraries can include CSS files and build hints which will be appended to the build hints of application projects when they’re built.

All that said, you can still distribute libraries as plain old jars and include them in your Maven Codename One projects as jar dependencies. Codename One application projects will perform an additional compliance check to ensure that the jar is compatible, and the build will fail if it uses APIs that aren’t available in Codename One.

Codename One supports a subset of JavaSE8, as well as addition APIs for accessing device functionality and building beautiful user interfaces. See the Codename One javadocs for a definitive list of supported APIs.

2.5.1. Creating a library project

Use the cn1lib-archetype for generating a new Codename One library project as follows:

Command line
mvn archetype:generate \
  -DarchetypeArtifactId=cn1lib-archetype \
  -DarchetypeGroupId=com.codenameone \
  -DarchetypeVersion=LATEST \
  -DgroupId=com.example.mylib \
  -DartifactId=mylib \
  -Dversion=1.0-SNAPSHOT \
  -DinteractiveMode=false
This command is formatted for the bash prompt (for example, Linux or Mac). It will work on Windows also if you use bash. If you’re on Windows and are using PowerShell or the regular command prompt, then you’ll need to modify the command slightly. In particular, the entire command would need to be on a single line. (Remove the '\' at the end of each line, and merge lines together, with space between the command-line flags)

In the above snippet you would change the groupId, artifactId, and version properties to reflect your project settings.

You can run the archetype:generate goal with as many or few properties as you like, and it will prompt you to enter any properties that are required. For example, You could enter:

mvn archetype:generate

And then follow the prompts. Or you could enter:

mvn archetype:generate -DarchetypeGroupId=com.codenameone \
  -DarchetypeArtifactId=cn1lib-archetype
This command is formatted for the bash prompt (for example, Linux or Mac). It will work on Windows also if you use bash. If you’re on Windows and are using PowerShell or the regular command prompt, then you’ll need to modify the command slightly. In particular, the entire command would need to be on a single line. (Remove the '\' at the end of each line, and merge lines together, with space between the command-line flags)

And follow the prompts. This will, result in fewer prompts because you’ve already specified the archetype to use.

This will create a new project for you in the current directory, in a newly created directory named after the artifactId that you entered.

IntelliJ IDEA
  1. Select "File" > "New Project"…​

    intellij new project menu
  2. Select "Maven" in the left menu.

    intellij new project dialog maven
  3. Check the "Create from Archetype" checkbox intellij create from archetype checkbox. This should allow you to choose from the archetypes that are already known to IntelliJ.

  4. If you don’t see an option for com.codenameone:cn1lib-archetype, then IntelliJ doesn’t know about it yet. If, but you do see this option, you can skip to the next step. Press the "Add Archetype…​" button. This will display a dialog for you to enter the details of the archetype.

    intellij add archetype

    Fill in this dialog as shown in the above image. Specifically groupId=com.codenameone, artifactId="cn1lib-archetype," and version="LATEST"

    Then press OK.

  5. Select the option that says "com.codenameone:cn1lib-archetype"

    intellij select cn1lib archetype

    Then press "Next"

  6. This will display a form where you can enter the details of your project such as its location (where you want to create the project folder), the name, the artifact ID, and the groupID. Fill in this form as you see fit.

    intellij new cn1lib project details form

    Then click "Next"

  7. The final form in this wizard summarizes the project details and gives you an opportunity to add more properties to pass to the archetype:generate goal. In your case you don’t need to add any more properties. If the information looks correct, you can press Next.

    intellij new cn1lib project details summary

At this point you will be prompted to open the project.

NetBeans
  1. Select "File" > "New Project…​"

    netbeans new project menu
  2. In the "New Project" dialog, select "Java with Maven" in the left panel, and "Project from Archetype" in the right panel, as shown below.

    netbeans new project maven dialog

    Then press "Next"

  3. This will bring you to the "Maven Archetype" dialog as shown below:

    netbeans maven archetype cn1lib dialog

    Enter "com.codenameone" or "cn1lib-archetype" into the search field. Then select "cn1lib-archetype" in the "Known archetypes:" panel. This will prefill the Group ID, Artifact ID and Version fields for you. You may want to change Version to LATEST to ensure that it tries to use the latest available version of the archetype.

    Then click "Next"

  4. This will bring you to the "Name and Location" panel of the wizard.

    netbeans new project name and location

    Enter in the project name (which you’ll be forced to use as the artifact ID also), project location, groupId, version, and package. The "Package" is unimportant here as it isn’t used anywhere in the project.

    Once you’ve entered the information to your liking press the "Finish" button.

This will create a new library project for you at the location you specified.

Eclipse IDE
  1. Select "File" > "New Project…​"

  2. In the New Project dialog, expand the Maven item, and select Maven Project

    eclipse new project wizard

    Then press "Next"

  3. The next panel will look like the below image. The default settings on this panel should be fine. Press Next

    eclipse new project wizard new maven project
  4. In the next panel, enter "cn1lib" in the Filter field. After a moment the cn1lib-archetype should appear in the area below as shown here:

    eclipse new maven project cn1lib

    Select that option, and press Next

  5. The next panel, allows you to enter your project details, such as group ID, and artifact ID. Your project information here and then press Finish.

    eclipse new maven project details

This will create a new library project for you at the location you specified.

Project structure

Take a look at the project that was created. It’s a multi-module Maven project with the following modules:

common

The module where you’ll add all your cross-platform code and CSS, and build hint configuration. This module is in the "common" directory of the main project.

Java SE

The module where you can implement native interfaces for the Java SE platform. This module is in the "Java SE" directory of the main project.

ios

The module where you can implement native interfaces for the iOS platform. This module is in the "ios" directory of the main project.

android

The module where you can implement native interfaces for the Android platform. This module is in the "android" directory of the main project.

JavaScript

The module where you can implement native interfaces for the JavaScript platform. This module is in the "JavaScript" directory of the main project.

lib

The library module which includes all the other modules as dependencies, and can be used as a pom dependency in Codename One application projects that wish to use this library. This module is in the "lib" directory of the main project.

tests

An application project for writing unit tests against your library. This module is in the "tests" directory of the main project.

IntelliJ IDEA

The project inspector will look like:

intellij myfirstlib project inspector

This top-level view of the module structure may seem daunting. Most of your development will occur inside the "common" module. If you expand that module it will look more familiar to developers who have used the old Ant project structure:

intellij myfirstlibrary common project files

Your cross-platform Java source would go in the common/src/main/java directory. Your CSS files go in the common/src/main/css directory.

NetBeans

The project inspector will look like:

netbeans myfirstlibrary project inspector

This top-level view of the modules doesn’t provide a clear view of the project landscape, but, since 99% of your development will occur inside the common submodule. Open that "common" sub-module project as well and take a peek.

Right-click on the "Common" sub-module, and select "Open Project" as shown below:

netbeans myfirstlibrary open common submodule

With the common subproject open, the project inspector will look like:

netbeans myfirstlibrary project inspector with common

In this screenshot, "Source Packages" and "Other Sources/css" are expanded to highlight where your Java source files and CSS source files will be located.

The project inspector hides a few important files, but, so here is a screenshot of the File inspector for the common project:

netbeans my first library file inspector common
Eclipse IDE

The package explorer will look like:

eclipse cn1lib package explorer

In this screenshot, the common/src/main/css and common/src/main/java directories are expanded since this is where most of your module source will go.

Command line

If you do a file listing on the project directory, it shows the following:

Steves-Mac-Pro:MyFirstLibrary shannah$ find .
.
./tests
./tests/pom.xml
./tests/javase
./tests/javase/pom.xml
./tests/common
./tests/common/codenameone_settings.properties
./tests/common/pom.xml
./tests/common/nbactions.xml
./tests/common/src
./tests/common/src/test
./tests/common/src/test/java
./tests/common/src/test/java/com
./tests/common/src/test/java/com/example
./tests/common/src/test/java/com/example/myfirstlib
./tests/common/src/test/java/com/example/myfirstlib/MyFirstTest.java
./tests/common/src/main
./tests/common/src/main/css
./tests/common/src/main/css/theme.css
./tests/common/src/main/java
./tests/common/src/main/java/com
./tests/common/src/main/java/com/example
./tests/common/src/main/java/com/example/myfirstlib
./tests/common/src/main/java/com/example/myfirstlib/LibraryTests.java
./tests/cn1libs
./tests/.mvn
./tests/.mvn/jvm.config
./pom.xml
./javase
./javase/pom.xml
./javase/src
./javase/src/main
./javase/src/main/java
./javase/src/main/java/com
./javase/src/main/java/com/example
./javase/src/main/java/com/example/myfirstlib
./ios
./ios/pom.xml
./ios/src
./ios/src/main
./ios/src/main/objectivec
./common
./common/codenameone_library_required.properties
./common/pom.xml
./common/codenameone_library_appended.properties
./common/src
./common/src/test
./common/src/test/java
./common/src/test/java/com
./common/src/test/java/com/example
./common/src/test/java/com/example/myfirstlib
./common/src/test/java/com/example/myfirstlib/MyLibraryTest.java
./common/src/main
./common/src/main/css
./common/src/main/css/theme.css
./common/src/main/java
./common/src/main/java/com
./common/src/main/java/com/example
./common/src/main/java/com/example/myfirstlib
./common/src/main/java/com/example/myfirstlib/MyLibrary.java
./android
./android/pom.xml
./android/src
./android/src/main
./android/src/main/java
./android/src/main/java/com
./android/src/main/java/com/example
./android/src/main/java/com/example/myfirstlib
./lib
./lib/pom.xml
./MyFirstLibrary.iml
./javascript
./javascript/pom.xml
./javascript/src
./javascript/src/main
./javascript/src/main/javascript
./.idea
./.idea/encodings.xml
./.idea/jarRepositories.xml
./.idea/.gitignore
./.idea/workspace.xml
./.idea/misc.xml
./.idea/compiler.xml

This may seem daunting at first, but it’s important to realize that 99% of the time, you’ll be working in the "common" module - most of the other stuff is boilerplate.

Important files

A few key files in this project that you’ll be using more than the others.

pom.xml

The maven configuration file of the root module is where you will set project-wide properties such as the cn1.version property, which specifies the version of the Codename One libraries that the module should be compiled against. Periodically, you’ll want to update the cn1.version property to point to the latest version.

When/if you decide to deploy your module to Maven central, you’ll need to add more deployment-related settings in this file.

common/pom.xml

The maven configuration file for the "common" module, which will contain most of your cn1lib’s source code, CSS files, and properties files. If your library depends on other libraries or jar files, you’ll be adding them as dependencies in this file, and not the root pom.xml file.

common/codenameone_library_appended.properties

This file is where you can specify properties that should be merged with the codenameone_settings.properties of application projects that include this library as a dependency. This is where you would add, for example, Gradle dependencies required for the Android builds, or CocoaPods dependencies that are required for iOS builds.

common/codenameone_library_required.properties

This file allows you to specific build hints that must be present in application projects that include this library. If this library requires a particular android build tools version, or a specific Java version, then those requirements should be specified in this file.

Important directories

As mentioned earlier, 99% of all your development will likely occur inside the "common" module. The other modules are for native implementations of Native interfaces.

common/src/main/java

This is where your cross-platform Java source files will be placed.

common/src/main/css

If your library uses CSS, this is where all CSS-related files will be placed.

common/src/main/resources

Other non-java resources that you want to have included in the classpath.

Building the library
Command line

To build the library, run the "install" goal on the root module as follows:

mvn install
IntelliJ IDEA

Press the "build" intellij build icon button on the toolbar.

NetBeans

Right-click on the "root" module in the project explorer and select Build.

netbeans right click build
You must build the root module and not one of the submodules.

Or you could have selected the "root" module in the project explorer and pressed the "build" netbeans build button button on the toolbar.

Eclipse IDE

Right-click on the "root" module in the project explorer and select Run as > Maven Install

eclipse build cn1lib
If the build fails for any reason, check to make sure that your project is using the latest version of the Codename One plugin. You can do this by opening the pom.xml file, and changing the cn1.version and cn1.plugin.version properties to reference the latest version. Check for the latest version, listed as <release> in the repository metadata.
Building the Legacy.cnlib file

When using the Maven build tool, you no longer require the.cn1lib file at all. Your library projects can be handled entirely via Maven’s dependency mechanism. The preferred way to distribute your libraries is on Maven central, and the preferred way to add a library to an application is via a Maven "pom" dependency.

That being said, you may still want to distribute your library as a.cn1lib file for the sake of users who are still using Ant as their build tool. For that reason, when you build a library project, the cn1lib is automatically built as well. After running a build, you can look in the common/target directory and find your.cn1lib file ready to be distributed.

Editing Java Code

To get acquainted with your project, add a "Hello World" Java class that you want to make available as part of your cn1lib.

Add a new class inside the "common/src/main/java" directory with package com.example, and name HelloWorld. Enter the following contents into the class:

public class HelloWorld {
    public static void helloWorld() {
        System.out.println("Hello world");
    }
}

Now build the library again. (See Section 2.5.1.6, “Building the library”).

Using the library in an application project

Now that you’ve built your library and added a Java class, try adding it as a dependency in an application project. If you haven’t yet created an application project, do that now. See Section 2.2.2, “Creating a new project” for instructions on creating a new application project.

Open the common/pom.xml file of your application project.

Make sure you’re editing the common/pom.xml file of the application project and not the library project.

This file may look a little hairy as there is a lot of configuration in there. You will be looking for the <dependencies> section.

The common/pom.xml file will have more than one <dependencies> tag, as it includes some profiles handling things like Kotlin support. There will be one particular <dependencies> tag that includes a comment like

<!-- INJECT DEPENDENCIES -->

You should add your dependencies before this comment.

For the sake of this example, suppose your library was set up with the following coordinates:

groupId:

com.example

artifactId:

mylib

version:

1.0-SNAPSHOT

In this case you would add the following XML snippet to the <dependencies> section of your application’s common/pom.xml file:

<dependency>
    <groupId>com.example</groupId>
    <artifactId>mylib-lib</artifactId>
    <version>1.0-SNAPSHOT</version>
    <type>pom</type>
</dependency>
Notice that you appended "-lib" to the artifactId. This is because you’re including the "lib" module of your library project as the dependency, and not the root module. Also the <type>pom</type> is important as it indicates that this is a pom dependency - not a regular jar dependency.

Now try it out. Try adding the following code to your application project’s main class (or anywhere in the application project, for that matter):

This calls into the library you just built, so it isn’t one of the compiled examples:

import com.example.HelloWorld;

// ... inside start()
HelloWorld.helloWorld();

And build the project. The project should build OK, and if you run it, you should see that the helloWorld() method works as designed.

2.5.2. Adding menus to the simulator

A cn1lib can contribute menu items to the Codename One simulator’s menu bar. This is the same affordance the framework itself uses for the Skins / Native Theme / Simulate menus — opened up so library authors can expose backend-specific actions (for example, "Add a simulated peripheral," "Inject a push notification," or "Switch backend") without users having to write any Swing code or instrument their app.

Every menu item is also reachable from CN1 UnitTests (or any app code) through CN.execute("namespace:itemN") — the JavaSE port’s URL execute is overloaded to recognize a registered hook url and dispatch it on the EDT instead of opening it as a browser URL. On Android, iOS, JavaScript and other production targets no hooks are registered, so a hook-style URL falls through to the normal native execute and (almost always) becomes a no-op; tests should pair CN.execute with CN.canExecute for that reason. Hooks can also be declared with no menu label, which makes them callable from tests but invisible in the menu — useful for state-priming actions a human wouldn’t click.

The contract

Each cn1lib ships a properties file at a well-known classpath location. The simulator scans every jar on its classpath for this resource and merges the results, so multiple cn1libs coexist cleanly:

# META-INF/codenameone/simulator-hooks.properties
name=Bluetooth
namespace=bluetooth   # optional; defaults to slugified `name`

# Each itemN is the action; the matching labelN is the menu text.
# Items are positional — the loader reads item1, item2, item3, ... and
# stops at the first missing index. Don't skip numbers.
item1=com.example.bt.simulator.Hooks#toggleAdapter
label1=Toggle adapter on/off

item2=com.example.bt.simulator.Hooks#addDemoPeripheral
label2=Add demo peripheral

# Label omitted → API-only hook. Callable from tests, invisible in menu.
item3=com.example.bt.simulator.Hooks#primeReadFailure

Required keys:

name

Menu title shown in the simulator’s menu bar. One menu per properties file.

itemN

A fully.qualified.ClassName#staticMethodName reference for the Nth menu item. The method must be public static void and take no arguments. Items are numbered from 1 upward; the loader stops at the first missing itemN, so don’t leave gaps.

Optional keys:

namespace

Identifier used for the CN.execute lookup (for example, bluetooth for a URL like bluetooth:item1). Defaults to lowercased, ASCII-slugified name (Push Notifications! → push-notifications). Set this explicitly when you want a different identifier from the display name.

labelN

Display text for the matching itemN. Omit entirely to make the hook API-only — registered with CN.execute but hidden from the menu.

No groups, no submenus, no priority — flat by design. If you need ordering relative to another cn1lib, you can’t have it: discovery order wins, and that’s intentional so the contract stays small and the future simulator UX can re-render this metadata however it likes.

The action method

The simulator dispatches every action on the Codename One EDT through Display.callSerially, so your method can call Display.getInstance(), Form.show(), Dialog.show(), ToastBar.showInfoMessage() and any other CN1 API. Reflection uses the same classloader that loaded Display, so cn1lib internals (including package-private classes) resolve normally:

This is a method in your own cn1lib, so it isn’t one of the compiled examples:

public static void resetPairing() {
    PairingState.clear();                 // package-private, same cn1lib
    if (Display.isInitialized()) {
        ToastBar.showInfoMessage("Pairing state cleared");
    }
}

The Display.isInitialized() guard is a useful pattern when the same static methods are also called from JUnit tests that don’t run inside a live CN1 simulator — the state mutation runs in both contexts, only the UI feedback is skipped.

Worked example using cn1-bluetooth

The cn1-bluetooth cn1lib ships a JavaSE port with two backends: a scriptable in-memory simulator and a real-hardware backend that talks to a native helper (CoreBluetooth on macOS, BlueZ on Linux, WinRT on Windows). Both are useful in different stages of development, and the menu lets the user choose between them and exercise the simulator without writing any test scaffolding.

Its simulator-hooks.properties looks like this:

name=Bluetooth
namespace=bluetooth

item1=com.codename1.bluetoothle.BluetoothSimulatorHooks#toggleAdapter
label1=Toggle adapter on/off

item2=com.codename1.bluetoothle.BluetoothSimulatorHooks#addDemoPeripheral
label2=Add demo peripheral

item3=com.codename1.bluetoothle.BluetoothSimulatorHooks#switchToNativeBle
label3=Switch backend → native BLE (real hardware)

# API-only: used by the test suite but never displayed in the menu
item4=com.codename1.bluetoothle.BluetoothSimulatorHooks#primeReadFailure

When the user runs an app that depends on cn1-bluetooth, the simulator’s menu bar gets a Bluetooth menu with the three labeled items. Clicking Add demo peripheral drops a peripheral into the in-memory simulator that the running app can then scan for, connect to, and exchange data with — without any real hardware. item4 is callable from tests via CN.execute("bluetooth:item4") but never shows up in the menu.

Calling hooks from CN1 unit tests

CN1 unit tests (AbstractTest subclasses run via mvn cn1:test) compile under the same restrictions as the rest of the app — no reflection, no JavaSE-only imports. Drive a hook the same way you’d execute any URL — CN.execute recognizes registered hook urls and dispatches them on the EDT:

public class BluetoothDemoTest extends AbstractTest {
    @Override
    public boolean runTest() throws Exception {
        // Skip cleanly off-simulator: a real device has no hook registered
        // and CN.canExecute will not return TRUE.
        if (!Boolean.TRUE.equals(CN.canExecute("bluetooth:item2"))) {
            return true;
        }
        // Seed the simulator — same effect as clicking "Add demo peripheral".
        CN.execute("bluetooth:item2");
        // nullnow drive the public Bluetooth API as usual.
        return true;
    }
}

A common pattern: ship label-bearing hooks for actions a developer might want to fire manually (toggle adapter, inject notification), and ship label-less hooks for test-only state setup (primeReadFailure, seedFixture) that would just clutter the menu.

What’s intentionally not exposed
  • Swing types. JMenu, JMenuItem, KeyStroke and friends don’t appear in the contract. The simulator UX may change shape (toolbar, command palette, sidebar) and cn1libs shouldn’t have to follow.

  • Submenus, separators, priority. The metadata is a flat list with no hierarchy. If you want grouping, ship multiple simulator-hooks.properties files in separate jars — each becomes its own menu.

  • Long-running work on the EDT. Hook methods run on the CN1 EDT; if you need to do I/O, fire-and-forget a new Thread(…​) from the method or use CN.invokeAndBlock so you don’t block the UI.

2.5.3. Distributing your library

The recommended way to distribute your library is on Maven central. That way users will be able to install your library by copying and pasting a familiar <dependency> snippet into their pom.xml file.

3. Gradle project workflow

Maven is the standard way to build a Codename One application, and everything in the Maven project workflow chapter remains the reference. Gradle is an optional alternative for applications that want a smaller project: one directory instead of a root pom.xml and eight modules, and no native or backend directories until the application has native code or a server.

The Gradle build isn’t a second implementation. The com.codenameone Gradle plugin calls the same build engine the Maven plugin uses, so a Gradle project stages the same upload for the build server, runs the same local builders, compiles CSS with the same compiler and checks the same bytecode rules. An application built both ways uploads identical content for every target.

3.1. Choosing between Maven and Gradle

Choose Gradle when:

  • You want the smallest project that works: a settings file, your sources and nothing else.

  • Your team already uses Gradle, or your IDE and CI work better with it.

  • The application doesn’t need any of the Maven-only goals listed in Section 3.10, “Limits”.

Stay with Maven when:

  • The application targets Java 8. Gradle projects compile for Java 17 only, the bytecode level Codename One builds for every platform.

  • It still uses legacy .cn1lib files rather than libraries published to a Maven repository.

  • It depends on a goal that has no Gradle task yet.

Gradle projects leave out what the Maven build carries for older projects: legacy .cn1lib files (consumed or produced), the legacy Designer (resource editor) task, the Java 8 target, and the Maven-only files and profiles such as codenameone_maven.properties and the install-codenameone profile. Running Gradle needs JDK 17 or newer and Gradle 8.5 or newer; every project ships a Gradle wrapper, so you never install Gradle yourself.

3.2. Getting started

3.2.1. The initializr

In the Codename One initializr, set Build tool to Gradle. A Gradle project then offers three project types:

App

A client application.

App + backend

A client application with a backend/ subproject, as described in Section 3.8, “The backend”.

Backend only

A server with no client at all: no settings file, theme, simulator or native directories.

The download opens in IntelliJ IDEA, NetBeans, Eclipse or Visual Studio Code, and builds from the command line with the ./gradlew wrapper it contains.

3.2.2. Converting an existing project

The Maven plugin converts a Maven or Ant application to the Gradle layout, writing a new project beside the old one and leaving the old one untouched. In the commands in this chapter, VERSION stands for the Codename One release you use:

cd MyApp          # the Maven or Ant project
mvn com.codenameone:codenameone-maven-plugin:VERSION:convert-to-gradle
cd ../MyApp-gradle
./gradlew run

The conversion runs anywhere, with or without a project in the working directory. These properties control it:

mvn com.codenameone:codenameone-maven-plugin:VERSION:convert-to-gradle \
  -Dcn1.sourceProject=/path/to/MyApp \
  -Dcn1.outputDir=/path/to/MyApp-gradle \
  -Dcn1.includeBackend=true
cn1.sourceProject

The project to convert. Defaults to the project Maven runs in, else the working directory.

cn1.outputDir

Where the Gradle project goes. Defaults to <project>-gradle beside the source project. It must not exist or must be empty.

cn1.includeBackend

Carries over a backend module that’s still the untouched archetype skeleton. Off by default, because every Maven project has that module; a backend with code of its own is always converted.

cn1.gradleVersion

The plugin version the new settings.gradle.kts declares. Defaults to the version of the Maven plugin doing the conversion.

The conversion moves sources, CSS, localization and resources to src/main/…​, each platform’s native implementations to src/<platform>/<lang>, and the dependencies of common/pom.xml into build.gradle.kts. It raises codename1.arg.java.version to 17 and says so. Ant projects that mix Java and Kotlin in src/ get their Kotlin sources in src/main/kotlin and the Kotlin Gradle plugin in build.gradle.kts.

A project that uses legacy .cn1lib files is refused, and the message names every one of them. Depend on each library’s Maven coordinates instead, or republish it as a Gradle cn1lib (see Section 3.6, “Libraries”), then convert again.

The generate-app-project goal, which migrates an Ant project or a project template, produces a Gradle project directly with -Dcn1.buildTool=gradle:

mvn com.codenameone:codenameone-maven-plugin:VERSION:generate-app-project \
  -DgroupId=com.example.myapp \
  -DartifactId=myapp \
  -Dversion=1.0-SNAPSHOT \
  -DmainName=MyApp \
  -DsourceProject=/path/to/AntProject \
  -Dcn1.buildTool=gradle \
  -DinteractiveMode=false

3.3. The project layout

MyApp/
  settings.gradle.kts
  build.gradle.kts            (optional: the application's own dependencies)
  gradle.properties
  gradlew, gradlew.bat, gradle/wrapper/
  codenameone_settings.properties
  icon.png
  src/main/java/              (and src/main/kotlin/ for Kotlin sources)
  src/main/css/theme.css
  src/main/resources/
  src/main/l10n/
  src/test/java/
  src/android/java/           created by generateNativeInterfaces, when needed
  src/ios/objectivec/
  src/javase/java/
  src/javascript/javascript/
  src/win/c/
  src/linux/c/
  backend/                    created by addBackend, when needed

The native and backend directories don’t exist until the application needs them. The plugin declares them anyway, so creating one later needs no build-file edit.

The settings file is the only Codename One line a project needs, with VERSION replaced by the release:

pluginManagement {
    repositories {
        maven("https://repo.codenameone.com/maven2")
        gradlePluginPortal()
    }
}

plugins {
    id("com.codenameone") version "VERSION"
}

rootProject.name = "MyApp"

The plugin, applied from the settings file, adds the repository the framework is published to (and Maven Central for other libraries), applies itself to the project and to backend/ when there is one, and builds against its own version. There’s one version number to bump.

A project’s kind comes from the files the other build tools already use: codenameone_settings.properties makes it an application, codenameone_library_appended.properties a cn1lib, and application.properties without a settings file a backend. The codename1.kind Gradle property (APP, LIB or BACKEND) overrides the detection for the root project. Subprojects, such as an application’s backend, are always detected from their own files, because a Gradle property set on the command line or in gradle.properties reaches every project of the build.

The generated gradle.properties turns on the configuration cache and the build cache, which is what makes a second ./gradlew run start in about a second:

# Gradle caches the configuration of this build, which is what makes the second
# ./gradlew run start in about a second.
org.gradle.configuration-cache=true
org.gradle.caching=true

To resolve the framework from a mirror, or from a directory holding a locally built Codename One, set codename1.repository there:

# Resolve the plugin's framework artifacts from a mirror, or from a local
# directory holding a locally built Codename One, instead of repo.codenameone.com.
codename1.repository=/path/to/maven/repository

3.4. Running and building

./gradlew run      # the simulator
./gradlew debug    # the simulator, waiting for a debugger on port 5005
./gradlew cn1Test  # the unit tests, in the simulator's test runner

The simulator reloads CSS as you edit it, and its hot reload recompiles through Gradle. Cloud builds and local builds are tasks too:

./gradlew buildAndroid           # send an Android build to the build server
./gradlew buildIos               # send an iOS debug build
./gradlew buildIosXcodeProject   # generate an Xcode project locally
./gradlew buildJavascriptLocal   # build the JavaScript port locally

cn1Build runs any target by name, and codename1.stageOnly stops once the upload jar is staged and checked, which is useful for inspecting exactly what a build would send:

./gradlew cn1Build -Pcodename1.platform=ios -Pcodename1.buildTarget=ios-source
./gradlew buildAndroid -Pcodename1.stageOnly=true

Gradle runs one Codename One build at a time, even when a command line names several, because each one uses the build client and the local toolchains.

3.4.1. Task reference

Gradle taskMaven goalWhat it does

run

cn1:run

Runs the application in the simulator.

debug

cn1:debug

Runs the simulator suspended, waiting for a debugger on port 5005.

cn1Css

cn1:css

Compiles src/main/css/theme.css, merged with the CSS of every cn1lib, into theme.res.

transcodeSvg

cn1:transcode-svg

Turns SVG and Lottie assets into Java sources.

generateGuiSources

cn1:generate-gui-sources

Generates sources from GUI builder XML and CodeRAD view templates.

cn1Compile

compile

Compiles the application and its simulator native code; the simulator’s hot reload runs it.

prepareSimulator

cn1:prepare-simulator-classpath

Writes the files the simulator reads at startup.

cn1Test

cn1:test

Runs the unit tests in the simulator’s test runner.

generateNativeInterfaces

cn1:generate-native-interfaces

Writes implementation stubs for every native interface; see Section 3.5, “Native interfaces”.

verifyNativeInterfaces<Build>

(none)

Runs before each build task and fails when a native interface has no implementation for that platform.

buildAndroid, buildAndroidGradleProject

cn1:buildAndroid, cn1:buildAndroidGradleProject

An Android cloud build; an Android Studio project generated locally.

buildIos, buildIosRelease, buildIosXcodeProject

cn1:buildIos, cn1:buildIosRelease, cn1:buildIosXcodeProject

An iOS debug or App Store cloud build; an Xcode project generated locally.

buildMacNative, buildMacDesktop

cn1:buildMacNative, cn1:buildMacDesktop

A native macOS build; a macOS desktop (JVM) build.

buildWindowsDesktop, buildWindowsDevice

cn1:buildWindowsDesktop, cn1:buildWindowsDevice

A Windows desktop (JVM) build; a native Windows build.

buildLinuxDevice

cn1:buildLinuxDevice

A native Linux build.

buildJavascript, buildJavascriptLocal

cn1:buildJavascript

A JavaScript cloud build; the JavaScript port built locally.

cn1Build

cn1:build

The build given by -Pcodename1.platform and -Pcodename1.buildTarget.

settings, guibuilder, gameBuilder, certificateWizard

cn1:settings, cn1:guibuilder, cn1:gamebuilder, cn1:certificatewizard

Opens Codename One Settings, the GUI Builder, the Game Builder or the iOS Certificate Wizard for this project.

addBackend

(none)

Adds a backend/ subproject to the application.

runBackend

cn1:backend

Runs a backend on this JVM.

backendPackage

cn1:backend-package

Builds a backend as a single native binary.

backendWebApp

cn1:backend-webapp

Builds the app for the browser and stages it for the backend to serve at /.

backendTest

test -Dcn1.backend.compiledTests=true

Runs a backend’s tests as a native binary. The standard test task runs them on this JVM.

cn1Update

cn1:update

Updates the plugin version in settings.gradle.kts and the build client.

A build task accepts -Pautomated=true to wait for a cloud build and download its result, and -Popen=false (or -Pcodename1.open=false) to keep a generated Xcode or Android Studio project from opening.

3.4.2. Build hints

Build hints come from codenameone_settings.properties, as in every Codename One project. The codenameone {} block in build.gradle.kts adds hints for every build of the project, without the codename1.arg. prefix:

codenameone {
    buildHints.put("ios.newStorageLocation", "true")
    buildHints.put("android.targetSDKVersion", "35")
}

A hint on the command line applies to that build only, and wins over both. -Pcodename1.arg.<hint> and -Dcodename1.arg.<hint> are equivalent:

./gradlew buildIos -Pcodename1.arg.ios.newStorageLocation=true

The same block also sets version, the framework version the project builds against (it defaults to the plugin’s), and mainClass, which defaults to the package and main name in the settings file.

3.5. Native interfaces

A Gradle project starts without native directories, and adding a native interface later needs no change to any build file.

  1. Declare the interface in src/main/java, as described in native interfaces:

    public interface MyNative extends NativeInterface {
        String helloWorld(String hi);
    }
  2. Generate the stubs:

    ./gradlew generateNativeInterfaces

    The task compiles the application, finds every interface that extends NativeInterface, and writes a stub for each platform into src/<platform>/<lang>, creating only the directories it writes to. An existing implementation is never overwritten unless you pass -Pcn1.overwrite=true.

  3. Implement the stubs. The Java SE implementation in src/javase/java compiles against the application and joins the simulator’s classpath on the next ./gradlew run. The other platforms' sources travel in that platform’s upload.

-Pcn1.nativeInterface limits the task to one interface, and -Pcn1.swift=true and -Pcn1.kotlin=true add Swift and Kotlin stubs beside the Objective-C and Java ones:

./gradlew generateNativeInterfaces -Pcn1.nativeInterface=com.example.myapp.MyNative \
  -Pcn1.swift=true -Pcn1.kotlin=true

Before every build, the plugin checks that each native interface has an implementation for the target platform. A missing one fails the build before anything is sent, naming the file to create, rather than failing later on the build server.

To remove a native interface, delete the interface and its implementation files; nothing else refers to them.

3.6. Libraries

3.6.1. Using a cn1lib

Declare a cn1lib by its -lib coordinates in build.gradle.kts, next to any plain Java library:

dependencies {
    // A Codename One library published to a Maven repository:
    cn1lib("com.codenameone:googlemaps-lib:1.0")

    // A plain Java library that only uses APIs Codename One supports:
    implementation("org.example:library:1.0")
}

These are the coordinates a Maven project uses with <type>pom</type>. The library’s classes and CSS reach every build, and its platform-specific code reaches only that platform’s: Maven chooses those jars with profiles, and the plugin reads the same profiles from the library’s published pom.xml. The library’s build hints merge into the application’s, as they do under Maven.

A project that declares repositories of its own in build.gradle.kts keeps the Codename One repository too: the plugin adds it beside them.

3.6.2. Building a cn1lib

A Gradle project with a codenameone_library_appended.properties file (and no codenameone_settings.properties) is a cn1lib. It uses the same settings file, src/main/java for the library, src/main/css for its CSS and src/<platform>/<lang> for native code, and generateNativeInterfaces works as it does for an application. The build script sets the coordinates and, to publish somewhere other than the local repository, a repository:

group = "com.example"
version = "1.0"

publishing {
    repositories {
        maven {
            name = "company"
            url = uri("https://maven.example.com/releases")
        }
    }
}
./gradlew publishToMavenLocal   # install into ~/.m2 for local testing
./gradlew publish               # publish to the repositories the build declares

The library is published in the same shape the Maven cn1lib-archetype produces, so Maven and Gradle applications both consume it. For a project named N:

N-common

The compiled library, with codenameone_library_appended.properties and codenameone_library_required.properties under META-INF/codenameone/.

N-common, classifier cn1css

The library’s CSS, as a zip.

N-<platform>

One jar per platform: compiled classes for javase, sources for the others, which the native builders compile.

N-lib

A pom that applications depend on, with one codename1.platform profile per platform.

N-backend

The library’s server half, compiled from src/backend/java and src/backend/resources, when there is one. A server that depends on it wires its controllers, beans and entities as its own; see Section 37.8, “Controllers and beans from a library”.

Gradle cn1libs don’t produce .cn1lib files.

3.7. Kotlin

Kotlin sources go in src/main/kotlin, and the project applies the Kotlin Gradle plugin in build.gradle.kts. plugins {} must be the first statement of the script:

plugins {
    kotlin("jvm") version "2.2.10"
}

dependencies {
    // the application's own dependencies, as before
}

Java and Kotlin classes in one project can call each other. Both are checked by the same bytecode compliance rules as a Java-only project.

3.8. The backend

addBackend adds a backend/ subproject to an existing application. The settings plugin includes it automatically, so settings.gradle.kts doesn’t change. Its tasks run with the project path in front:

./gradlew addBackend                          # create backend/ once
CN1_PROFILE=dev ./gradlew :backend:runBackend  # run it on this JVM
./gradlew :backend:backendPackage              # build the native binary
./gradlew :backend:test                        # run its tests on this JVM
./gradlew :backend:backendTest                 # and as a native binary

backendWebApp builds the app for the browser and stages it in backend/build/webapp. runBackend then serves the app at /, and backendPackage leaves it beside the binary, so one address is both the API and the app:

./gradlew :backend:backendWebApp               # build the app for the browser and stage it
CN1_PROFILE=dev ./gradlew :backend:runBackend  # the server now answers / with the app

The browser build takes about a minute, so neither task runs it for you: run backendWebApp when the app changed. Hosting the app in the browser covers how the server serves it.

A backend-only project has the same bootstrap with the server at the root: application.properties, application-dev.properties and src/main/java. Its tasks are runBackend, backendPackage, backendTest, cn1Update and the standard test, which runs the backend’s tests on this JVM; Chapter 38, Backend testing covers writing them. backendPackage writes the binary to build/<project name>:

CN1_PROFILE=dev ./gradlew runBackend
./gradlew backendPackage
CN1_PROFILE=dev PORT=9000 ./build/MyService

CN1_PROFILE=dev selects the development profile that application-dev.properties configures, with an in-memory SQLite database; without it the server reads the production settings and expects DATABASE_URL. PORT overrides the configured port. runBackend takes -Pcn1.backend.mainClass, -Pcn1.backend.args and -Pcn1.backend.jvmArgs. The server-side backend chapter covers the runtime itself.

3.9. Tools and updates

The desktop tools open on the Gradle project as they do on a Maven one:

./gradlew settings            # Codename One Settings
./gradlew guibuilder          # the GUI Builder
./gradlew gameBuilder         # the Game Builder
./gradlew certificateWizard   # the iOS Certificate Wizard

cn1Update moves the project to the latest release by rewriting the plugin version in settings.gradle.kts, and updates the build client. -Pcodename1.updateTo picks a version instead:

./gradlew cn1Update
./gradlew cn1Update -Pcodename1.updateTo=VERSION

3.10. Limits

These features remain Maven goals, with no Gradle task yet:

  • The OpenAPI, gRPC and GraphQL client generators (cn1:generate-openapi, cn1:generate-grpc, cn1:generate-graphql).

  • cn1:create-game-scene.

  • The on-device debugging helpers for Android and iOS.

An application that needs one of these stays on Maven for now.

Core concepts

4. The EDT - Event Dispatch Thread

4.1. What’s The EDT

Codename One allows developers to create as many threads as they want; however to interact with the Codename One user interface components a developer must use the EDT. The EDT stands for "Event Dispatch Thread" but it handles a lot more than "events."

The EDT is the main thread of Codename One, by using one thread Codename One can avoid complex synchronization code and focus on simple functionality that assumes one thread.

This has huge advantages for your code. You can normally assume that all code will occur on a single thread and avoid complex synchronization logic.

You can visualize the EDT as a loop such as this:

while(codenameOneRunning) {
     performEventCallbacks();
     performCallSeriallyCalls();
     drawGraphicsAndAnimations();
     sleepUntilNextEDTCycle();
}

Normally, every call you receive from Codename One will occur on the EDT. For example, every event, calls to paint(), and lifecycle calls (start etc.) should all occur on the EDT.

This is pretty powerful, however it means that as long as your code is processing nothing else can happen in Codename One!

If your code takes too long to execute then no painting or event processing will occur during that time, so a call to Thread.sleep() will actually stop everything!

The solution is pretty simple, if you need to perform something that requires intensive CPU you can spawn a thread.

Codename One’s networking code automatically spawns its own network thread (see the NetworkManager). However, this also poses a problem…​

Codename One assumes all modifications to the UI are performed on the EDT. If you spawn a separate thread, how do you force its modifications back into the EDT?

Codename One includes helper methods in the Display class to help in these situations: isEDT(), callSerially(Runnable), callSeriallyOnIdle(Runnable), and callSeriallyAndWait(Runnable) (with an optional timeout overload).

isEDT() is useful for generic code that needs to test whether the current code is executing on the EDT.

The two methods that coordinate work with the EDT pull in opposite directions, and the difference is easiest to see against the cycle itself. callSerially moves a Runnable onto the EDT. invokeAndBlock moves one the other way: called on the EDT it hands the Runnable to a pooled thread, and called off the EDT it simply runs it on the calling thread. Either way that Runnable isn’t on the EDT, so don’t touch the UI from inside it:

The EDT cycle and how callSerially and invokeAndBlock hand work to it
Figure 12. The EDT’s cycle, and where callSerially and invokeAndBlock enter it

4.2. Call Serially (And Wait)

callSerially(Runnable) should normally be called off the EDT (in a separate thread), the run method within the submitted runnable will be invoked on the EDT.

The Runnable passed to the callSerially and callSeriallyAndWait methods isn’t a Thread. Use the Runnable interface as a convenient callback interface:
// this code is executing in a separate thread
final String res = methodThatTakesALongTime();
Display.getInstance().callSerially(new Runnable() {
     public void run() {
          // this occurs on the EDT so I can make changes to UI components
          resultLabel.setText(res);
     }
});
You can write this code more concisely using Java 8 lambda code as such:
// this code is executing in a separate thread
String res = methodThatTakesALongTime();
Display.getInstance().callSerially(() -> resultLabel.setText(res));

This allows code to leave the EDT and then later on return to it to perform things within the EDT.

The callSeriallyAndWait(Runnable) method blocks the current thread until the method completes, this is useful for cases such as user notification e.g.:

// this code is executing in a separate thread
methodThatTakesALongTime();
Display.getInstance().callSeriallyAndWait(() -> {
  // this occurs on the EDT so I can make changes to UI components
  globalFlag = Dialog.show("Are You Sure?", "Do you want to continue?", "Continue", "Stop");
});
// this code is executing the separate thread
// global flag was already set by the call above
if(!globalFlag) {
   return;
}
otherMethod();
If you’re unsure use callSerially. The use cases for callSeriallyAndWait are rare. When you do need to wait, the overload that accepts a timeout lets background threads marshal results back to the EDT without risking an indefinite stall if the EDT is busy.

If the work you’re posting back to the EDT is expensive and can wait until the UI finishes its current pass, use callSeriallyOnIdle(). This queues the runnable for execution after the EDT completes painting, animations, and any other queued tasks. Deferring longer tasks to the idle queue helps avoid starving animations and transitions when bursts of background callbacks arrive together.

4.2.1. callSerially On The EDT

One of the misunderstood topics is why you’d ever want to invoke callSerially when you’re still on the EDT. This is best explained by example. Say you have a button that has quite a bit of functionality tied to its events e.g.:

  1. A user added an action listener to show a Dialog.

  2. A framework the user installed added some logging to the button.

  3. The button repaints a release animation as its being released.

However, this might cause a problem if the first event being handled (the dialog) causes an issue with the following events. For example, a dialog will block the EDT (using invokeAndBlock), events will keep happening but since the event you’re in "already happened" the button repaint and the framework logging won’t occur. The same problem also occurs if you show a form which might trigger logic that relies on the current form still being present.

One of the solutions to this problem is to wrap the action listeners body with a callSerially. In this case the callSerially will postpone the event to the next cycle (loop) of the EDT and let the other events in the chain complete. Notice that you shouldn’t use this normally since it includes an overhead and complicates application flow, however when you run into issues in event processing this is worth trying to see if its the cause.

You should never invoke callSeriallyAndWait on the EDT since this would effectively mean sleeping on the EDT. That method throws an exception if its invoked from the EDT.

If you need to run logic on the EDT but must ensure nothing inside it blocks, the Display class also provides invokeWithoutBlocking() and invokeWithoutBlockingWithResultSync(). These helpers temporarily disable invokeAndBlock() during the runnable. Any nested call to invokeAndBlock() while blocking is disabled results in a BlockingDisallowedException. Framework code that wraps user callbacks can use these methods to guard against accidental nested blocking that would otherwise deadlock or stall the UI, yet still obtain a return value when needed via invokeWithoutBlockingWithResultSync().

4.3. Debugging EDT Violations

Two types of EDT violations exist:

  1. Blocking the EDT thread so the UI performance is considerably slower.

  2. Invoking UI code on a separate thread

Codename One provides a tool to help you detect some of these violations some caveats may apply though…

It’s an imperfect tool. It might fire "false positives" meaning it might detect a violation for legal code and it might miss some illegal calls. However, it’s a valuable tool in the process of detecting hard to track bugs that are sometimes reproducible on the devices (due to race condition behavior).

To activate this tool select the Debug EDT menu option in the simulator and pick the level of output you wish to receive:

Debug EDT
Figure 13. Debug EDT

Full output will include stack traces to the area in the code that’s suspected in the violation.

4.4. Invoke And Block

Invoke and block is the exact opposite of callSeriallyAndWait(), it blocks the EDT and opens a separate thread for the runnable call. This functionality is inspired by the Foxtrot API, which is a remarkably powerful tool most Swing developers don’t know about.

This is best explained by an example. Typical Java code reads as a single sequence as such:

doOperationA();
doOperationB();
doOperationC();

This works well normally but on the EDT it might be a problem, if one of the operations is slow it might slow the whole EDT (painting, event processing etc.). Normally you can move operations into a separate thread e.g.:

This means that operation C will happen in parallel to operation B which might be a problem…​
For example, instead of using operation names lets use a more "real world" example:

updateUIToLoadingStatus();
readAndParseFile();
updateUIWithContentOfFile();

Notice that the first and last operations must be conducted on the EDT but the middle operation might be slow! Since updateUIWithContentOfFile needs readAndParseFile to occur before it starts doing the new thread won’t be enough.

A simplistic approach is to do something like this:

updateUIToLoadingStatus();
new Thread() {
    public void run() {
          readAndParseFile();
          updateUIWithContentOfFile();
    }
}.start();

However, updateUIWithContentOfFile should be executed on the EDT and not on a random thread. The right way to do this would therefore be something like this:

updateUIToLoadingStatus();
new Thread() {
    public void run() {
          readAndParseFile();
          Display.getInstance().callSerially(new Runnable() {
               public void run() {
                     updateUIWithContentOfFile();
               }
          });
    }
}.start();

This is legal and would work reasonably well, however it gets complicated as you add more and more features that need to be chained serially after all these are 3 methods!

Invoke and block solves this in a unique way you can get almost the exact same behavior by using this:

updateUIToLoadingStatus();
Display.getInstance().invokeAndBlock(new Runnable() {
    public void run() {
          readAndParseFile();
    }
});
updateUIWithContentOfFile();

Or this with Java 8 syntax:

updateUIToLoadingStatus();
Display.getInstance().invokeAndBlock(() -> readAndParseFile());
updateUIWithContentOfFile();

Invoke and block effectively blocks the current EDT in a legal way. It spawns a separate thread that runs the run() method and when that run method completes it goes back to the EDT.

All events and EDT behavior still work while invokeAndBlock is running, this is because invokeAndBlock() keeps calling the main thread loop internally.

Notice that invokeAndBlock comes at a slight performance penalty. Also notice that nesting invokeAndBlock calls (or over using them) isn’t recommended.
However, they’re convenient when working with multiple threads/UI.

Even if you never call invokeAndBlock directly you’re probably using it indirectly in APIs such as Dialog that show a dialog while blocking the current thread e.g.:

public void actionPerformed(ActionEvent ev) {
  // will return true if the user clicks "OK"
  if(!Dialog.show("Question", "How Are You", "OK", "Not OK")) {
  // ask what went wrongnull
  }
}

Notice that the dialog show method will block the calling thread until the user clicks OK or Not OK…​

Other APIs such as NetworkManager.addToQueueAndWait() also make use of this feature. Pretty much every "AndWait" method or blocking method uses this API internally!

To explain how invokeAndBlock works you can return to the sample above of how the EDT works:

while(codenameOneRunning) {
     performEventCallbacks();
     performCallSeriallyCalls();
     drawGraphicsAndAnimations();
     sleepUntilNextEDTCycle();
}

invokeAndBlock() works in a similar way to this pseudo-code:

void invokeAndBlock(Runnable r) {
    openThreadForR(r);
    while(r is still running) {
         performEventCallbacks();
         performCallSeriallyCalls();
         drawGraphicsAndAnimations();
         sleepUntilNextEDTCycle();
    }
}

The EDT is effectively "blocked" but invokeAndBlock "redoes" it from within…​

As you can see this is a simple approach for thread programming in UI, you don’t need to block your flow and track the UI thread. You can program in a way that seems sequential (top to bottom) but uses multi-threading correctly without blocking the EDT.

5. Events

Most events in Codename One are routed via the high-level events (for example, action listener) but sometimes you need access to low-level events (for example, when drawing via Graphics) that provide more fine grained access. Typically working with the higher level events is far more potable since it might map to different functionality on different devices.

5.1. High-level events

High-level events are broadcast using an addListener/setListener - publish/subscribe system. Most of them are channeled via the EventDispatcher class which further simplifies that and makes sending events far easier.

All events are fired on the Event Dispatch Thread, the EventDispatcher makes sure of that.

5.1.1. Chain of events

Since all events fire on the EDT some complexities occur. E.g.:

You have two listeners monitoring the same event (or related events for example, pointer event and button click event both of which will fire when the button is touched).

When the event occurs you can run into a scenario like this:

  1. First event fires

  2. It shows a blocking dialog or invokes an "AndWait" API

  3. Second event fires after the dialog was dismissed!

This happens because events are processed in-order per cycle. Since the old EDT cycle is stuck (because of the Dialog) the rest of the events within the cycle can’t complete. New events are in a new EDT cycle so they can finish fine!

A workaround to this issue is to wrap the code in a callSerially, you shouldn’t do this universally as this can create a case of shifting the problem to the next EDT cycle. But, using callSerially will allow the current cycle to flush which should help.

Another workaround for the issue is avoiding blocking calls within an event chain.

Why a blocking call in the first listener delays the second one
Figure 14. One batch, walked in order

5.1.2. Action events

The most common high-level event is the ActionListener which allows binding a generic action event to pretty much anything. This is so ubiquitous in Codename One that it’s even used for networking (as a base class) and for some low-level event options.

For example, you can bind an event callback for a Button by using:

Button b = new Button("Click Me");
b.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ev) {
        // button was clicked, you can do anything you want herenull
    }
});

Or thanks to the Java 8 lambdas you can write it as:

Button b = new Button("Click Me");
b.addActionListener((ev) -> {
    // button was clicked, you can do anything you want here.
});

Notice that the click will work whether the button was touched using a mouse, finger or keypad shortcut seamlessly with an action listener. Many components work with action events for example, buttons, text components, slider etc.

Quite a few high-level event types exist that are more specific to requirements.

Types of action events

When an action event is fired it’s given a type, but this type might change as the event evolves for example, a command triggered by a pointer event won’t include details of the original pointer event.

You can get the event type from getEventType(), this also gives you a rather exhaustive list of the possible event types for the action event.

Modern gesture components also publish custom action types. For example, SwipeableContainer dispatches ActionEvent.Type.Swipe when the top component is fully opened, allowing code to react to swipe gestures without monitoring low-level drags. Listening for these higher level events keeps gesture handling portable across touch and desktop targets.

Source of event

ActionEvent has a source object, what that source is depends on the event type. For most component based events this is the component but there are some nuances.

The getComponent() method might not get the actual component. In case of a lead component such as MultiButton the underlying Button will be returned and not the MultiButton itself.

To get the component that you would logically think of as the source component use the getActualComponent() method.

Event consumption

An ActionEvent can be consumed, once consumed it will no longer proceed down the chain of event processing. This is useful for some cases where you would like to block behavior from proceeding down the path.

For example, the event dispatch thread allows you to listen to errors on the EDT using:

Display.getInstance().addEdtErrorHandler((e) -> {
    Exception err = (Exception)e.getSource();
    // null
});

This will work great but you will still get the default error message from the EDT over that exception. To prevent the event from proceeding to the default error handling you can do this:

Display.getInstance().addEdtErrorHandler((e) -> {
    e.consume();
    Exception err = (Exception)e.getSource();
    // null
});

Notice that you can check if an event was already consumed using the isConsumed() method but it’s pretty unlikely that you will receive a consumed event as the system will stop sending it.

NetworkEvent

NetworkEvent is a subclass of ActionEvent that’s passed to actionPerformed callbacks made in relation to generic network code. For example:

NetworkManager.getInstance().addErrorListener(new ActionListener<NetworkEvent>() {
    public void actionPerformed(NetworkEvent ev) {
        // now we have access to the methods on NetworkEvent that provide more information about the network specific flags
    }
});

Or with Java 8 lambdas:

NetworkManager.getInstance().addErrorListener((ev) -> {
    // now we have access to the methods on NetworkEvent that provide more information about the network specific flags
});

The NetworkEvent allows the networking code to reuse the EventDispatcher infrastructure and to simplify event firing through the EDT. But you should notice that some code might not be equivalent for example, you could do this to read the input stream:

ConnectionRequest r = new ConnectionRequest() {
    @Override
    protected void readResponse(InputStream input) throws IOException {
        // read the input stream
    }
};

Or you can do something similar using this code:

ConnectionRequest r = new ConnectionRequest();
r.addResponseListener((e) -> {
    byte[] data = (byte[])e.getMetaData();
    // work with the byte data
});

These seem similar but they have one important distinction. The latter code is invoked on the EDT, so if data is big it might slow down processing. The ConnectionRequest is invoked on the network thread and so can process any amount of data without slowing down the UI.

MessageEvent and the Cross-Platform message bus

Bridging to native code often means passing messages between Codename One Java and platform specific code. The cross-platform message bus provides a high-level abstraction for that by letting you post messages to the native layer and subscribe for messages that originate there. Use Display.postMessage() to send an MessageEvent to the platform, and Display.addMessageListener() to receive events that arrive from native code, JavaScript bridges, or background services. Message events include helpers like isPromptForAudioRecorder(), isPromptForAudioPlayer(), and getPromptPromise() that allow you to hook into permission prompts emitted by the JavaScript port so custom UI can respond to platform requests while keeping the event dispatch on the EDT. This API complements NetworkEvent by covering native-to-Java messaging without requiring direct low-level callbacks.

5.1.3. DataChangedListener

The DataChangedListener is used in several places to show that the underlying model data has changed:

  • TextField - the text field provides an action listener but that "fires" when the data input is complete. DataChangedListener fires with every key entered and thus allows functionality such as "auto complete" and is indeed used internally in the Codename One AutoCompleteTextField.

  • TableModel & ListModel - the model for the Table class notifies the view that its content has changed via this event, thus allowing the UI to refresh.

There is an exhaustive example of search that’s implemented using the DataChangedListener in the Toolbar section.

5.1.4. FocusListener

The focus listener allows you to track the "selected" or focused component. It isn’t as useful as it used to be in feature phones.

You can bind a focus listener to the Component itself and receive an event when it gained focus, or you can bind the listener to the Form and receive events for every focus change event within the hierarchy.

5.1.5. ScrollListener

ScrollListener allows tracking scroll events so UI elements can be adapted if necessary.

Scrolling is seamless and this event isn’t necessary, but if developers wish to "shrink" or "fade" an element on scrolling this interface can be used to achieve that. Notice that you should bind the scroll listener to the actual scrollable component and not to an arbitrary component.

For example, in this code from the Flickr demo the Toolbar is faded based on scroll position:

public class CustomToolbar extends Toolbar implements ScrollListener {
    private int alpha;

    public CustomToolbar() {
    }

    public void paintComponentBackground(Graphics g) {
        int a = g.getAlpha();
        g.setAlpha(alpha);
        super.paintComponentBackground(g);
        g.setAlpha(a);
    }

    public void scrollChanged(int scrollX, int scrollY, int oldscrollX, int oldscrollY) {
        alpha = scrollY;
        alpha = Math.max(alpha, 0);
        alpha = Math.min(alpha, 255);
    }
}
There is a better way of implementing this exact effect using title animations illustrated here.

5.1.6. SelectionListener

The SelectionListener event is used to broadcast list model selection changes to the list view. Since list supports the ActionListener event callback its the better option since it’s more coarse grained.

SelectionListener gets fired too often for events and that might result in a performance penalty. When running on non-touch devices list selection could be changed with the keypad and a specific fire button click would fire the action event, for those cases SelectionListener made a lot of sense. But, in touch devices this API isn’t as useful.

5.1.7. StyleListener

StyleListener allows components to track changes to the style objects. For example, if the developer does something like:

cmp.getUnselectedStyle().setFgColor(0xffffff);

This will trigger a style event that will eventually lead to the component being repainted. This is quite important for the component class but not an important event for general user code. It’s recommended that developers don’t bind a style listener.

5.1.8. Component state change events

Component instances now publish lifecycle hooks that fire when they become initialized on a form and when they’re removed. You can subscribe with Component.addStateChangeListener() to receive ComponentStateChangeEvent instances that show whether the component is transitioning to the initialized state. This is useful for running setup or teardown logic alongside focus, scroll, and selection listeners.

5.1.9. Event dispatcher

When creating your own components and objects you sometimes want to broadcast your own events, for that purpose Codename One has the EventDispatcher class which saves a lot of coding effort in this regard. For example, if you wish to provide an ActionListener event for components you can add this to your class:

private final EventDispatcher listeners = new EventDispatcher();

public void addActionListener(ActionListener a) {
    listeners.addListener(a);
}
public void removeActionListener(ActionListener a) {
    listeners.removeListener(a);
}

Then when you need to broadcast the event use:

private void fireEvent(ActionEvent ev) {
    listeners.fireActionEvent(ev);
}

5.2. Low-level events

Low-level events map to "system" events directly. Touch events are considered low-level since they might expose platform specific nuances to your code.

For example, one platform might send many events during drag while another might send a few. The high-level event handling hides those complexities but some of them trickle down into the low-level event handling.

Codename One tries to hide some complexities from the low-level events as well. But, due to the nature of the event types it’s a more challenging task.

Low-level events can be bound in one of 3 ways:

  • Use one of the add listener methods in Form for example, addPointerPressedListener.

  • Override one of the event callbacks on Form

  • Override one of the event callbacks on a Component.

That last one depends on the event. A key callback on an ordinary Component only fires while that component holds focus, because Form routes key events to the focused one - the exception is a key the menu bar claims, which Form.keyPressed hands to MenuBar first. That exception has its own exception: focusedHandlesInput gives a printable key back to the focused component when it consumes raw text input, which is how a focused text editor keeps typing out of the menu bar.

A pointer callback has no focus prerequisite at all, and three things about its target are worth knowing. Form.pointerPressed resolves the lead parent of whatever sits under the touch, so isEnabled() and isFocusable() are asked of that parent rather than of the component you pressed. The callback itself goes to the lead component, which is the class to override or attach a listener to. And focus is assigned only when the lead parent is focusable and enabled and the press isn’t a scroll wheel - in the content pane both before the callback and again after it, so moving focus from inside a pointer callback there can be undone the moment it returns.

The path a pointer event takes from the native callback to your listener
Figure 15. How one touch reaches your code

Each of those has advantages and disadvantages, specifically:

  • 'Form' based events and callbacks deliver pointer events in the 'Form' coordinate space.

  • 'Component' based key events require focus, pointer events don’t

  • 'Form' based events can block existing functionality from proceeding through the event chain for example, you can avoid calling super in a form event and thus block other events from happening (for example, block a listener or component event from triggering).

Table 1. Event type map

Listener

Override Form

Override Component

Coordinate System

Form

Form

Component

Block current functionality

Yes, just avoid super

Partially (event consume)

No

5.2.1. Low-level event types

There are two basic types of low-level events: Key and Pointer.

Key events are relevant to physical keys and won’t trigger on virtual keyboard keys, to track those use a TextField with a DataChangedListener as mentioned above.

The pointer events (touch events) can be intercepted by overriding one or more of these methods in Component or Form. Notice that unless you want to block functionality you should probably invoke super when overriding:

public void pointerDragged(int[] x, int[] y)
public void pointerDragged(final int x, final int y)
public void pointerPressed(int[] x, int[] y)
public void pointerPressed(int x, int y)
public void pointerReleased(int[] x, int[] y)
public void pointerReleased(int x, int y)
public void pointerHover(int[] x, int[] y)
public void pointerHoverPressed(int[] x, int[] y)
public void pointerHoverReleased(int[] x, int[] y)
public void longPointerPress(int x, int y)
public void keyPressed(int keyCode)
public void keyReleased(int keyCode)
public void keyRepeated(int keyCode)

Notice that most pointer events have a version that accepts an array as an argument, this allows for multi-touch event handling by sending all the touched coordinates. Desktop and pen-enabled devices can also trigger hover events without a press. To respond to those you can override the pointerHover* callbacks on Form or Component, which are invoked before a button receives focus or a drag begins on those platforms.

While you can override longPointerPress, there is no need. The dedicated Component.addLongPressListener() helper wires long press detection into an action listener so you can keep gesture logic in the high-level API.

Drag lifecycles also expose a completion hook. When Component.addDragFinishedListener() is registered it receives ActionEvent.Type.DragFinished once the framework has completed its cleanup, allowing you to reset state or trigger follow-up actions that should occur after the drag image is hidden.

5.2.2. Drag event sanitation

Drag events are quite difficult to handle across devices. Some devices send a ridiculous number of events for even the lightest touch while others send too little. It seems like too many drag events wouldn’t be a problem, but if you drag over a button then it might disable the buttons action event (since this might be the user trying to scroll).

Drag sensitivity is about the component being dragged which is why you have the method getDragRegionStatus that allows you to "hint" to the drag API whether you’re interested in drag events or not and if so in which directional bias.

For example, if your component is a painting app where you’re trying to draw using drag gestures you would use code such as:

public class MyComponent extends Component {
    protected int getDragRegionStatus(int x, int y) {
        return DRAG_REGION_LIKELY_DRAG_XY;
    }
}

This indicates that you want all drag events on both AXIS to be sent as soon as possible. Notice that this doesn’t disable event sanitation.

5.3. BrowserNavigationCallback

The BrowserNavigationCallback isn’t quite an "event" but there is no real "proper" classification for it.

The callback method of this interface is invoked off the EDT! You must NEVER block this method and must not access UI or Codename One sensitive elements in this method!

The browser navigation callback is invoked directly from the native web component as it navigates to a new page. Because of that it’s invoked on the native OS thread and gives you a unique opportunity to handle the navigation ourselves as you see fit. That’s why it MUST be invoked on the native thread, since the native browser is pending on your response to that method, spanning an invokeAndBlock/callSerially would be to slow and would bog down the browser.

6. Device Input and Form Factors

Codename One runs on a wide range of hardware, from phones and tablets to desktops, foldables, and devices driven by a mouse or a stylus. This chapter covers the cross-platform APIs that expose that hardware: rich pointer detail (mouse buttons, pen pressure and tilt, the pointing device type), the mouse wheel, foldable device posture, and multi-display / desktop-window awareness.

These APIs are additive: on a device or platform that doesn’t report a given capability the value falls back to a sensible default, so a single code base keeps working everywhere.

6.1. Rich pointer events

The classic pointerPressed, pointerReleased and pointerDragged callbacks carry only the x/y coordinates of the touch. Modern devices provide far more detail: which mouse button was used, the kind of pointing device (finger, mouse, stylus or eraser), the pressure applied, the stylus tilt, the contact area and the keyboard modifiers held at the time.

That detail is exposed through the immutable PointerEvent snapshot. There are two ways to read it.

6.1.1. From an ActionEvent

Any pointer listener receives an ActionEvent; call getPointerEvent() on it:

myComponent.addPointerPressedListener(e -> {
    PointerEvent pe = e.getPointerEvent();
    if (pe.isSecondaryButton()) {
        showContextMenu(pe.getX(), pe.getY());
    }
    System.out.println("pressure=" + pe.getPressure() + " type=" + pe.getPointerType());
});

6.1.2. By polling

When you’re inside a pointer callback you can also poll the current values directly from CN (or Display), mirroring the existing CN.isShiftKeyDown() family:

int button = CN.getPointerButton();      // PointerEvent.BUTTON_PRIMARY, BUTTON_SECONDARY, ...
float pressure = CN.getPointerPressure(); // 0.0 - 1.0, defaults to 1.0
boolean pen = CN.isStylusPointer();
PointerEvent current = CN.getCurrentPointerEvent();
Values have safe defaults. On a plain touch screen the button is BUTTON_PRIMARY, the pressure is 1.0 and the type is TYPE_TOUCH (or TYPE_UNKNOWN on ports that don’t classify the device).

6.2. Two and three button mice

PointerEvent.getButton() returns one of BUTTON_PRIMARY, BUTTON_SECONDARY, BUTTON_MIDDLE, BUTTON_BACK or BUTTON_FORWARD. CN.getPressedButtonMask() returns a bitmask of every button currently held (MASK_PRIMARY, MASK_SECONDARY, …​), which is useful during a drag.

The real button is reported on every desktop port - macOS, Windows and Linux - and in the browser, so the right, middle and (where the mouse has them) back and forward buttons are all distinguished. On a plain touch screen there is only the primary button.

For the common case of a context menu, use the unified addContextMenuListener. It fires for a secondary (right) mouse click, a stylus barrel button click and a long press, so the same code handles desktop and touch:

label.addContextMenuListener(e -> {
    e.consume(); // suppress the normal click/long-press handling
    showMyContextMenu(e.getX(), e.getY());
});

6.3. Mouse wheel and trackpad scrolling

By default the mouse wheel and trackpad scroll a scrollable container automatically. To react to the wheel yourself - for example control plus wheel to zoom, or horizontal scrolling - add a addMouseWheelListener. The listener receives a WheelEvent; consuming it prevents the default scroll.

A positive getDeltaY() reveals content above (the user scrolled down); a positive getDeltaX() reveals content to the left. isPrecise() is true for high resolution devices such as trackpads. On the desktop simulator, hold shift while turning the wheel to produce horizontal scrolling.

WheelEvent is a single universal scroll-gesture API: it’s fed by the mouse wheel and trackpad on the desktop, by the wheel / external trackpad on Android, and by the trackpad, Magic Mouse and mouse wheel on iOS and iPadOS (captured natively and routed through the same pipeline). Continuous trackpad scrolling reports isPrecise() == true, while a notched wheel reports false. On the Apple Watch the Digital Crown also feeds this same pipeline, so a list scrolls under the crown and a mouse wheel listener receives the crown as a WheelEvent.

6.4. Trackpad gestures (magnify and rotate)

Beyond scrolling, the trackpad reports magnify (pinch) and rotate gestures. Override pinch(float scale) to zoom and rotation(float radians) to rotate; both return true to mark the gesture as handled. pinch is also driven by a two finger pinch on touch screens, so the same code works on mobile and the desktop.

The trackpad gestures are wired on every desktop port: the macOS trackpad, the Windows touch screen and gesture-capable touchpads (through the system WM_GESTURE messages), and the Linux touchpad (through the GTK touchpad gesture events). scale is an incremental zoom factor (just above or below 1.0) and radians is the incremental rotation since the previous callback, so accumulate them to track the total.

A Windows precision touchpad usually reports a pinch as control plus wheel rather than a system gesture, so it also arrives through the universal wheel API. Handle that case with a addMouseWheelListener that checks isControlDown() (shown above) if you target those devices.

6.5. Stylus and pen support

When a stylus is used (Apple Pencil, S-Pen, Surface Pen) the pointer type is TYPE_STYLUS, or TYPE_ERASER for the eraser end. The PointerEvent then also carries:

  • getPressure() - normalized pressure between 0.0 and 1.0.

  • getTiltX() / getTiltY() - tilt in degrees (altitude and azimuth on iOS).

  • getContactSize() - normalized size of the contact area.

For drawing surfaces a dedicated addStylusListener fires on press, drag and release only when the pointer is a stylus or eraser:

drawingArea.addStylusListener(e -> {
    PointerEvent pe = e.getPointerEvent();
    float width = 1f + pe.getPressure() * 9f; // pressure controls stroke width
    if (pe.isEraser()) {
        erase(pe.getX(), pe.getY());
    } else {
        drawPoint(pe.getX(), pe.getY(), width);
    }
});

Pen hover (the pen moving above the screen without touching, available on devices such as the S-Pen and the M2 iPad with Apple Pencil) flows through the existing pointerHover callbacks; the snapshot reports isHovering() as true.

Touch-enabled desktops are handled too: on a Windows or Linux PC with a touch screen the finger reports TYPE_TOUCH, and a Windows pen reports TYPE_STYLUS, so the same drawing and gesture code runs on a touch laptop as on a phone. Display.getInstance().isTouchScreenDevice() is true on those machines.

6.6. Foldable devices and posture

Foldable and dual screen devices (Galaxy Fold, Galaxy Flip, Pixel Fold, Surface Duo) change shape at runtime. Query the live posture through DevicePosture:

DevicePosture p = CN.getDevicePosture();
// isTableTop() is true for book posture too, so check the hinge is
// horizontal before laying out top-and-bottom
if (p.isFoldable() && p.isTableTop()
        && p.getFoldOrientation() == DevicePosture.FOLD_ORIENTATION_HORIZONTAL) {
    layoutForTableTop(p.getFoldBounds(null));
}
  • getPosture() - POSTURE_FLAT, POSTURE_HALF_OPENED, POSTURE_CLOSED or POSTURE_UNKNOWN.

  • getHingeAngle() - hinge angle in degrees (-1 when unknown).

  • getFoldOrientation() - FOLD_ORIENTATION_VERTICAL, FOLD_ORIENTATION_HORIZONTAL or FOLD_ORIENTATION_NONE.

  • getFoldBounds(Rectangle) - the region the hinge occludes, in display coordinates, or null when there is no separating fold. Treat it like Form.getSafeArea(): keep interactive content out of it, or split a master and detail layout across the two halves.

React to fold changes with a posture listener:

class FoldAwareForm extends Form {
    private ActionListener postureListener;

    protected void initComponent() {
        super.initComponent();
        postureListener = e -> relayoutForPosture(CN.getDevicePosture());
        CN.addPostureListener(postureListener);
    }

    protected void deinitialize() {
        // CN registers on the singleton Display, so a screen that never
        // unregisters stays reachable and keeps receiving posture changes
        CN.removePostureListener(postureListener);
        super.deinitialize();
    }
}

To exercise this in the desktop simulator, use the Simulate → Foldable menu: enable foldable mode, then pick a posture (flat, half-opened or closed), the fold orientation (vertical or horizontal) and the hinge angle. The running app receives the same posture changes and listener callbacks it would on a real foldable device.

Foldable support on Android is opt-in so it never adds weight to apps that don’t use it. Enable it with the android.foldableSupport=true build hint (the version can be overridden with android.windowVersion). Note that the hinge angle isn’t available on Android, so getHingeAngle() returns -1 there.

6.7. Desktop windowing and external displays

Some mobile devices run in a desktop windowing mode where the app shares the screen with other windows: Samsung DeX, Android desktop windowing and iPad Stage Manager. CN.isDesktopMode() reports this. It’s distinct from CN.isDesktop(), which reports a genuine desktop platform (Windows, macOS or Linux).

CN.getDisplayCount() returns the number of attached displays and CN.isExternalDisplayConnected() is a convenience for getDisplayCount() > 1. On the desktop port these reflect the real monitors attached to the machine.

6.8. Apple TV remote

On Apple TV the Siri Remote is delivered through the standard key handling, so the same keyPressed/keyReleased and game-key code you write for other platforms works on the TV. The directional buttons map to the arrow / game keys, the click maps to enter (fire), the menu button maps to the back key, and play/pause maps to the media play/pause key. No TV specific API is required.

User interface

7. Basics: Themes, styles, components, and layouts

Start with a brief overview of the core ideas in Codename One. This chapter revisits them in more detail as it goes on.

7.1. Components

Every button, label, or other element on the screen in a Codename One application is a Component. This is a simplified version of the class hierarchy:

The Core Component Class Hierarchy
Figure 16. The Core Component Class Hierarchy

The Form is a special Component. It’s the root component shown to the user. Container is a Component type that can hold other components. That lets you create elaborate hierarchies by nesting Container instances.

Component UML
Figure 17. Component UML

A Codename One application is effectively a series of forms, but one Form can be visible at a time. The form contains everything on the screen. Under the hood, the Form has a few separate parts:

Structure of a Form
Figure 18. Structure of a Form
  • Content Pane - this is the body of the Form. When you add a Component to the Form, it goes into the content pane. The content pane scrolls vertically by default.

  • Title Area - you can’t add directly to this area. The title area is managed by the Toolbar class. Toolbar sits at the top of the form and handles the title design. The title area has two parts:

    • Title of the Form and its commands (the buttons on the right and left of the title)

    • Status Bar - on iOS, the top area leaves room for the notch, battery, clock, and similar indicators. Without that space, those elements would overlap the title.

Now that the structure is clear, open the Java file TodoApp.java in the project you created. You should see the lines that set up the UI in the start() method:

7.1.1. Layout managers

A layout manager decides the size and location of components within a Container. Every Container has a layout manager. The default layout manager is FlowLayout.

What each Codename One layout manager is for
Figure 19. What each layout manager is for

To understand layouts, first understand a basic concept about Component: each component has a “preferred size.” That’s the size a component wants to occupy. For example, a Label uses the exact size needed to fit the label text, icon, and padding.

Understanding Preferred Size

The Component class contains many useful methods. One of the most important is calcPreferredSize(), which recalculates the size a component wants when something changes.

By default Codename One invokes the getPreferredSize() method rather than calcPreferredSize() directly.
getPreferredSize() invokes calcPreferredSize() and caches the value.

The preferred size depends on internal constraints such as font size, border sizes, and padding.

When a layout manager positions and sizes the component, it MIGHT take the preferred size into account. It can also ignore it entirely.

For example, FlowLayout gives components their preferred size wherever the row has space for it, narrowing one that’s too wide and expanding them all when fillRows is set, while BorderLayout resizes the center component by default and the other components along one axis.

You can define a group of components to have the same preferred width or height by using the setSameWidth and setSameHeight methods, for example:

Listing 3. setSameWidth/Height
Component.setSameWidth(cmp1, cmp2, cmp3, cmp4);
Component.setSameHeight(cmp5, cmp6, cmp7);

Codename One has a setPreferredSize method that lets developers explicitly request a component size. But, that caused many problems. For example, preferred size should change with device orientation or similar operations. The API also encouraged accidental hardcoding of UI values such as forcing pixel sizes. As a result, the method was deprecated.

Use setSameWidth and setSameHeight when you need sizing alignment. Use setHidden when you need to hide a component. As a last resort, override calcPreferredSize.

A layout manager places a component based on its own logic and the preferred size, sometimes called the “natural size.” A FlowLayout walks the components in the order they were added and sizes them one after another. When it reaches the end of the row, it moves to the next row.

Use FlowLayout for simple things
FlowLayout is great for simple cases, but it has issues when components change size dynamically, such as a text field. In those cases, it can choose bad line breaks and take up too much space.
Layout Manager Primer Part I
Figure 20. Layout Manager Primer Part I
Layout Manager Primer Part II
Figure 21. Layout Manager Primer Part II

Scrolling doesn’t work well for all layout types because the positioning algorithm within a layout can break. Scrolling on the Y axis works well for BoxLayout Y, which is why it was picked for the TodoForm:

Table 2. Scrolling in Layout Managers
LayoutScrollable

Flow Layout

Possible on Y axis only

Border Layout

Scrolling is blocked

Box Layout Y

Scrollable only on the Y axis

Box Layout X

Scrollable only on the X axis

Grid Layout

Scrollable

LayeredLayout

Not scrollable (usually)

Nesting Scrollable Containers

Only one element can be scrollable within the hierarchy. Otherwise, if you drag your finger over the Form, Codename One can’t know which element you want to scroll. By default, the form’s content pane scrolls on the Y axis unless you disable it explicitly. Setting the layout to BorderLayout disables scrolling implicitly.

It’s fine to use non-scrollable layouts such as BorderLayout inside a scrollable container. In the TodoApp, for example, TodoItem uses BorderLayout inside a scrollable BoxLayout Form.

Layouts can be divided into two distinct groups:

  • Constraint Based - BorderLayout (and a few others such as GridBagLayout, MigLayout, and TableLayout)

  • Regular - All the other layout managers

When you add a Component to a Container with a regular layout you do so with a simple add method:

Listing 4. Adding to a Regular Container
Container cnt = new Container(BoxLayout.y());
cnt.add(new Label("Just Added"));

This works great for regular layouts but might not for constraint based layouts. A constraint based layout accepts another argument. For example: BorderLayout needs a location for the Component:

Listing 5. Adding to a Regular Container
cnt.add(NORTH, new Label("Just Added"));

This line assumes you have an import static com.codename1.ui.CN.*; in the top of the file. In BorderLayout (which is a constraint based layout) placing an item in the NORTH places it in the top of the Container.

The CN class is a class that contains many static helper methods and functions. It’s specifically designed for static import in this way to help keep your code terse
Static Global Context

The CN class is a thin wrapper around features in Display, NetworkManager, Storage, FileSystemStorage etc. It also adds common methods and constants from several other classes so Codename One code feels more terse for example, you can do:

That’s optional, if you don’t like static imports you can just write CN. for every element

From that point on you can write code that looks like this:

callSerially(() -> runThisOnTheEDT());

Instead of:

Display.getInstance().callSerially(() -> runThisOnTheEDT());

The same applies for most network manager calls e.g.:

addToQueue(myConnectionRequest);

Instead of:

NetworkManager.getInstance().addToQueue(myConnectionRequest);

Some things were changed so you won’t have too many conflicts for example, Log.p or Log.e would have been problematic so you now have:

log("my log message");
log(myException);

Instead of Display.getInstance().getCurrent() you now have getCurrentForm() since getCurrent() is too generic. For most methods you should just be able to remove the NetworkManager or Display access and it should "just work."

The motivation for this is threefold:

  • Terse code

  • Small performance gain

  • Cleaner API without some baggage in Display or NetworkManager

Some of your samples in this guide might rely on that static import being in place. This helps you keep the code terse and readable in the code listings.

Terse syntax

Almost every layout allows you to add a component using many variants of the add method:

Listing 6. Versions of add
Container cnt = new Container(BoxLayout.y());
cnt.add(new Label("Just Added")); (1)
cnt.addAll(new Label("Adding Multiple"), (2)
    new Label("Second One"));

cnt.add(new Label("Chaining")). (3)
    add(new Label("Value"));
1Regular add
2addAll accepts many components and adds them in a batch
3add returns the parent Container instance so you can chain calls like that

In the race to make code “tighter” you can make this even shorter. Most layout managers have their own custom terse syntax style for example:

Listing 7. Terse Syntax
Container boxY = BoxLayout.encloseY(cmp1, cmp2); (1)
Container boxX = BoxLayout.encloseX(cmp3, cmp4);
Container flowCenter = FlowLayout. (2)
    encloseCenter(cmp5, cmp6);
1Most layouts have a version of enclose to encapsulate components within
2FlowLayout has variants that support aligning the components on various axes

To sum this up, you can use layout managers and nesting to create elaborate UI’s that implicitly adapt to different screen sizes and device orientation.

Flow Layout
Flow Layout
Figure 22. Flow Layout

Flow layout lets the components "flow" horizontally and break a line when reaching the edge of the container. It’s the default layout manager for containers. Because it’s so flexible it’s also problematic as it can result in wrong preferred size values for the parent Container. This can create a reflow issue, as a result recommend using flow layout for trivial cases. Avoid it for things such as text input etc. As the size of the text input can vary in runtime:

Form hi = new Form("Flow Layout", new FlowLayout());
hi.add(new Label("First")).
    add(new Label("Second")).
    add(new Label("Third")).
    add(new Label("Fourth")).
    add(new Label("Fifth"));
hi.show();

Flow layout also supports terse syntax shorthand such as:

Container flowLayout = FlowLayout.encloseIn(
        new Label("First"),
        new Label("Second"),
        new Label("Third"),
        new Label("Fourth"),
        new Label("Fifth"));

Flow layout can be aligned to the left (the default), to the center, or to the right. It can also be vertically aligned to the top (the default), middle (center), or bottom.

Flow layout aligned to the center
Figure 23. Flow layout aligned to the center
Flow layout aligned to the right
Figure 24. Flow layout aligned to the right
Flow layout aligned to the center horizontally & the middle vertically
Figure 25. Flow layout aligned to the center horizontally & the middle vertically

Components within the flow layout get their natural preferred size by default and aren’t stretched in any axis.

The natural sizing behavior is often used to prevent other layout managers from stretching components. For example: if you have a border layout element in the south and you want it to keep its natural size instead of adding the element to the south directly you can wrap it using parent.add(BorderLayout.SOUTH, FlowLayout.encloseCenter(dontGrowThisComponent)).
Box Layout

BoxLayout places elements in a row (X_AXIS) or column (Y_AXIS) according to box orientation. Box is a simple and predictable layout that serves as the "workhorse" of component lists in Codename One.

You can create a box layout Y using something like this:

Form hi = new Form("Box Y Layout", new BoxLayout(BoxLayout.Y_AXIS));
hi.add(new Label("First")).
    add(new Label("Second")).
    add(new Label("Third")).
    add(new Label("Fourth")).
    add(new Label("Fifth"));

Which results in this

BoxLayout Y
Figure 26. BoxLayout Y

Box layout also supports a shorter terse notation which you use here to show the X axis box:

Container box = BoxLayout.encloseX(new Label("First"),
        new Label("Second"),
        new Label("Third"),
        new Label("Fourth"),
        new Label("Fifth"));
BoxLayout X
Figure 27. BoxLayout X

The box layout keeps the preferred size of its destination orientation and scales elements on the other axis. Specifically X_AXIS will keep the preferred width of the component while growing all the components vertically to match in size. Its Y_AXIS counterpart keeps the preferred height while growing the components horizontally.

This behavior is useful since it allows elements to align as they would all have the same size.

Sometimes the growing behavior in the X axis is undesired, for these cases you can use the X_AXIS_NO_GROW variant.

BoxLayout X_AXIS_NO_GROW
Figure 28. BoxLayout X_AXIS_NO_GROW
FlowLayout vs. BoxLayout.X_AXIS
When applicable recommend BoxLayout over FlowLayout as it acts more consistently in all situations. Another advantage of BoxLayout is the fact that it grows and thus aligns the components in a consistent column or row
Border Layout
Border Layout
Figure 29. Border Layout

Border layout is unique. BorderLayout is a constraint-based layout that can place up to five components in one of the five positions: NORTH, SOUTH, EAST, WEST or CENTER:

Form hi = new Form("Border Layout", new BorderLayout());
hi.add(BorderLayout.CENTER, new Label("Center")).
    add(BorderLayout.SOUTH, new Label("South")).
    add(BorderLayout.NORTH, new Label("North")).
    add(BorderLayout.EAST, new Label("East")).
    add(BorderLayout.WEST, new Label("West"));
hi.show();
The Constraints are Included in the CN class
You can use the static import of the CN class and then the syntax can be add(SOUTH, new Label("South"))

The layout always stretches the NORTH/SOUTH components on the X-axis to fill the container and the EAST/WEST components on the Y-axis. The center component is stretched to fill the remaining area by default. For example, the setCenterBehavior allows you to manipulate the behavior of the center component so it’s placed in the center without stretching.

For example:

Form hi = new Form("Border Layout", new BorderLayout());
((BorderLayout)hi.getLayout()).setCenterBehavior(BorderLayout.CENTER_BEHAVIOR_CENTER);
hi.add(BorderLayout.CENTER, new Label("Center")).
    add(BorderLayout.SOUTH, new Label("South")).
    add(BorderLayout.NORTH, new Label("North")).
    add(BorderLayout.EAST, new Label("East")).
    add(BorderLayout.WEST, new Label("West"));
hi.show();

Results in:

Border Layout with CENTER_BEHAVIOR_CENTER
Figure 30. Border Layout with CENTER_BEHAVIOR_CENTER
Scrolling is Disabled in Border Layout
Because of its scaling behavior scrolling a border layout makes no sense. Container implicitly blocks scrolling on a border layout, but it can scroll its parents/children

For RTL the EAST and WEST values are implicitly reversed as shown in this image:

Border Layout in RTL mode
Figure 31. Border Layout in RTL mode
RTL and Bidi

RTL (Right To Left) or Bidi (bi-directional) are common terms used for languages such as Hebrew, Arabic etc. These languages are written from the right to left direction hence all the UI needs to be “reversed.” Bidi denotes the fact that while the language is written from right to left, the numbers are still written in the other direction hence two directions…​

Preferred Size Still Matters
The preferred size of the center component doesn’t matter in border layout but the preferred size of the sides is. For example: If you place a large component in the SOUTH it will take up the entire screen and won’t leave room for anything
Grid Layout

GridLayout accepts a predefined grid (rows/columns) and grants all components within it equal size based on the dimensions of the largest components.

The main use case for this layout is a grid of icons for example: like one would see in the iPhone home screen

If the number of rows * columns is smaller than the number of components added a new row is implicitly added to the grid. For example, if the number of components is smaller than available cells (won’t fill the last row) blank spaces will be left in place.

In this example you can see that a 2×2 grid is used to add 5 elements, this results in an additional row that’s implicitly added turning the grid to a 3×2 grid implicitly and leaving one blank cell:

Form hi = new Form("Grid Layout 2×2", new GridLayout(2, 2));
hi.add(new Label("First")).
    add(new Label("Second")).
    add(new Label("Third")).
    add(new Label("Fourth")).
    add(new Label("Fifth"));
Grid Layout 2×2
Figure 32. Grid Layout 2×2

When you use a 2×4 size ratio you would see elements getting cropped as you do here. The grid layout uses the grid size first and doesn’t pay too much attention to the preferred size of the components it holds.

Grid Layout 2×4
Figure 33. Grid Layout 2×4

Grid also has an autoFit attribute that can be used to automatically calculate the column count based on available space and preferred width. This is useful for working with UI’s where the device orientation might change.

A terse syntax for working with a grid also exists in two versions, one that uses the "auto-fit" option and another that accepts the number of columns. Here’s a sample of the terse syntax coupled with auto-fit followed by screenshots of the same code in two orientations:

GridLayout.encloseIn(new Label("First"),
    new Label("Second"),
    new Label("Third"),
    new Label("Fourth"),
    new Label("Fifth"));
Grid Layout autofit portrait
Figure 34. Grid Layout autofit portrait
Grid Layout autofit landscape
Figure 35. Grid Layout autofit landscape

7.1.2. Table Layout

The TableLayout is an elaborate constraint based layout manager that can arrange elements in rows/columns while defining constraints to control complex behavior such as spanning, alignment/weight etc.

Note the Different Package for TableLayout
The TableLayout is in the com.codename1.ui.table package and not in the layouts package.
This is because TableLayout was originally designed for the Table class.

Despite being constraint based the TableLayout isn’t strict about constraints and will implicitly add a constraint when one is missing. This is unlike the BorderLayout which will throw an exception in this case.

Unlike GridLayout TableLayout won’t implicitly add a row if the row/column count is wrong
Form hi = new Form("TableLayout", new TableLayout(2, 2));
hi.add(new Label("First"));
hi.add(new Label("Second"));
hi.add(new Label("Third"));
hi.add(new Label("Fourth"));
hi.add(new Label("Fifth"));
hi.show();
2×2 TableLayout with 5 elements, notice that the last element is missing
Figure 36. 2×2 TableLayout with 5 elements, notice that the last element is missing

TableLayout supports the ability to grow the last column which can be enabled using the setGrowHorizontally method. You can also use a shortened terse syntax to construct a TableLayout but since the TableLayout is a constraint based layout you won’t be able to use its full power with this syntax.

The default usage of the encloseIn method below uses the setGrowHorizontally flag:

Container table = TableLayout.encloseIn(2,
        new Label("First"),
        new Label("Second"),
        new Label("Third"),
        new Label("Fourth"),
        new Label("Fifth"));
Form hi = new Form("TableLayout Enclose 2", new BorderLayout());
hi.add(BorderLayout.CENTER, table);
hi.show();
TableLayout.encloseIn() with default behavior of growing the last column
Figure 37. TableLayout.encloseIn() with default behavior of growing the last column
The full potential

TableLayout is a beast, to truly appreciate it you need to use the constraint syntax which allows you to span, align and set width/height for the rows and columns.

TableLayout works with a Constraint instance that can communicate your intentions into the layout manager. Such constraints can include more than one attribute for example: span and height.

TableLayout constraints can’t be reused for more than one component

The constraint class supports the following attributes

Table 3. Constraint Properties

column

The column for the table cell. This defaults to -1 which will place the component in the next available cell

row

Like column, defaults to -1 as well

width

The column width in percentages, -1 will use the preferred size. -2 for width will take up the rest of the available space

height

Like width but doesn’t support the -2 value

spanHorizontal

The cells that should be occupied horizontally defaults to 1 and can’t exceed the column count - current offset.

spanVertical

Like spanHorizontal with the same limitations

horizontalAlign

The horizontal alignment of the content within the cell, defaults to the special case -1 value to take up all the cell space can be either -1, Component.LEFT, Component.RIGHT or Component.CENTER

verticalAlign

Like horizontalAlign can be one of -1, Component.TOP, Component.BOTTOM or Component.CENTER

You need to set width/height to one cell in a column/row

The table layout constraint sample tries to show some unique things you can do with constraints.

The constraint sample below spans the title across all three columns and spans the notes row across two columns:

TableLayout layout = new TableLayout(4, 3);
layout.setGrowHorizontally(true);
Form hi = new Form("Table Layout", layout);

TableLayout.Constraint title = layout.createConstraint();
title.setHorizontalSpan(3);
title.setHorizontalAlign(Component.CENTER);
hi.add(title, new Label("Invoice"));

hi.add(new Label("Item"));
hi.add(new Label("Qty"));
hi.add(new Label("Total"));
hi.add(new Label("Design"));
hi.add(new Label("2"));
hi.add(new Label("$120"));

TableLayout.Constraint notes = layout.createConstraint();
notes.setHorizontalSpan(2);
notes.setHeightPercentage(40);
hi.add(notes, new SpanLabel("Notes span two columns"));
hi.add(new Button("Pay"));

hi.show();

That sample creates its constraints with a shorthand. Written out in full, a constraint is a separate object you configure and then pass in place of the usual layout argument:

TableLayout.Constraint cn = tl.createConstraint();
cn.setWidthPercentage(20);
hi.add(cn, new Label("AAA"));
TableLayout constraints can be used to create elaborate UI’s
Figure 38. TableLayout constraints can be used to create elaborate UI’s
TextMode Layout

TextModeLayout is a unique layout manager. It acts like TableLayout on Android and like BoxLayout.Y_AXIS in other platforms. Internally it delegates to one of these two layout managers so in a sense it doesn’t have as much functionality of its own.

For example: this is a sample usage of TextModeLayout:

TextModeLayout tl = new TextModeLayout(3, 2);
Form f = new Form("Pixel Perfect", tl);
TextComponent title = new TextComponent().label("Title");
TextComponent price = new TextComponent().label("Price");
TextComponent location = new TextComponent().label("Location");
TextComponent description = new TextComponent().label("Description").multiline(true);

f.add(tl.createConstraint().horizontalSpan(2), title);
f.add(tl.createConstraint().widthPercentage(30), price);
f.add(tl.createConstraint().widthPercentage(70), location);
f.add(tl.createConstraint().horizontalSpan(2), description);
f.setEditOnShow(title.getField());
f.show();
TextModeLayout on iOS
Figure 39. TextModeLayout on iOS
TextModeLayout on Android with the same code
Figure 40. TextModeLayout on Android with the same code

As you can see from the code and samples above there is a lot going on under the hood. On Android you want a layout that’s like TableLayout so you can “pack” the entries. On iOS you want a box layout Y kind of layout but you also want the labels/text to align…​

The TextModeLayout isn’t a layout as much as it’s a delegate. When running in the Android mode (which you refer to as the “on top” mode) the layout is almost an exact synonym of TableLayout and in fact delegates to an underlying TableLayout. In fact there is a public final table instance within the layout that you can refer to directly…​

One small difference exists between the TextModeLayout and the underlying TableLayout: your choice to default to align entries to TOP with this mode.

Aligning to TOP is important for error handling for TextComponent in Android otherwise the entries “jump”

When working in the non-android environment you use a BoxLayout on the Y axis as the delegate. One thing you do here differs from a default box layout: grouping. Grouping allows the labels to align by setting them to the same width, internally it invokes Component.setSameWidth(). Since text components hide the labels there is a special group method there that can be used. For example, this is implicit with the TextModeLayout which is pretty cool.

TextModeLayout was created specifically for the TextComponent and InputComponent so check out the section about them in the components chapter.

7.1.3. Layered Layout

When used without constraints, the LayeredLayout places the components in order one on top of the other and sizes them all to the size of the largest component. This is useful when trying to create an overlay on top of an existing component. For example: an "x" button to allow removing the component.

The X on this button was placed there using the layered layout code below
Figure 41. The X on this button was placed there using the layered layout code below

The code to generate this UI is slightly complex and contains few relevant pieces. The truly relevant piece is this block:

hi.add(LayeredLayout.encloseIn(settingsLabel,
        FlowLayout.encloseRight(close)));

You’re doing three distinct things here:

  1. You’re adding a layered layout to the form

  2. You’re creating a layered layout and placing two components within. This would be the equivalent of creating a LayeredLayout Container and invoking add twice

  3. You use FlowLayout to position the X close button in the right position

When used without constraints, the layered layout sizes all components to the exact same size one on top of the other. It requires that you use another container within; to position the components correctly

This is the full source of the example for completeness:

Form hi = new Form("Layered Layout");
int w = Math.min(Display.getInstance().getDisplayWidth(), Display.getInstance().getDisplayHeight());
Button settingsLabel = new Button("");
Style settingsStyle = settingsLabel.getAllStyles();
settingsStyle.setFgColor(0xff);
settingsStyle.setBorder(null);
settingsStyle.setBgColor(0xff00);
settingsStyle.setBgTransparency(255);
settingsStyle.setFont(settingsLabel.getUnselectedStyle().getFont().derive(w / 3, Font.STYLE_PLAIN));
FontImage.setMaterialIcon(settingsLabel, FontImage.MATERIAL_SETTINGS);
Button close = new Button("");
close.setUIID("Container");
close.getAllStyles().setFgColor(0xff0000);
FontImage.setMaterialIcon(close, FontImage.MATERIAL_CLOSE);
hi.add(LayeredLayout.encloseIn(settingsLabel,
        FlowLayout.encloseRight(close)));

Forms have a built in layered layout that you can access through getLayeredPane(), this allows you to overlay elements on top of the content pane.

The layered pane is used internally by components such as InteractionDialog, AutoComplete etc.

Codename One also includes a GlassPane that resides on top of the layered pane. Its useful if you want to "draw" on top of elements but is harder to use than layered pane
Insets and reference components

LayeredLayout supports insets for its children. This effectively allows you to position child components precisely where you want them, relative to their container or siblings. This functionality forms the under-pinnings of the GUI Builder’s Auto layout mode.

As an example, suppose you wanted to position a button in the lower right corner of its container. This can be achieved with LayeredLayout as follows:

Container cnt = new Container(new LayeredLayout());
Button btn = new Button("Submit");
LayeredLayout ll = (LayeredLayout)cnt.getLayout();
cnt.add(btn);
ll.setInsets(btn, "auto 0 0 auto");

The result is:

Button positioned in bottom right using insets

The thing new here is this line:

ll.setInsets(btn, "auto 0 0 auto");

This is called after btn has already been added to the container. It says that you want its insets to be "auto" on the top and left, and 0 on the right and bottom. This insets string follows the CSS notation of top right bottom left (that’s: start on top and go clockwise), and the values of each inset may be provided in pixels (px), millimetres (mm), percent (%), or the special "auto" value. Like CSS, you can also specify the insets using a 1, 2, or 3 values. For example:

  1. "1mm" - Sets 1mm insets on all sides.

  2. "1mm 2mm" - Sets 1mm insets on top and bottom; 2mm on left and right.

  3. "1mm 10% 2mm" - Sets 1mm on top, 10% on left and right, and 2mm on bottom.

  4. "1mm 2mm 1px 50%" - Sets 1mm on top, 2mm on right, 1px on bottom, and 50% on left.

auto insets

The special "auto" inset indicates that it’s a flexible inset. If all insets are set to "auto," then the component will be centered both horizontally and vertically inside its "bounding box."

The "inset bounding box" is the containing box from which a component’s insets are measured. If the component’s insets aren’t linked to any other components, then its inset bounding box will be the inner bounds (that’s: taking padding into account) of the component’s parent container.

If one inset is fixed (that’s: defined in px, mm, or %), and the opposite inset is "auto," then the "auto" inset will allow the component to be its preferred size. If you want to position a component to be centered vertically, and 5mm from the left edge, you could do:

ll.setInsets(btn, "auto auto auto 5mm");

Resulting in:

Button vertically centered 5mm from left edge
Figure 42. Button vertically centered 5mm from left edge

Move it to the right edge with:

ll.setInsets(btn, "auto 5mm auto auto");
% insets

Percent (%) insets are calculated about the inset bounding box. A 50% inset is measured as 50% of the length of the bounding box on the inset’s axis. For example: A 50% inset on top would be 50% of the height of the inset bounding box. A 50% inset on the right would be 50% of the width of the inset bounding box.

Insets, margin, and padding

A component’s position in a layered layout is determined as follows: (Assume that cmp is the component that you’re positioning, and cnt is the container (In pseudo-code):

x = cnt.paddingLeft + cmp.calculatedInsetLeft + cmp.marginLeft
y = cnt.paddingTop + cmp.calculatedInsetTop + cmp.marginTop
w = cnt.width - cnt.verticalScroll.width - cnt.paddingRight - cmp.calculatedInsetRight - cmp.marginRight - x
h = cnt.height - cnt.horizontalScroll.height - cnt.paddingBottom - cmp.calculatedInsetBottom - cmp.marginBottom - y
The calculatedInsetXXX values here will be the same as the corresponding provided inset if the inset has no reference component. If it does have a reference component, then the calculated inset will depend on the position of the reference component.

If no inset is specified, then it’s assumed to be 0. This ensures compatibility with designs that were created before layered layout supported insets.

Component references: Linking components together

If all you need to do is position a component relative to its parent container’s bounds, then mere insets provide you with enough vocabulary to achieve this. But most UIs are more complex than this and require another concept: reference components. Often you will want to position a component relative to another child of the same container. This is also supported.

For example, suppose you want to place a text field in the center of the form (both horizontally and vertically), and have a button placed beside it to the right. Positioning the text field is trivial (setInset(textField, "auto")), but there is no inset that you can provide that would position the button to the right of the text field. To do your goal, you need to set the text field as a reference component of the button’s left inset, which "links" the button’s left inset to the text field. Here is the syntax:

Container cnt = new Container(new LayeredLayout());
LayeredLayout ll = (LayeredLayout)cnt.getLayout();
Button btn = new Button("Submit");
TextField tf = new TextField();
cnt.add(tf).add(btn);
ll.setInsets(tf, "auto")
  .setInsets(btn, "auto auto auto 0")
  .setReferenceComponentLeft(btn, tf, 1f);

This would result in:

Button’s left inset linked to text field
Figure 43. Button’s left inset linked to text field

The two active lines here are the last two:

ll.setInsets(tf, "auto")
  .setInsets(btn, "auto auto auto 0")
  .setReferenceComponentLeft(btn, tf, 1f);
The reference position is defined as the distance, expressed as a fraction of the reference component’s length on the inset’s axis, between the reference component’s leading (outer) edge and the point from which the inset is measured. A reference position of 0 means that the inset is measured from the leading edge of the reference component. A value of 1.0 means that the inset is measured from the trailing edge of the reference component. A value of 0.5 means that the inset is measured from the center of the reference component. Etc. Any floating point value can be used, though the most common values are 0 and 1.

The definition above may make reference components and reference position seem more complex than they are. Some examples:

  1. For a top inset:

    1. referencePosition == 0 ⇒ the inset is measured from the top edge of the reference component.

    2. referencePosition == 1 ⇒ the inset is measured from the bottom edge of the reference component.

  2. For a bottom inset:

    1. referencePosition == 0 ⇒ the inset is measured from the bottom edge of the reference component.

    2. referencePosition == 1 ⇒ the inset is measured from the top edge of the reference component.

  3. For a left inset:

    1. referencePosition == 0 ⇒ the inset is measured from the left edge of the reference component.

    2. referencePosition == 1 ⇒ the inset is measured from the right edge of the reference component.

  4. For a right inset:

    1. referencePosition == 0 ⇒ the inset is measured from the right edge of the reference component.

    2. referencePosition == 1 ⇒ the inset is measured from the left edge of the reference component.

Layers In Codename One

Codename One allows placing components one on top of the other and you commonly use layered layout to do that. The form class has a built-in Container that resides in a layer on top of the content pane of the form.

When you add an element to a form it implicitly goes into the content pane. But, you can use getLayeredPane() and add any Component there. Such a Component will appear above the content pane. Notice that this layer resides below the title area (on the Y axis) and won’t draw on top of that.

When Codename One introduced the layered pane it was instantly useful. But, its popularity caused conflicts. Two separate pieces of code using the layered pane could collide with one another. Codename One solved it with getLayeredPane(Class c, boolean top). This method allocates a layer for a specific class within the layered pane. This way if two different classes use this method instead of the getLayeredPane() method they won’t collide. Each will get its own container in a layered layout within the layered pane seamlessly. The top flag indicates whether you want the layer to be the top most or bottom most layer within the layered pane (assuming it wasn’t created already). This allows you to place a layer that can appear above or below the already installed layers.

You only make use of the layered pane in this book but there are two more layers on top of it. The form layered pane is identical to the layered pane but spans the entire height of the Form (including the title area). As a result the form layered pane is slower as it needs to handle some special cases to support this functionality.

The glass pane is the top most layer, unlike the layered pane it’s purely a graphical layer. You can only draw on the glass pane with a Painter instance and a Graphics object. You can’t add components into that layer.

The Layered Pane
Figure 44. The Layered Pane

7.1.4. GridBag Layout

GridBagLayout was introduced to simplify the process of porting existing Swing/AWT code with a more familiar API. The API for this layout is problematic as it was designed for AWT/Swing where styles were unavailable. As a result it has its own insets API instead of using elements such as padding/margin.

Prefer TableLayout, which is just as capable and integrates better with Codename One.

The sample below is the Java tutorial’s GridBag example, ported to Codename One:

private static Button gridButton(String text) {
    Button button = new Button(text);
    button.setCapsText(false);
    Style style = button.getAllStyles();
    style.setBgColor(0xf4f8ff);
    style.setBgTransparency(255);
    style.setFgColor(0x0d47a1);
    style.setBorder(Border.createLineBorder(1, 0x2b5c9e));
    style.setPaddingUnit(Style.UNIT_TYPE_DIPS);
    style.setPadding(2, 2, 2, 2);
    return button;
}

public static Form createForm() {
    Form hi = new Form("GridBagLayout", new BorderLayout());
    Container grid = new Container(new GridBagLayout());
    Style gridStyle = grid.getAllStyles();
    gridStyle.setPaddingUnit(Style.UNIT_TYPE_DIPS);
    gridStyle.setPadding(4, 4, 4, 4);
    Button button;
    GridBagConstraints c = new GridBagConstraints();
    //natural height, maximum width
    c.fill = GridBagConstraints.HORIZONTAL;
    button = gridButton("One");
    c.weightx = 0.5;
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 0;
    c.gridy = 0;
    grid.addComponent(c, button);

    button = gridButton("Two");
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 0.5;
    c.gridx = 1;
    c.gridy = 0;
    grid.addComponent(c, button);

    button = gridButton("Three");
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 0.5;
    c.gridx = 2;
    c.gridy = 0;
    grid.addComponent(c, button);

    button = gridButton("Long-Named Button 4");
    c.fill = GridBagConstraints.HORIZONTAL;
    c.ipady = 40;      //make this component tall
    c.weightx = 0.0;
    c.gridwidth = 3;
    c.gridx = 0;
    c.gridy = 1;
    grid.addComponent(c, button);

    button = gridButton("5");
    c.fill = GridBagConstraints.HORIZONTAL;
    c.ipady = 0;       //reset to default
    c.weighty = 1.0;   //request any extra vertical space
    c.anchor = GridBagConstraints.PAGE_END; //bottom of space
    c.insets = new Insets(10,0,0,0);  //top padding
    c.gridx = 1;       //aligned with button 2
    c.gridwidth = 2;   //2 columns wide
    c.gridy = 2;       //third row
    grid.addComponent(c, button);
    hi.add(BorderLayout.NORTH, grid);
    return hi;
}

Because of the way GridBag works there’s no terse syntax for it, although one should be possible.

GridBagLayout sample from the Java tutorial running on Codename One
Figure 45. GridBagLayout sample from the Java tutorial running on Codename One

7.1.5. Group Layout

GroupLayout is a layout that would be familiar to the users of the NetBeans GUI builder (Matisse). Its a layout manager that’s hard to use for manual coding but is powerful for some elaborate use cases. Although MigLayout and LayeredLayout might be superior options.

It was originally added during the LWUIT days as part of an internal try to port Matisse to LWUIT. It’s still useful to this day as developers copy and paste Matisse code into Codename One and produce elaborate layouts with drag.

Since the layout is based on an older version of GroupLayout some things need to be adapted in the code or you should use the special "compatibility" library for Matisse to get better interaction. You also recommend tweaking Matisse to use import statements instead of full package names, that way if you use Label changing the awt import to a Codename One import will make it use work for Codename One’s Label.

Unlike any other layout manager GroupLayout adds the components into the container instead of the standard API. This works for GUI builder code but as you can see from this sample it doesn’t make the code readable:

public static Form createForm() {
    Form hi = new Form("GroupLayout");

    Label label1 = new Label();
    Label label2 = new Label();
    Label label3 = new Label();
    Label label4 = new Label();
    Label label5 = new Label();
    Label label6 = new Label();
    Label label7 = new Label();

    label1.setText("label1");

    label2.setText("label2");

    label3.setText("label3");

    label4.setText("label4");

    label5.setText("label5");

    label6.setText("label6");

    label7.setText("label7");

    GroupLayout layout = new GroupLayout(hi.getContentPane());
    hi.setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(GroupLayout.LEADING)
        .add(layout.createSequentialGroup()
            .addContainerGap()
            .add(layout.createParallelGroup(GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .add(label1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(LayoutStyle.RELATED)
                    .add(layout.createParallelGroup(GroupLayout.LEADING)
                        .add(label4, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                        .add(label3, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                        .add(label2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
                .add(label5, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                .add(layout.createSequentialGroup()
                    .add(label6, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(LayoutStyle.RELATED)
                    .add(label7, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
            .addContainerGap(296, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(GroupLayout.LEADING)
        .add(layout.createSequentialGroup()
            .addContainerGap()
            .add(layout.createParallelGroup(GroupLayout.TRAILING)
                .add(label2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                .add(label1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(LayoutStyle.RELATED)
            .add(label3, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(LayoutStyle.RELATED)
            .add(label4, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(LayoutStyle.RELATED)
            .add(label5, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(LayoutStyle.RELATED)
            .add(layout.createParallelGroup(GroupLayout.LEADING)
                .add(label6, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                .add(label7, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
            .addContainerGap(150, Short.MAX_VALUE))
    );
    return hi;
}
GroupLayout Matisse generated UI running in Codename One
Figure 46. GroupLayout Matisse generated UI running in Codename One

If you’re porting newer Matisse code there are simple changes you can do:

  • Change addComponent to add

  • Change addGroup to add

  • Remove references to ComponentPlacement and reference LayoutStyle directly

7.1.6. Mig Layout

MigLayout is a popular cross-platform layout manager that was ported to Codename One from Swing.

MiG is still considered experimental so proceed with caution!
The API was deprecated to serve as a warning of its experimental status.

The best reference for MiG would probably be its quick start guide (PDF link). The sample below is one of that guide’s examples, ported to Codename One:

public static Form createForm() {
    Form hi = new Form("MigLayout",
            new MigLayout("wrap 2, insets 4mm", "[right]3mm[32mm]", "[]12[]12[]12[]"));
    hi.add(new Label("First name"));
    hi.add("growx, w 32mm", new TextField("", "First name"));
    hi.add(new Label("Last name"));
    hi.add("growx, w 32mm", new TextField("", "Last name"));
    hi.add(new Label("Phone"));
    hi.add("growx, w 32mm", new TextField("", "Phone"));
    Button ok = new Button("OK");
    ok.setCapsText(false);
    Style okStyle = ok.getAllStyles();
    okStyle.setBgColor(0xf4f8ff);
    okStyle.setBgTransparency(255);
    okStyle.setFgColor(0x0d47a1);
    okStyle.setBorder(Border.createLineBorder(1, 0x2b5c9e));
    okStyle.setPaddingUnit(Style.UNIT_TYPE_DIPS);
    okStyle.setPadding(2, 2, 2, 2);
    hi.add("span 2, growx", FlowLayout.encloseCenter(ok));
    return hi;
}
MiG layout sample ported to Codename One
Figure 47. MiG layout sample ported to Codename One

It should be reasonably easy to port MiG code but you should notice the following:

  • MiG handles a lot of the spacing/padding/margin issues that are missing in Swing/AWT. With Codename One styles you have the padding and margin which are probably a better way to do a lot of the things that MiG does

  • The add method in Codename One can be changed as shown in the sample above.

  • The constraint argument for Codename One add calls appears before the Component instance.

7.2. Themes and styles

Next you need to introduce you to 3 important terms in Codename One: Theme, Style, and UIID.

Themes are similar conceptually to CSS, in fact they can be created with CSS syntax as this guide covers soon. The various Codename One ports ship with a native theme representing the appearance of the native OS UI elements. Every Codename One application has its own theme that derives the native theme and overrides behavior within it.

If the native theme has a button defined, you can override properties of that button in your theme. This allows you to customize the look while retaining some native appearances. This works by merging the themes to one big theme where your application theme overrides the definitions of the native theme. This is pretty like the cascading aspect of CSS if you’re familiar with that.

Themes consist of a set of UIID definitions. Every component in Codename One has a UIID associated with it. UIID stands for User Interface Identifier. This UIID connects the theme to a specific component. A UIID maps to CSS classes if you’re familiar with that concept. For example, Codename One doesn’t support the complex CSS selector syntax options as those can impact runtime performance.

For example: see this code where:

Listing 8. setUIID on TextField
nameText.setUIID("Label");

This is a text field component (user input field) but it will look like a Label.

Effectively you told the text field that it should use the UIID of Label when it’s drawing itself. It’s common to do tricks like that in Codename One. For example: button.setUIID("Label") would make a button appear like a label and allow you to track clicks on a Label.

The UIID’s translate the theme elements into a set of Style objects. These Style objects get their initial values from the theme but can be further manipulated after the fact. To make the text field’s foreground color red you could use this code:

Listing 9. Setting a style directly
nameText.getAllStyles().setFgColor(0xff0000);

The color is in hexadecimal RRGGBB format so 0xff00 would be green and 0xff0000 would be red.

getAllStyles() returns a Style object but why do you need “all” styles?

Each component can have one of 4 states and each state has a Style object. This means you can have 4 style objects per Component:

  • Unselected: used when a component isn’t touched and doesn’t have focus. You can get that object with getUnselectedStyle().

  • Selected: used when a component is touched or if focus is drawn for non-touch devices. You can get that object with getSelectedStyle().

  • Pressed: used when a component is pressed. Notice it’s applicable to buttons and button subclasses. You can get that object with getPressedStyle().

  • Disabled: used when a component is disabled. You can get that object with getDisabledStyle().

The getAllStyles() method returns a special case Style object that lets you set the values of all 4 styles from one class so the code before would be equivalent to invoking all 4 setFgColor methods. For example, getAllStyles() works for setting properties not for getting them!

don’t use getStyle() for manipulation
getStyle() returns the current Style object which means it will behave inconsistently. The paint method uses getStyle() as it draws the current state of the Component but other code should avoid that method. Use the specific methods instead: getUnselectedStyle(), getSelectedStyle(), getPressedStyle(), getDisabledStyle() and getAllStyles()

As you can see, it’s a bit of a hassle to change styles from code which is why the theme is so appealing.

7.2.1. Theme

A theme allows you to define the styles externally through a set of UIID’s (User Interface ID’s). Themes can be authored directly in CSS and then compiled into the Codename One resource file, which keeps styling concerns separate from application logic.

The theme is stored in the theme.res file in the project.

You load the theme file using this line of code in the init(Object) method in the main class of the application:

Listing 10. Theme Loading Code
theme = UIManager.initFirstTheme("/theme");

In a CSS project this file is generated automatically from the stylesheet. Legacy applications that still edit the resource file by hand can continue to do so, but new projects should prefer the CSS workflow described below.

This code is shorthand for resource file loading and for the installation of theme. You could technically have more than one theme in a resource file at which point you could use initNamedTheme() instead. The resource file is a special file format that includes inside it many features:

  • Themes

  • Images

  • Localization Bundles

  • Data files

7.2.2. Working with CSS themes

Modern Codename One projects ship with a src/main/css/theme.css file (or an equivalent stylesheet). Editing this file allows you to define UIIDs using standard CSS syntax together with Codename One–specific extensions such as cn1-derive for inheritance and the #Constants block for theme constants. Each time you build or run the project, the build tool compiles the CSS into the theme.res resource file automatically. Saving the CSS while the simulator is running will also trigger a refresh so you can iterate on styling.

Because the CSS compiler produces the final resource file, you should treat the generated theme.res as an output artifact and keep your changes in the CSS source. Images referenced from CSS rules (for example: background images or multi-images) should be placed alongside the stylesheet so that they’re picked up by the compiler. More details about the supported selectors and properties are covered in the dedicated CSS chapter later in this guide.

7.3. GUI builder

The GUI builder arranges components visually: you drag them onto a canvas, position them, and edit their properties in an inspector, without writing the layout code by hand. It’s a desktop application that the Codename One Maven plugin launches, so it works the same way whichever IDE you use for the surrounding Java code. Forms designed in the builder use auto layout mode by default, which positions and resizes components on the canvas using LayeredLayout behind the scenes.

7.3.1. Hello world

Two goals do the work:

  • cn1:create-gui-form generates a new GUI form: the .gui XML file plus the matching Java source.

  • cn1:guibuilder opens the GUI builder on the project.

Both goals accept a className parameter that points at the fully qualified class name of the form. From the root of a multi-module Codename One project, create a new form like this:

mvn cn1:create-gui-form -DclassName=com.example.MyForm

This generates two files inside the common module:

  1. common/src/main/guibuilder/com/example/MyForm.gui

  2. common/src/main/java/com/example/MyForm.java

If you run the goal from inside the common submodule the files are written directly under that module’s src/main/…​ directory. By default the goal creates a Form; pass -DguiType=Dialog or -DguiType=Container to generate one of the other types, and pass -DautoLayout=false to opt out of auto layout mode.

To open the form in the GUI builder:

mvn cn1:guibuilder -DclassName=com.example.MyForm

Projects generated from the archetype also carry a ready-made shortcut for this: a CN1 GUI Builder run configuration in IntelliJ IDEA, an Open in GUI Builder action in NetBeans, a GUI Builder launch configuration in Eclipse, and a Tools > GUI Builder entry in the Visual Studio Code Maven favorites. They all run the same goal.

The full goal reference, including every parameter, lives in the cn1:create-gui-form goal and the cn1:guibuilder goal in the Maven goals appendix.

The GUI builder is a Java 8 artifact, so it runs on whichever JDK already builds your project.

7.3.2. The workspace

The GUI builder editing a newly created form
Figure 48. The GUI builder editing a form created with cn1:create-gui-form

The window has three columns:

  • Project forms and palette — on the left. The upper half lists every .gui file in the project under the Forms tab, and the component tree of the form you are editing under the Hierarchy tab. Picking a component from the tree is often easier than hitting it on the canvas, particularly when it’s behind something else. The lower half is the component palette, with a search field for finding a component by name.

  • Design canvas — in the middle. This is a live Codename One rendering of your form, styled by the project’s own theme.css, so what you see is what the application draws. The buttons above the canvas switch it between phone portrait, phone landscape, tablet, and a full-width desktop canvas.

  • Inspector — on the right. It shows the selected component under three tabs: Properties, Layout, and Events.

The toolbar carries Save, Undo, Redo and Refresh on the left, and CSS and Code on the right. Changes are written to the .gui file when you press Save.

The two dividers between the columns can be dragged, so you can give the canvas more room while positioning components and give the inspector more room while filling in properties.

7.3.3. Designing a form

Drag a component from the palette onto the canvas to add it. As you drag, the builder highlights where the component would land: the container that would receive it, and, in auto layout mode, guides showing the edges it would line up with. Dropping outside a valid target leaves the form unchanged.

Select a component by clicking it on the canvas or by picking it in the Hierarchy tab. A selected component shows resize handles; drag its body to move it, or a handle to resize it. Hold Shift while clicking to select several components at once, which is what the alignment actions in the top-left corner of the canvas operate on: they align edges, centers or baselines, match widths or heights, or disconnect a component from the relationships it has picked up.

Double-click a component that displays text — or long-press it — to edit that text in place, without going to the inspector.

The Properties tab holds what the component is: its name, its text, the UIID that connects it to a CSS selector, and the settings that belong to its type, such as the input constraint of a text field or the range of a slider. The Layout tab holds where it sits: its position in its parent, the layout manager of a container, and, for auto layout, its alignment reference and its horizontal and vertical size policies. The Events tab binds an event, such as a button press, to a method in the companion Java source.

7.3.4. Auto layout mode

New forms use auto layout mode. In this mode you place components where you want them rather than accepting the positions a layout manager dictates.

All forms designed in auto layout mode use LayeredLayout
Auto layout mode is built on the inset support in LayeredLayout. Component positioning uses insets and reference components, not absolute coordinates.

An inset can be fixed (stated in millimetres, pixels or a percentage) or flexible, and it can be measured from the parent or from a sibling component. That’s what makes a form designed on one canvas size still work on another: a component pinned to the bottom of the form stays there on a taller screen, and a component pinned below its neighbor follows that neighbor when it moves.

The builder chooses insets for you as you drag, and it prefers a relationship with a nearby component over a distance from the edge of the form. The Layout tab shows the choice it made and lets you change it:

  • Alignment reference — the component this one is positioned against, or the nearest component if you haven’t chosen one.

  • Horizontal size policy and Vertical size policy — whether the component keeps its preferred size, keeps a fixed size, fills its parent, or matches the size of its reference component.

Resize the canvas with the device buttons above it after every few changes. A form that looks right on one canvas can fall apart on another, and switching between phone portrait and desktop is the quickest way to find out before a device does.

7.3.5. Nested containers and other layouts

A form doesn’t have to be one flat surface. Drag a Container from the palette to group components together, then use the Container layout picker in the Layout tab to give it whichever layout manager suits that part of the form: box, border, flow, grid, table, or layered again. Components dragged into that container are then arranged by it, and the drop guides change to match — a box layout shows where in the sequence the component would go, a border layout shows which region would receive it, and a table layout shows the cell.

Containers can be nested as far as you need, and a component can be dragged out of one container and into another; the builder rewrites its constraints for the layout it lands in.

7.3.6. The theme and the companion source

The CSS button opens the project stylesheet inside the builder.

Editing theme.css inside the GUI builder
Figure 49. Editing the project stylesheet; the canvas re-renders as you type

The stylesheet is compiled and applied to the canvas as you edit it, so a color or a font change is visible immediately on the form you are designing. This is the same src/main/css/theme.css the application builds with, described in Working with CSS themes.

The Code button opens the companion Java source.

The generated companion source
Figure 50. The companion Java source, generated from the form

Everything between the // <gui-builder-generated> and // </gui-builder-generated> markers is written by the builder from the .gui file and is replaced whenever the form is saved. The region between the // <gui-builder-user-code> markers is yours: event handlers and anything else you add there is preserved across saves. The editor makes the distinction visible, and the status line reminds you which region takes your changes.

Forms scaffolded by older versions of cn1:create-gui-form used a different marker style. Opening such a form in the builder converts the file to the format above and keeps the methods you had written.

7.3.7. What’s stored on disk

A form is two files that belong together:

  • common/src/main/guibuilder/<package>/<Name>.gui — the XML description of the component tree. This is the file the builder reads and writes, and the one to keep under version control.

  • common/src/main/java/<package>/<Name>.java — the companion Java source.

The two files are connected by name. If you rename or move one, rename or move the other to match, or the builder can no longer pair them.

The .gui file is plain XML and readable enough to review in a diff:

<?xml version="1.0" encoding="UTF-8"?>

<component type="Form" name="SignInForm" title="Sign in" layout="LayeredLayout" autoLayout="true">
    <component type="Label" name="heading" text="Welcome back" layeredInsets="12% auto auto 8%" />
    <component type="TextField" name="email" hint="Email" layeredInsets="26% 8% auto 8%"
        guidedReferences="heading|-|-|-" />
    <component type="Button" name="signIn" text="Sign in" actionEvent="onSignIn"
        layeredInsets="62% 8% auto 8%" guidedReferences="email|-|-|-" />
</component>

You can edit it by hand, but reopen the form afterward: the builder doesn’t watch the file while it’s running.

8. The components of Codename One

This chapter covers the components of Codename One. It doesn’t cover every component, but it goes deeper than the Javadocs.

8.1. Container

The Codename One container is a base class for many high-level components. A container can hold other components.

Every component has a parent container. That parent can be null when the component isn’t inside another container or when it’s a top-level container. A container can have many children.

Component-Container relationship expressed as UML
Figure 51. Component-Container relationship expressed as UML

Components are arranged in containers with layout managers. A layout manager decides how to arrange components inside the container.

You can read more about layout managers in the basics section.

8.1.1. Composite components

Codename One components share a generic inheritance hierarchy. For example, Button derives from Label and thus receives all its abilities.

Some components are composites and derive from the Container class. For example, the MultiButton is a composite button that derives from Container but behaves like a Button. Most of the time this feels seamless, but a few details matter.

  • Don’t use the Container-derived methods on such a composite component (for example, add and remove).

  • You can’t cast it to the type it relates to. For example, you can’t cast MultiButton to Button.

  • Events can be more nuanced. For example, if you rely on ActionEvent.getSource() or ActionEvent.getComponent(), they may not behave as expected. For a MultiButton, they return the underlying Button. To work around that, use ActionEvent.getActualComponent().

Lead Component

Codename One includes a feature for creating composite components called "lead components." It lets components like MultiButton act like a single component while still containing multiple components.

Lead components work by assigning one component as the "leader." That leader determines the style state for every component in the hierarchy. If a Container is led by a Button, the button determines whether the selected or pressed state applies to the entire hierarchy.

This means a single Component can contain multiple nested UIID`s. For example, `MultiButton has UIID`s such as `MultiLine1, which you can customize with APIs such as setUIIDLine1.

The lead component also handles events from a single source. Clicking another component in the hierarchy sends the event to the leading Button, which can make action events route to a different target than the apparent click target. That’s why getActualComponent() exists.

You can learn more about lead components in here.

8.2. Form

A Form isn’t one surface. It’s a title area, a content pane, any number of layered panes, and on ports that place commands in a soft-key or button bar, a menu bar as well. Knowing which of them receives a component explains most of what happens next:

The parts of a Form: title area, content pane, layered pane and safe area
Figure 52. The parts of a Form, and which accessor reaches each one

Form is the top-level container in Codename One. Form derives from Container and is the element the app shows. Only one form can be visible at any given time. You can get the visible Form with the code:

Form currentForm = Display.getInstance().getCurrent();

A form is a container with a title, a content area, and an optional menu or menu-bar area. When you call methods such as add or remove on a form, you’re invoking something that maps to this:

myForm.getContentPane().add(cmp);

Form is effectively a Container with a border layout. The north section holds the title area, the south section holds the optional menu bar, and the center stretches as the content pane. Place all components in the content pane.

Form layout graphic
Figure 53. Form layout graphic

You can see that every Form has space allocated for the title area. If you don’t set the title, it won’t show up, but it will still be there. The same isn’t always true for the menu bar, which can vary. Effectively, the section that matters is the content pane, so the form tries to do the right thing by pretending to be the content pane. For example, this isn’t always seamless, and sometimes code needs to invoke getContentPane() to work directly with the container.

A good example for such a case is layout animations. Animating the form might not produce the right results. When in doubt, it’s easier to use getContentPane() instead of working with the Form directly.

As you can see from the graphic, Form has two layers that live on top of the content pane/title. The first is the layered pane, which allows you to place "always on top" components. The layered pane is added implicitly when you invoke getLayeredPane().

You still need to place components using layout managers to get them to appear in the right place when using the layered pane.

8.2.1. Safe areas

Modern phones often include display cut-outs, rounded corners, or persistent gesture/navigation indicators that overlap the physical screen edges. These intrusions are no longer limited to iOS—many recent Android devices behave the same way—so Codename One provides a "safe area" API to ensure your UI remains visible regardless of the device. The safe area is the portion of the display that’s guaranteed to be unobstructed.

Tabs with safe-area padding enabled
Figure 54. Tabs with safe-area padding enabled
Tabs without safe-area padding
Figure 55. Tabs without safe-area padding
Automatic Safe-Area handling

Form calculates the safe region automatically, and core UI components that anchor themselves to the screen edges apply that information without more work:

  • Toolbar and the status bar placeholder respect the top safe margins so that titles and action buttons remain legible around notches.

  • Tabs, Sheet, and FloatingActionButton instances mark their internal containers as safe areas so navigation controls are padded above gesture/navigation bars.

  • UI fragment templates can opt-in to safe areas declaratively using the safeArea flag, ensuring generated components stay within the padded region.

This means that many applications will work on devices such as the iPhone X/14 family or Android devices with edge-to-edge displays. You need to intervene when you use custom containers that you position flush against a screen edge or when you perform your own painting.

Marking your own containers as safe

If you create a container that should always stay clear of the unsafe portions of the screen (for example, a bottom navigation bar, an on-screen joystick, or a floating tool palette), enable safe-area padding explicitly:

Form form = new Form(new BorderLayout());

Container bottomBar = new Container(BoxLayout.x());
bottomBar.setSafeArea(true);
bottomBar.addAll(new Button("Home"), new Button("Search"), new Button("Profile"));

form.add(BorderLayout.SOUTH, bottomBar);
form.show();

Safe-area padding is applied when the container doesn’t have a scrollable parent. For scrollable content, you can assume the user can scroll the component into view instead.

Most layouts never need to know where the safe area begins, but if you draw manually (for example, inside paint() or on the glass pane) you can query it directly:

Form form = Display.getInstance().getCurrent();
Rectangle safe = form.getSafeArea();

Graphics g = null; // e.g. inside paint()
g.setClip(safe.getX(), safe.getY(), safe.getWidth(), safe.getHeight());
// Custom drawing code that should avoid the notch/gesture areas

The rectangle returned by Form#getSafeArea() is updated automatically whenever the OS reports a change (rotation, multitasking gestures, showing or hiding the system navigation area, etc.). In unusual situations where you adjust the safe-area root yourself (for example, when animating a container in from off-screen) you can force a recalculation by calling Form#setSafeAreaChanged().

Safe-Area roots and advanced layouts

Safe-area padding is calculated relative to a "safe-area root." Forms are roots by default, but you can mark any container as a root using Container#setSafeAreaRoot(true) when you need precise control, for example, when preparing a side menu that starts off-screen and slides in:

Container drawer = new Container(BoxLayout.y());
drawer.setSafeAreaRoot(true); // Ensure safe margins apply before the drawer is visible
drawer.setSafeArea(true);

Marking the drawer as both a root and a safe area prevents a jump the moment it becomes visible, because the safe padding is already applied while it’s off-screen.

Remember that safe areas apply across platforms. Always verify your screens on actual devices (or in the Codename One simulator with a device skin that exposes cut-outs) to make sure critical UI elements remain inside the padded region.

The second layer is the glass pane which allows you to draw arbitrary things on top of everything. The order in the image is indeed right:

  1. ContentPane is lowest

  2. LayeredPane is second

  3. GlassPane is painted last

It’s important to notice that a layered pane is on top of the ContentPane and doesn’t stretch to the title. A GlassPane stretches all the way but with a "lightweight" title area, for example, the Toolbar API.

The GlassPane allows developers to overlay UI on top of existing UI and paint as they see fit. This is useful for things that provide notification but don’t want to intrude with application functionality.

8.3. Dialog

A Dialog is a special kind of Form that can occupy a portion of the screen. It also has the more functionality of the modal show method.

When showing a dialog you have two basic options: modeless and modal:

  • Modal dialogs (the default) block the current EDT thread until the dialog is dismissed. To understand how they do it, read about invokeAndBlock.
    Modal dialogs are a useful way to prompt the user since the code can assume the user responded in the next line of execution. This promotes a linear and intuitive way of writing code.

  • Modeless dialogs return, so a call to show such a dialog can’t assume anything in the next line of execution. This is useful for features such as progress indicators where you aren’t waiting for user input.

For example: a modal dialog can be expressed as such:

if(Dialog.show("Click Yes Or No", "Select one", "Yes", "No")) {
    // user clicked yes
} else {
    // user clicked no
}

Notice that during the show call above the execution of the next line was "paused" until you got a response from the user and once the response was returned you could proceed directly.

All usage of Dialog must be within the Event Dispatch Thread (the default thread of Codename One). This is true for modal dialogs. The Dialog class knows how to "block the EDT" without blocking it.

To learn more about invokeAndBlock which is the workhorse behind the modal dialog functionality check out the EDT section.

The Dialog class contains many static helper methods to show user notifications, but also allows a developer to create a Dialog instance, add information to its content pane and show the dialog.

Dialogs contain a ContentPane like Form.

When showing a dialog in this way, you can either ask Codename One to position the dialog in a specific location based on the BorderLayout concept of locations, or position it by spacing it in pixels from the four edges of the screen.

For example: you could do something like this to show a simple modal Dialog:

Dialog d = new Dialog("Title");
d.setLayout(new BorderLayout());
d.add(BorderLayout.CENTER, new SpanLabel("Dialog Body", "DialogBody"));
d.showPacked(BorderLayout.SOUTH, true);
Custom Dialog in the south position
Figure 56. Custom modal Dialog in the south position
You can turn the code above to a modless Dialog by flipping the boolean true argument to false.

You can position a Dialog by determining the space from the edges for example: with this code you can occupy the bottom portion of the screen:

Dialog d = new Dialog("Title");
d.setLayout(new BorderLayout());
d.add(BorderLayout.CENTER, new SpanLabel("Dialog Body", "DialogBody"));
d.show(hi.getHeight() / 2, 0, 0, 0);
Custom Dialog positioned
Figure 57. Custom Dialog positioned absolutely
hi is the name of the parent Form in the sample above.

8.3.1. Styling dialogs

It’s important to style a Dialog using getDialogStyle() or setDialogUIID methods rather than styling the dialog object directly.

The reason for this is that the Dialog is a Form that takes up the whole screen. The Form that’s visible behind the Dialog is rendered as a screenshot. Customizing the actual UIID of the Dialog won’t produce the desired results.

8.3.2. Tint and blurring

By default a Dialog uses a platform specific tint color when it’s showing for example: notice the background in the image below is tinted:

Form hi = new Form("Tint Dialog", new BoxLayout(BoxLayout.Y_AXIS));
Button showDialog = new Button("Tint");
showDialog.addActionListener((e) -> Dialog.show("Tint", "Is On/* omitted */", "OK", null));
hi.add(showDialog);
hi.show();
Dialog with tinted background
Figure 58. Dialog with tinted background

The tint color can be manipulated on the parent form, you can set it to any AARRGGBB value to set any color using the setTintColor method. Notice that this is invoked on the parent form and not on the Dialog!

This is an AARRGGBB value and not an RRGGBB value! This means that 0 will be transparent.

You can also manipulate this default value globally using the theme constant tintColor. The sample below tints the background in green:

Form hi = new Form("Tint Dialog", new BoxLayout(BoxLayout.Y_AXIS));
hi.setTintColor(0x7700ff00);
Button showDialog = new Button("Tint");
showDialog.addActionListener((e) -> Dialog.show("Tint", "Is On/* omitted */", "OK", null));
hi.add(showDialog);
hi.show();
Dialog with green tinted background
Figure 59. Dialog with green tinted background

You can apply Gaussian blur to the background of a dialog to highlight the foreground further and produce an attractive effect. You can use the setDefaultBlurBackgroundRadius to apply this globally, you can use the theme constant dialogBlurRadiusInt to do the same or you can do this on a per Dialog basis using setBlurBackgroundRadius.

Not all device types support blur you can test if your device supports it using Display.getInstnace().isGaussianBlurSupported(). If blur isn’t supported the blur setting will be ignored:
Form hi = new Form("Blur Dialog", new BoxLayout(BoxLayout.Y_AXIS));
Dialog.setDefaultBlurBackgroundRadius(8);
Button showDialog = new Button("Blur");
showDialog.addActionListener((e) -> Dialog.show("Blur", "Is On/* omitted */", "OK", null));
hi.add(showDialog);
hi.show();
The blur effect coupled with the OS default tint
Figure 60. The blur effect coupled with the OS default tint

It might be a bit hard to notice the blur effect with the tinting so here is the same code with tinting disabled:

hi.setTintColor(0);
The blur effect is more pronounced when the tint is disabled
Figure 61. The blur effect is more pronounced when the tint is disabled

8.3.3. Popup dialog

A popup dialog is a common mobile paradigm showing a Dialog that points at a specific component. It’s a standard Dialog that’s shown in a unique way:

Form hi = new Form("Popup Dialog", new BoxLayout(BoxLayout.Y_AXIS));
Button showDialog = new Button("Show");
showDialog.addActionListener(e -> {
    Dialog d = new Dialog("Title");
    d.setLayout(new BorderLayout());
    d.add(BorderLayout.CENTER, new SpanLabel("Dialog Body", "DialogBody"));
    // the popup points at the button, which must be on screen to have a position
    d.showPopupDialog(showDialog);
});
hi.add(showDialog);
hi.show();
Popup Dialog
Figure 62. Popup Dialog

The popup dialog accepts a Component or Rectangle to point at and handles the rest.

Styling the arrow of the popup dialog

When Codename One was young you needed a popup arrow implementation but your low-level graphics API was pretty basic. As a workaround you created a version of the 9-piece image border that supported pointing arrows at a component.

Today Codename One supports pointing an arrow from the RoundRectBorder class. This is implicit for the PopupDialog UI. This allows for better customization of the border (color etc.) and it looks better on newer displays. It also works on all OSs. Right now the iOS theme has the old image border approach.

This will change with a future update where all OSes will align and iOS will use the lightweight popup too
You can make all OSes act the same way by overriding the PopupDialog UIID and defining its style to RoundRectBorder

The new RoundRectBorder support works by setting the track component property on border. When that’s done the border implicitly points to the right location.

If you still need deeper customization of the arrow you can still use the old 9-piece border functionality illustrated below.

Legacy 9-Piece Border arrow

One of the harder aspects of a popup dialog is the construction of the theme elements required for arrow styling. To get that sort of behavior you will need a custom image border and 4 arrows pointing in each direction that will be overlaid with the border.

The sizes of the arrow images should be similarly proportioned and fit within the image borders whitespace. The block image of the dialog should have empty pixels in the sides to reserve space for the arrow. For example: if the arrows are all 32×32 pixels then the PopupDialog image should have 32 pixels of transparent pixels around it.

You will need to define the following theme constants for the arrow to work:

PopupDialogArrowBool=true
PopupDialogArrowTopImage=arrow-up.png
PopupDialogArrowBottomImage=arrow-down.png
PopupDialogArrowLeftImage=arrow-left.png
PopupDialogArrowRightImage=arrow-right.png

Each of the four image constants names an image in your theme resource, so add your own arrows under those names — the values here are placeholders and there are no arrows built in. A constant naming an image the theme doesn’t hold leaves the border with nothing to paint.

Then style the PopupDialog UIID with the image for the Dialog itself.

8.4. InteractionDialog

Dialogs in Codename One can be modal or modeless, the former blocks the calling thread and the latter doesn’t. For example, there is another definition to those terms: A modal dialog blocks access to the rest of the UI while a modeless dialog "floats" on top of the UI.

In that sense, all dialogs in Codename One are modal; they block the parent form since they’re effectively forms that show the "parent" in their background. InteractionDialog has an API that’s like the Dialog API but, unlike dialog, it never blocks anything. Neither the calling thread nor the UI.

InteractionDialog isn’t a Dialog since it doesn’t share the same inheritance hierarchy. For example, it acts and "feels" like a Dialog although it’s a Container in the LayeredPane.

InteractionDialog is a container that’s positioned within the layered pane. Notice that because of that design, you can have one such dialog at the moment and, if you add something else to the layered pane, you might run into trouble.

Using the interaction dialog is pretty trivial and like dialog:

InteractionDialog dlg = new InteractionDialog("Hello");
dlg.setLayout(new BorderLayout());
dlg.add(BorderLayout.CENTER, new Label("Hello Dialog"));
Button close = new Button("Close");
close.addActionListener((ee) -> dlg.dispose());
dlg.addComponent(BorderLayout.SOUTH, close);
Dimension pre = dlg.getContentPane().getPreferredSize();
int displayWidth = Display.getInstance().getDisplayWidth();
int dialogWidth = Math.max(pre.getWidth() + pre.getWidth() / 6, displayWidth * 2 / 3);
dlg.show(0, 0, displayWidth - dialogWidth, 0);
Interaction Dialog
Figure 63. Interaction Dialog

This will show the dialog on the right-hand side of the screen, which is pretty useful for a floating in place dialog.

The InteractionDialog can be shown at absolute or popup locations. This is inherent to its use case which is "non-blocking." When using this component you need to be aware of its location.

To make popup behavior feel natural on touch devices you can call setDisposeWhenPointerOutOfBounds(true) so the dialog automatically dismisses as soon as the user taps outside the title or content area. Internally the dialog listens for pointer pressed/released events and will call dispose() for you when the interaction happens beyond its bounds, so you no longer need to wire that logic manually.

By default the dialog is placed on the form’s layered pane, but you can switch between the global layered pane and form-specific layered pane using setFormMode(boolean). Setting form mode to true keeps the dialog coupled with the showing form even when the global layered pane is used elsewhere in your app.

Finally, recent updates added animation toggles so you can fine-tune presentation. setAnimateShow(boolean) turns the show/dispose animations on or off, while setRepositionAnimation(boolean) enables a "grow/shrink" reposition effect during those animations when you want a more dynamic transition.

8.5. Label

Label represents a text, icon, or both. Label is also the base class of Button which in turn is the base class for RadioButton & CheckBox. Thus the functionality of the Label class extends to all these components.

Label text can be positioned in one of 4 locations as such:

Form hi = new Form("Label Position", new BoxLayout(BoxLayout.Y_AXIS));
Image icon = FontImage.createMaterial(FontImage.MATERIAL_INFO, "Label", 3.0f);
Label left = new Label("Left", icon);
left.setTextPosition(Component.LEFT);
Label right = new Label("Right", icon);
right.setTextPosition(Component.RIGHT);
Label bottom = new Label("Bottom", icon);
bottom.setTextPosition(Component.BOTTOM);
Label top = new Label("Top", icon);
top.setTextPosition(Component.TOP);
hi.add(left).add(right).add(bottom).add(top);
hi.show();
Label positions
Figure 64. Label positions

Label allows a single line of text, line breaking is an expensive operation on mobile devices [1] and so the Label class doesn’t support it.

SpanLabel supports many lines with a single label, notice that it does carry a performance penalty for this functionality.

Labels support tickering and the ability to end with "…​" if there isn’t enough space to render the label. Developers can determine the placement of the label to its icon in a few powerful ways.

8.5.1. Label gap

The gap between the label text & the icon defaults to 2 pixels due to legacy settings. The setGap method of Label accepts a gap size in pixels.

Two pixels is low for most cases & it’s hard to customize for each Label.

You can use the theme constant labelGap which is a floating point value you can specify in millimeters that will allow you to determine the default gap for a label. You can also customize this manually using the method Label.setDefaultGap(int) which determines the default gap in pixels.

8.5.2. Autosizing labels

One of the common requests you received over the years is a way to let text "fit" into the allocated space so the font will match almost the width available. In some designs this is important but it’s also tricky. Measuring the width of a String is an expensive operation on some OSes., there is no other way other than trial & error to find the "best size."

Still although something is "slow" you might still want to use it for some cases, this isn’t something you should use in a renderer, infinite scroll etc. and recommend minimizing the usage of this feature as much as possible.

This feature is applicable to Label and its subclasses (for example: Button), with components such as TextArea (for example: SpanButton) the choice between shrinking and line break would require some complex logic.

To activate this feature use setAutoSizeMode(true) for example:

Form hi = new Form("AutoSize", BoxLayout.y());

Label a = new Label("Short Text");
a.setAutoSizeMode(true);
Label b = new Label("Much Longer Text than the previous line...");
b.setAutoSizeMode(true);
Label c = new Label("MUCH MUCH MUCH Much Longer Text than the previous line by a pretty big margin...");
c.setAutoSizeMode(true);

Label a1 = new Button("Short Text");
a1.setAutoSizeMode(true);
Label b1 = new Button("Much Longer Text than the previous line...");
b1.setAutoSizeMode(true);
Label c1 = new Button("MUCH MUCH MUCH Much Longer Text than the previous line by a pretty big margin...");
c1.setAutoSizeMode(true);
hi.addAll(a, b, c, a1, b1, c1);

hi.show();
Automatically sizes the fonts of the buttons/labels based on text and available space
Figure 65. Automatically sizes the fonts of the buttons/labels based on text and available space

8.6. TextField and TextArea

The TextField class derives from the TextArea class, and both are used for text input in Codename One.

TextArea defaults to multi-line input and TextField defaults to single line input but both can be used in both cases. The main differences between TextField and TextArea are:

  • Blinking cursor is rendered on TextField

  • DataChangedListener is available in TextField. This is crucial for character by character input event tracking

  • Done listener is available in the TextField

  • Different UIID

The semantic difference between TextField & TextArea dates back to the ancestor of Codename One: LWUIT. Feature phones don’t have "proper" in-place editing capabilities & thus TextField was introduced to allow such input.

Because it lacks the blinking cursor capability TextArea is often used as a multi-line label and is used internally in SpanLabel, SpanButton etc.

A common use case is to have an important text component in edit mode as you enter a Form. Codename One forms support this exact use case through the Form.setEditOnShow(TextArea) method.

TextField & TextArea support constraints for various types of input such as NUMERIC, EMAIL, URL, etc. Those usually affect the virtual keyboard used, but might not limit input in some platforms. For example: on iOS even with NUMERIC constraint you would still be able to input characters.

If you need to prevent specific types of input check out the validation section.

The following sample shows off simple text field usage:

Form hi = new Form("Text", BoxLayout.y());
TextField plain = new TextField("", "Any text");
TextField email = new TextField("", "E-Mail", 20, TextField.EMAILADDR);
TextField url = new TextField("", "URL", 20, TextField.URL);
TextField phone = new TextField("", "Phone", 20, TextField.PHONENUMBER);
TextField number = new TextField("", "Number", 20, TextField.NUMERIC);
TextArea notes = new TextArea(4, 20);
notes.setHint("Notes");
hi.addAll(plain, email, url, phone, number, notes);
hi.show();
Simple text component sample
Figure 66. Simple text component sample
The Toolbar section contains an elaborate TextField search sample with DataChangedListener and rather unique styling.

8.6.1. Masking

A common use case when working with text components is the ability to "mask" input for example: in the credit card number above you would want 4 digits for each text field and don’t want the user to tap Next 3 times.

Masking allows you to accept partial input in one field and implicitly move to the next, this can be used to all types of complex input thanks to the text component API. E.g with the code above you can mask the credit card input so the cursor jumps to the next field implicitly using this code:

TextField num1 = new TextField("", "", 5, TextField.NUMERIC);
TextField num2 = new TextField("", "", 5, TextField.NUMERIC);
TextField num3 = new TextField("", "", 5, TextField.NUMERIC);
TextField num4 = new TextField("", "", 5, TextField.NUMERIC);
// the first three are trimmed to four by automoveToNext when the fifth
// digit arrives; the last one has no successor, so it needs a limit
num4.setMaxSize(4);
automoveToNext(num1, num2);
automoveToNext(num2, num3);
automoveToNext(num3, num4);

Then implement the method automoveToNext as:

private void automoveToNext(final TextField current, final TextField next) {
    current.addDataChangedListener((type, index) -> {
        String val = current.getText();
        // more than one digit can arrive at once from a paste or autofill, so
        // keep four and hand the whole remainder on -- the next field's own
        // listener splits it again if it is still too long
        if(val.length() > 4) {
            current.stopEditing();
            current.setText(val.substring(0, 4));
            String rest = val.substring(4);
            next.setText(rest);
            if(rest.length() <= 4) {
                // a longer remainder means the next field's listener is still
                // splitting; let the last one in the chain take the focus
                next.startEditingAsync();
            }
        }
    });
}

Notice you can invoke stopEditing(Runnable) where you receive a callback as editing is stopped.

8.6.2. The virtual keyboard

A common misconception for developers is assuming the virtual keyboard represents "keys." For example: developers often override the "keyEvent" callbacks which are invoked for physical keyboard typing and expect those to occur with a virtual keyboard.

This isn’t the case since a virtual keyboard is a different beast. With a virtual keyboard characters typed might produce a different output due to autocorrect. Some keyboards don’t even have "keys" in the traditional sense or don’t type them in the traditional sense (for example: swiping).

The constraint property for the TextField/TextArea is crucial for a virtual keyboard.
When working with a virtual keyboard it’s important that the parent Container for the TextField/TextArea is scrollable. Otherwise the component won’t be reachable or the UI might be distorted when the keyboard appears.
Action Button client property

By default, the virtual keyboard on Android has a "Done" button, you can customize it to be a search icon, a send icon, or a go icon using a hint such as this:

searchTextField.putClientProperty("searchField", Boolean.TRUE);
sendTextField.putClientProperty("sendButton", Boolean.TRUE);
goTextField.putClientProperty("goButton", Boolean.TRUE);

This will adapt the icon for the action on the keys.

Next and done on iOS

You try to hide a lot of the platform differences in Codename One, input is ** different between OSes. A common reliance is the ability to send the "Done" event when the user presses the Done button. This button doesn’t always exist for example: if there is an Enter button (due to multiline input) or if there is a Next button in that place.

To unify the behavior you slightly customized the iOS keyboard as such:

Next virtual keyboard with toolbar
Figure 67. Next virtual keyboard with toolbar
Done virtual keyboard without toolbar
Figure 68. Done virtual keyboard without toolbar
This works with 3rd party keyboards too…​

For example, this behavior might not be desired so to block that you can do:

tf.putClientProperty("iosHideToolbar", Boolean.TRUE);

This will hide the toolbar for that given field.

You can customize the color of the Done button in the toolbar by setting the ios.doneButtonColor display property. For example: To change the color to red, you could do Display.getInstance().setProperty("ios.doneButtonColor", String.valueOf(0xff0000)).

8.6.3. Clearable text field

iOS has a convention where an X can be placed after the text field to clear it. Some Android apps have it but there is no native support for that as of this writing.

You can wrap a TextField with a clearable wrapper to get this effect on all platforms. For example: replace this:

cnt.add(myTextField);

With this:

cnt.add(ClearableTextField.wrap(myTextField));

You can also specify the size of the clear icon if you wish. This is technically a Container with the text field style and a button to clear the text at the edge.

8.7. TextComponent

When building input forms you sometimes want to adapt to the native OS behavior and create a UI that’s a bit more distinct to the native OS. TextField and TextArea are low-level, you can create an Android style UI with such components but it might look out of place in iOS.

For example: this is how most of you would expect the UI to look on iOS and Android respectively:

TextModeLayout on iOS
Figure 69. Text Input on iOS
TextModeLayout on Android with the same code
Figure 70. Text Input on Android

Doing this with text fields is possible but would require code that looks a bit different and jumps through hoops. TextComponent allows this exact UI without forcing developers to write OS specific code:

TextModeLayout tl = new TextModeLayout(3, 2);
Form f = new Form("Pixel Perfect", tl);
TextComponent title = new TextComponent().label("Title");
TextComponent price = new TextComponent().label("Price");
TextComponent location = new TextComponent().label("Location");
TextComponent description = new TextComponent().label("Description").multiline(true);

f.add(tl.createConstraint().horizontalSpan(2), title);
f.add(tl.createConstraint().widthPercentage(30), price);
f.add(tl.createConstraint().widthPercentage(70), location);
f.add(tl.createConstraint().horizontalSpan(2), description);
f.setEditOnShow(title.getField());
f.show();
This code uses the TextModeLayout which is discussed in the layouts section

The text component uses a builder approach to set various values for example:

TextComponent t = new TextComponent().
    text("This appears in the text field").
    hint("This is the hint").
    label("This is the label").
    multiline(true);

The code is pretty self-explanatory and more convenient than typical setters/getters. It automatically handles the floating hint style of animation when running on Android.

8.7.1. Error handling

The validator class supports text component and it should "work." But the cool thing is that it uses the material design convention for error handling!

If you add to the sample above a Validator:

Validator val = new Validator();
val.addConstraint(title, new LengthConstraint(2));
val.addConstraint(price, new NumericConstraint(true));

You would see something that looks like this on Android:

Error handling when the text is blank
Figure 71. Error handling when the text is blank
Error handling when there is some input (notice red title label)
Figure 72. Error handling when there is some input (notice red title label)
On iOS the situation hasn’t changed much yet
Figure 73. On iOS the situation hasn’t changed much yet

The underlying system is the errorMessage method which you can chain like the other methods on TextComponent as such:

TextComponent tc = new TextComponent().
    label("Input Required").
    errorMessage("Input is essential in this field");

8.7.2. InputComponent and PickerComponent

To keep the code common and generic you use the InputComponent abstract base class and derive the other classes from that. PickerComponent is the other option.

A picker can work with your existing sample using code like this:

TextModeLayout tl = new TextModeLayout(3, 2);
Form f = new Form("Pixel Perfect", tl);
TextComponent title = new TextComponent().label("Title");
TextComponent price = new TextComponent().label("Price");
TextComponent location = new TextComponent().label("Location");
PickerComponent date = PickerComponent.createDate(new Date()).label("Date");
TextComponent description = new TextComponent().label("Description").multiline(true);
Validator val = new Validator();
val.addConstraint(title, new LengthConstraint(2));
val.addConstraint(price, new NumericConstraint(true));
f.add(tl.createConstraint().widthPercentage(60), title);
f.add(tl.createConstraint().widthPercentage(40), date);
f.add(location);
f.add(price);
f.add(tl.createConstraint().horizontalSpan(2), description);
f.setEditOnShow(title.getField());
f.show();

This produces the following which looks pretty standard:

Picker component taking place in iOS
Figure 74. Picker component taking place in iOS
And in Android
Figure 75. And in Android

The one tiny thing you should notice with the PickerComponent is that you don’t construct the picker component using new PickerComponent(). Instead you use create methods such as PickerComponent.createDate(new Date()). The reason for that’s that you have many types of pickers and it wouldn’t make sense to have one constructor.

8.7.3. Underlying theme constants and UIID’s

These varying looks are implemented through a combination of layouts, theme constants and UIID’s. The most important UIID’s are: TextComponent, FloatingHint & TextHint.

There are many related theme constants that can manipulate some pieces of this functionality:

  • textComponentErrorColor a hex RGB color which defaults to null in which case this has no effect. When defined this will change the color of the border and label to the given color to match the material design styling. This implements the red border underline in cases of error and the label text color change

  • textComponentErrorLineBorderBool toggles the material-style underline that appears on validation errors. Set it to false if you prefer to supply a different border when errors are shown

  • textComponentOnTopBool toggles the on top mode which makes things look like they do on Android. This defaults to true on Android and false on other OSes. This can also be manipulated through the onTopMode(boolean) method in InputComponent, but the layout will use the theme constant

  • textComponentAnimBool toggles the animation mode which again can be manipulated by a method in InputComponent. If you want to keep the UI static without the floating hint effect set this to false. Notice this defaults to true on Android

  • textComponentFieldUIID sets the UIID of the text field to something other than TextField this is useful for platforms such as iOS where the look of the text field is different within the text component. This allows you to make the background of the text field transparent when it’s within the TextComponent and make it different from the regular text field

  • inputComponentErrorMultilineBool makes error labels multi-line by default so longer validation messages can wrap instead of being clipped

8.8. Button

Button is a subclass of Label and as a result it inherits all its functionality, specifically icon placement, tickering, etc.

Button adds to the mix some more states such as a pressed UIID state and pressed icon.

Button supports more icon states such as rollover and disabled icon.

Button also exposes some functionality for subclasses specifically the setToggle method call which has no meaning when invoked on a Button but has a lot of implications for CheckBox & RadioButton.

Button event handling can be performed through an ActionListener or through a Command.

Changes in a Command won’t be reflected into the Button after the command was set to the Button.

Here is a trivial hello world style Button:

Form hi = new Form("Button");
Button b = new Button("My Button");
hi.add(b);
b.addActionListener((e) -> Log.p("Clicked"));

The same three buttons under the two modern native themes. A button takes its shape, fill and font from the theme, so the platform difference costs no code:

The same buttons under iOS Modern (left) and Android Material (right)

iOS Modern Android Material

Such a button can be styled to look like a link using code like this or by making these settings in the theme and using code such as btn.setUIID("Hyperlink"):

Form hi = new Form("Button");
Button b = new Button("Link Button");
b.getAllStyles().setBorder(Border.createEmpty());
b.getAllStyles().setTextDecoration(Style.TEXT_DECORATION_UNDERLINE);
hi.add(b);
b.addActionListener((e) -> Log.p("Clicked"));
Button styled to look like a link
Figure 76. Button styled to look like a link

8.8.1. Uppercase buttons

Buttons on Android’s material design UI use upper case styling which isn’t the case for iOS. To solve this you have the method setCapsText(boolean) in Button which has the corresponding isCapsText, isCapsTextDefault & setCapsTextDefault(boolean). This is pretty core to Codename One so to prevent this from impacting everything unless you explicitly invoke setCapsText(boolean) the default value of true will apply when the UIID is Button, RaisedButton or for the built-in Dialog buttons.

You also have a theme constant: capsButtonTextBool. This constant controls caps text behavior from the theme and is set to true in the Android native theme.

8.8.2. Raised Button

Raised button is a style of button that’s available on Android and used to highlight an important action within a form. To confirm with the material design UI guidelines you might want to leverage a raised button UI element on Android but use a regular button everywhere else.

First you need to know whether a raised button exists in the theme. On Android this will return true but on other OSes it will return false. A potential future update might make another platform true based on UI guidelines in other OSes.

For this purpose you have got the theme constant hasRaisedButtonBool which will return true on Android but will be false elsewhere. You can use it like this:

if(UIManager.getInstance().isThemeConstant("hasRaisedButtonBool", false)) {
    // that means we can use a raised button
}

To enable this you have the RaisedButton UIID that derives from Button and will act like it except for the places where hasRaisedButtonBool is true in which case it will look like this:

Raised and flat button in simulator
Figure 77. Raised and flat button in simulator

Notice that you can customize the colors of these buttons now since the border respects user colors…​

In this case set the background color to purple and the foreground to white:

Purple raised button
Figure 78. Purple raised button
Form f = new Form("Pixel Perfect", BoxLayout.y());
Button b = new Button("Raised Button", "RaisedButton");
Button r = new Button("Flat Button");
f.add(b);
f.add(r);
f.show();

8.8.3. Ripple effect

The ripple effect in material design highlights the location of the finger and grows as a circle to occupy the full area of the component as the user presses the button.

You can perform a ripple effect by darkening the touched area and growing that in a quick animation.

Ripple effect can be applied to any component but you have it turned on for buttons on Android which also applies to things like title commands, side menu elements etc. This might not apply at this moment to lead components like multi-buttons but that might change in the future.

Component has a property to enable the ripple effect setRippleEffect(boolean) and the corresponding isRippleEffect(). You can turn it on or off individually in the component level. For example, Button has static setButtonRippleEffectDefault(boolean) and isButtonRippleEffectDefault(). These allow you to define the default behavior for all the buttons and that can be configured through the theme constant buttonRippleBool which is on by default on the native Android theme.

8.9. CheckBox/RadioButton

CheckBox & RadioButton are subclasses of button that allow for either a toggle state or exclusive selection state.

Both CheckBox & RadioButton have a selected state that allows you to determine their selection.

RadioButton doesn’t allow you to "deselect" it, the way to "deselect" a RadioButton is by selecting another RadioButton.

The CheckBox can be added to a Container like any other Component but the RadioButton must be associated with a ButtonGroup otherwise if you have more than one set of RadioButton’s in the form you might have an issue.

Notice in the sample below that you associate all the radio buttons with a group but don’t do anything with the group as the radio buttons keep the reference internally. You also show the opposite side functionality and icon behavior:

Form hi = new Form("CheckBox", new BoxLayout(BoxLayout.Y_AXIS));
Image icon = FontImage.createMaterial(FontImage.MATERIAL_INFO, "Label", 3.0f);
CheckBox cb1 = new CheckBox("CheckBox No Icon");
cb1.setSelected(true);
CheckBox cb2 = new CheckBox("CheckBox With Icon", icon);
CheckBox cb3 = new CheckBox("CheckBox Opposite True", icon);
CheckBox cb4 = new CheckBox("CheckBox Opposite False", icon);
cb3.setOppositeSide(true);
cb4.setOppositeSide(false);
RadioButton rb1 = new RadioButton("Radio 1");
RadioButton rb2 = new RadioButton("Radio 2");
RadioButton rb3 = new RadioButton("Radio 3", icon);
new ButtonGroup(rb1, rb2, rb3);
rb2.setSelected(true);
hi.add(cb1).add(cb2).add(cb3).add(cb4).add(rb1).add(rb2).add(rb3);
hi.show();
RadioButton & CheckBox usage
Figure 79. RadioButton & CheckBox usage

Both of these components can be displayed as toggle buttons (see the toggle button section below), or use the default check mark/filled circle appearance based on the type/OS.

8.9.1. Toggle Button

A toggle button is a button that’s pressed and stays pressed. When a toggle button is pressed again it’s released from the pressed state. Hence the button has a selected state to show if it’s pressed or not like the CheckBox/RadioButton components in Codename One.

To turn any CheckBox or RadioButton to a toggle button use the setToggle(true) method. Or you can use the static createToggle method on both CheckBox and RadioButton to create a toggle button directly.

Invoking setToggle(true) implicitly converts the UIID to ToggleButton unless it was changed by the user from its original default value.

You can convert the sample above to use toggle buttons as such:

Form hi = new Form("RadioButton", new BoxLayout(BoxLayout.Y_AXIS));
Image icon = FontImage.createMaterial(FontImage.MATERIAL_INFO, "Label", 3.0f);
CheckBox cb1 = CheckBox.createToggle("CheckBox No Icon");
cb1.setSelected(true);
CheckBox cb2 = CheckBox.createToggle("CheckBox With Icon", icon);
CheckBox cb3 = CheckBox.createToggle("CheckBox Opposite True", icon);
CheckBox cb4 = CheckBox.createToggle("CheckBox Opposite False", icon);
cb3.setOppositeSide(true);
cb4.setOppositeSide(false);
ButtonGroup bg = new ButtonGroup();
RadioButton rb1 = RadioButton.createToggle("Radio 1", bg);
RadioButton rb2 = RadioButton.createToggle("Radio 2", bg);
RadioButton rb3 = RadioButton.createToggle("Radio 3", icon, bg);
rb2.setSelected(true);
hi.add(cb1).add(cb2).add(cb3).add(cb4).add(rb1).add(rb2).add(rb3);
hi.show();
Toggle button converted sample, on Android Material and iOS

Toggle buttons under Android Material Toggle buttons under the iOS theme

Both themes draw the selection as a change of fill rather than of label color alone, so a selected toggle stays readable for someone who can’t separate the two hues. The outlined row in each figure is the one holding focus: focus is drawn as a ring precisely so it can’t be mistaken for a value, since the framework resolves a focused toggle through the same style whether it’s checked or not.

That’s half the story though: to get the full effect of some cool toggle button UI’s you can use a ComponentGroup. This allows you to create a button bar effect with the toggle buttons.

For example, to enclose the CheckBox components in a vertical ComponentGroup and the RadioButton’s in a horizontal group, change the last line of the code above as such:

Form hi = new Form("ComponentGroup", new BoxLayout(BoxLayout.Y_AXIS));
CheckBox cb1 = CheckBox.createToggle("CheckBox 1");
CheckBox cb2 = CheckBox.createToggle("CheckBox 2");
CheckBox cb3 = CheckBox.createToggle("CheckBox 3");
CheckBox cb4 = CheckBox.createToggle("CheckBox 4");
ButtonGroup bg = new ButtonGroup();
RadioButton rb1 = RadioButton.createToggle("Radio 1", bg);
RadioButton rb2 = RadioButton.createToggle("Radio 2", bg);
RadioButton rb3 = RadioButton.createToggle("Radio 3", bg);
hi.add(ComponentGroup.enclose(cb1, cb2, cb3, cb4)).
        add(ComponentGroup.encloseHorizontal(rb1, rb2, rb3));
hi.show();
Toggle button converted sample wrapped in ComponentGroup
Figure 80. Toggle button converted sample wrapped in ComponentGroup

8.10. ComponentGroup

ComponentGroup is a special container that can be either horizontal or vertical (BoxLayout X_AXIS or Y_AXIS respectively).

ComponentGroup "restyles" the elements within the group to have a UIID that allows you to create a "round border" effect that groups elements together.

The following code adds 4 component groups to a Container to show the various UIID changes:

hi.add("Three Labels").
        add(ComponentGroup.enclose(new Label("GroupElementFirst UIID"), new Label("GroupElement UIID"), new Label("GroupElementLast UIID"))).
        add("One Label").
        add(ComponentGroup.enclose(new Label("GroupElementOnly UIID"))).
        add("Three Buttons").
        add(ComponentGroup.enclose(new Button("ButtonGroupFirst UIID"), new Button("ButtonGroup UIID"), new Button("ButtonGroupLast UIID"))).
        add("One Button").
        add(ComponentGroup.enclose(new Button("ButtonGroupOnly UIID")));
ComponentGroup adapts the UIID’s of the components added so you can style them
Figure 81. ComponentGroup adapts the UIID’s of the components added so you can style them

Notice the following about the code above and the resulting image:

  • Buttons have a different UIID than other element types. Their styling is slightly different in such UI’s so you need to pay attention to that.

  • When an element is placed alone within a ComponentGroup its a special case UIID.

A vertical ComponentGroup does nothing unless the theme sets the ComponentGroupBool constant to true; without it the group is just a box layout container. The legacy iOS themes set that flag, the current native themes don’t, and neither of them styles the GroupElement UIIDs a vertical group applies. A horizontal group is the exception, as long as it keeps the UIID setHorizontal gives it: it’s a segmented control, it renames its members to ToggleButton, and both native themes style that UIID and its First / Last / Only variants in full, so it needs no constant. Name your own element UIID with setElementUIID and it’s theme-gated again, exactly like a vertical one.

When ComponentGroupBool is set to true, the component group will change the styles of all components placed within it to match the element UIID given to it (GroupElement by default) with special caveats to the first/last/ elements. For example:

  1. With one element in a component group it will have the UIID: GroupElementOnly

  2. With two elements in a component group they will have the UIID’s GroupElementFirst, GroupElementLast

  3. With three elements in a component group they will have the UIID’s GroupElementFirst, GroupElement, GroupElementLast

  4. With four elements in a component group they will have the UIID’s GroupElementFirst, GroupElement, GroupElement, GroupElementLast

This allows you to define special styles for the edges.

You can customize the UIID set by the component group by calling setElementUIID in the component group for example: setElementUIID("ToggleButton") for three elements result in the following UIID’s:

ToggleButtonFirst, ToggleButton, ToggleButtonLast

8.11. MultiButton

MultiButton is a composite component (lead component) that acts like a versatile Button. It supports up to 4 lines of text (it doesn’t automatically wrap the text), an emblem (usually navigational arrow, or check box) and an icon.

MultiButton can be used as a button, a CheckBox or a RadioButton for creating rich UI’s.

The MultiButton was inspired by the aesthetics of the UITableView iOS component.

A common source of confusion in the MultiButton is the difference between the icon and the emblem, since both may have an icon image associated with them. The icon is an image representing the entry while the emblem is an optional visual representation of the action that will be undertaken when the element is pressed. Both may be used simultaneously or individually of one another:

Form hi = new Form("MultiButton", new BoxLayout(BoxLayout.Y_AXIS));
Image icon = FontImage.createMaterial(FontImage.MATERIAL_INFO, "Label", 3.0f);
Image emblem = FontImage.createMaterial(FontImage.MATERIAL_STAR, "Label", 2.0f);
MultiButton twoLinesNoIcon = new MultiButton("MultiButton");
twoLinesNoIcon.setTextLine2("Line 2");
MultiButton oneLineIconEmblem = new MultiButton("Icon + Emblem");
oneLineIconEmblem.setIcon(icon);
oneLineIconEmblem.setEmblem(emblem);
MultiButton twoLinesIconEmblem = new MultiButton("Icon + Emblem");
twoLinesIconEmblem.setIcon(icon);
twoLinesIconEmblem.setEmblem(emblem);
twoLinesIconEmblem.setTextLine2("Line 2");

MultiButton twoLinesIconEmblemHorizontal = new MultiButton("Icon + Emblem");
twoLinesIconEmblemHorizontal.setIcon(icon);
twoLinesIconEmblemHorizontal.setEmblem(emblem);
twoLinesIconEmblemHorizontal.setTextLine2("Line 2 Horizontal");
twoLinesIconEmblemHorizontal.setHorizontalLayout(true);

MultiButton twoLinesIconCheckBox = new MultiButton("CheckBox");
twoLinesIconCheckBox.setIcon(icon);
twoLinesIconCheckBox.setCheckBox(true);
twoLinesIconCheckBox.setTextLine2("Line 2");

MultiButton fourLinesIcon = new MultiButton("With Icon");
fourLinesIcon.setIcon(icon);
fourLinesIcon.setTextLine2("Line 2");
fourLinesIcon.setTextLine3("Line 3");
fourLinesIcon.setTextLine4("Line 4");

hi.add(oneLineIconEmblem).
add(twoLinesNoIcon).
add(twoLinesIconEmblem).
add(twoLinesIconEmblemHorizontal).
add(twoLinesIconCheckBox).
add(fourLinesIcon);
hi.show();
Multiple usage scenarios for the MultiButton
Figure 82. Multiple usage scenarios for the MultiButton

8.11.1. Styling the MultiButton

Since the MultiButton is a composite component setting its UIID will impact the top level UI.

To customize everything you need to customize the UIID’s for MultiLine1, MultiLine2, MultiLine3, MultiLine4 & Emblem.

You can customize the individual UIID’s through the API directly using the setIconUIID, setUIIDLine1, setUIIDLine2, setUIIDLine3, setUIIDLine4 & setEmblemUIID.

Recent versions also include a badge overlay that can be rendered in the corner of the main icon. Use setBadgeText() to display a value (for example a notification count) and setBadgeUIID() if you need a custom UIID instead of the default Badge styling. When you need to inspect or adjust the badge style programmatically, getBadgeStyleComponent() returns the component whose styles are applied to the badge so you can tweak padding, colors or borders before showing the MultiButton.

8.12. SpanButton

SpanButton is a composite component (lead component) that looks/acts like a Button but can break lines rather than crop them when the text is long.

Unlike the MultiButton it uses the TextArea internally to break lines seamlessly. The SpanButton is far simpler than the MultiButton and as a result isn’t as configurable:

Form hi = new Form("SpanButton", new BoxLayout(BoxLayout.Y_AXIS));
Image icon = FontImage.createMaterial(FontImage.MATERIAL_INFO, "Label", 3.0f);
SpanButton sb = new SpanButton("SpanButton is a composite component (lead component) that looks/acts like a Button but can break lines rather than crop them when the text is very long.");
sb.setIcon(icon);
hi.add(sb);
hi.show();
The SpanButton Component
Figure 83. The SpanButton Component
SpanButton is slower than both Button and MultiButton. Recommend using it when there is a genuine need for its functionality.

8.13. SpanLabel

SpanLabel is a composite component (lead component) that looks/acts like a Label but can break lines rather than crop them when the text is long.

SpanLabel uses the TextArea internally to break lines seamlessly and so doesn’t provide all the elaborate configuration options of Label.

One of the features of label that moved into SpanLabel to some extent is the ability to position the icon. For example, unlike a Label the icon position is determined by the layout manager of the composite so setIconPosition accepts a BorderLayout constraint:

Form hi = new Form("SpanLabel", new BoxLayout(BoxLayout.Y_AXIS));
Image icon = FontImage.createMaterial(FontImage.MATERIAL_INFO, "Label", 3.0f);
SpanLabel d = new SpanLabel("Default SpanLabel that can seamlessly line break when the text is really long.");
d.setIcon(icon);
SpanLabel l = new SpanLabel("NORTH Positioned Icon SpanLabel that can seamlessly line break when the text is really long.");
l.setIcon(icon);
l.setIconPosition(BorderLayout.NORTH);
SpanLabel r = new SpanLabel("SOUTH Positioned Icon SpanLabel that can seamlessly line break when the text is really long.");
r.setIcon(icon);
r.setIconPosition(BorderLayout.SOUTH);
SpanLabel c = new SpanLabel("EAST Positioned Icon SpanLabel that can seamlessly line break when the text is really long.");
c.setIcon(icon);
c.setIconPosition(BorderLayout.EAST);
hi.add(d).add(l).add(r).add(c);
hi.show();
The SpanLabel Component
Figure 84. The SpanLabel Component
SpanLabel is slower than Label. Recommend using it when there is a genuine need for its functionality.

8.14. OnOffSwitch

The OnOffSwitch allows you to write an application where the user can swipe a switch between two states (on/off). This is a common UI paradigm in Android and iOS, although it’s implemented in a radically different way in both platforms.

This is a rather elaborate component because of its unique design on iOS, but you’re able to accommodate most of the small behaviors of the component into your version, and it seamlessly adapts between the Android style and the iOS style.

The image below was generated based on the default use of the OnOffSwitch:

OnOffSwitch onOff = new OnOffSwitch();
hi.add(onOff);
The OnOffSwitch component as it appears on/off on iOS (top) and on Android (bottom)
Figure 85. The OnOffSwitch component as it appears on/off on iOS (top) and on Android (bottom)

As you can understand the difference between the way iOS and Android render this component has triggered two different implementations within a single component. The Android implementation uses standard buttons and is the default for non-iOS platforms.

You can force the Android or iOS mode by using the theme constant onOffIOSModeBool.

8.14.1. Validation

Validation is an inherent part of text input, and the Validator class allows that. You can enable validation through the Validator class to add constraints for a specific component. It’s also possible to define components that would be enabled/disabled based on validation state and the way in which validation errors are rendered (change the components UIID, paint an emblem on top, etc.). A Constraint is an interface that represents validation requirements. You can define a constraint in Java or use some built-in constraints such as LengthConstraint, RegexConstraint, etc.

This sample below continues from the place where the TextField sample above stopped by adding validation to that code:

TextField firstName = new TextField("", "First Name");
TextField surname = new TextField("", "Surname");
TextField url = new TextField("", "URL", 20, TextField.URL);
TextField email = new TextField("", "E-Mail", 20, TextField.EMAILADDR);
TextField phone = new TextField("", "Phone", 20, TextField.PHONENUMBER);
String phoneRegex = "[0-9\\-\\+ ]+";
TextField num1 = new TextField("", "", 5, TextField.NUMERIC);
TextField num2 = new TextField("", "", 5, TextField.NUMERIC);
TextField num3 = new TextField("", "", 5, TextField.NUMERIC);
TextField num4 = new TextField("", "", 5, TextField.NUMERIC);
Button submit = new Button("Submit");
// the masking from the previous sample still applies to these fields
automoveToNext(num1, num2);
automoveToNext(num2, num3);
automoveToNext(num3, num4);
num4.setMaxSize(4);

Validator v = new Validator();
v.addConstraint(firstName, new LengthConstraint(2)).
        addConstraint(surname, new LengthConstraint(2)).
        addConstraint(url, RegexConstraint.validURL()).
        addConstraint(email, RegexConstraint.validEmail()).
        addConstraint(phone, new RegexConstraint(phoneRegex, "Must be valid phone number")).
        addConstraint(num1, new LengthConstraint(4)).
        addConstraint(num2, new LengthConstraint(4)).
        addConstraint(num3, new LengthConstraint(4)).
        addConstraint(num4, new LengthConstraint(4));

v.addSubmitButtons(submit);

Form hi = new Form("Validation", new BoxLayout(BoxLayout.Y_AXIS));
hi.add(firstName).add(surname).add(url).add(email).add(phone).
        add(num1).add(num2).add(num3).add(num4).add(submit);
hi.show();
Validation and Regular Expressions
Figure 86. Validation & Regular Expressions

When the form components are bound to a model with @Bindable, the same constraints can be expressed as field annotations — @Required, @Length, @Regex, @Email, @Url, @Numeric, @ExistIn, @Validate — and the generated binder wires them into a Validator exposed through Binding#getValidator(). See the Validation annotations section in the component binding chapter for the full reference.

8.15. InfiniteProgress

The InfiniteProgress indicator spins an image infinitely to show that a background process is still working.

This style of animation is often nicknamed "washing machine" as it spins endlessly.

InfiniteProgress can be used in one of two ways either by embedding the component into the UI through something like this:

myContainer.add(new InfiniteProgress());

InfiniteProgress can also appear over the entire screen, thus blocking all input. This tints the background while the infinite progress rotates:

Dialog ip = new InfiniteProgress().showInifiniteBlocking();

// do some long operation here using invokeAndBlock or do something in a separate thread and callback later
// when you are done just call

ip.dispose();
Infinite progress
Figure 87. Infinite progress

The image used in the InfiniteProgress animation is defined by the native theme. You can override that definition either by defining the theme constant infiniteImage or by invoking the setAnimation method.

Despite the name of the method setAnimation expects a static image that will be rotated internally. Don’t use an animated image.

8.16. InfiniteScrollAdapter and InfiniteContainer

InfiniteScrollAdapter & InfiniteContainer allow you to create a scrolling effect that "never" ends with the typical Container/Component paradigm.

The motivation behind these classes is simple, say you have a lot of data to fetch from storage or from the internet. You can fetch the data in batches and show progress sign while you do this.

Infinite scroll fetches the next batch of data dynamically as you reach the end of the Container. InfiniteScrollAdapter & InfiniteContainer represent two similar ways to do that task.

Let start by exploring how you can achieve this UI that fetches data from a webservice:

InfiniteScrollAdapter demo code fetching property cross data
Figure 88. InfiniteScrollAdapter demo code fetching property cross data

The first step is creating the webservice call, you won’t go into too much detail here as webservices & IO are discussed later in the guide:

int pageNumber = 1;
java.util.List<Map<String, Object>> fetchPropertyData(String text) {
    try {
        ConnectionRequest r = new ConnectionRequest();
        r.setPost(false);
        r.setUrl("https://api.nestoria.co.uk/api");
        r.addArgument("pretty", "0");
        r.addArgument("action", "search_listings");
        r.addArgument("encoding", "json");
        r.addArgument("listing_type", "buy");
        r.addArgument("page", "" + pageNumber);
        pageNumber++;
        r.addArgument("country", "uk");
        r.addArgument("place_name", text);
        NetworkManager.getInstance().addToQueueAndWait(r);
        Map<String,Object> result = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(r.getResponseData()), "UTF-8"));
        Map<String, Object> response = (Map<String, Object>)result.get("response");
        return (java.util.List<Map<String, Object>>)response.get("listings");
    } catch(Exception err) {
        Log.e(err);
        return null;
    }
}
The demo code here doesn’t do any error handling! This is a bad practice and it’s taken here to keep the code short and readable. Proper error handling is used in the Property Cross demo.

The fetchPropertyData is a simplistic tool that fetches the next page of listings for the nestoria webservice. Notice that this method is synchronous and will block the calling thread (legally) until the network operation completes.

Now that you have a webservice lets proceed to create the UI. Check out the code annotations below:

Form hi = new Form("InfiniteScrollAdapter", new BoxLayout(BoxLayout.Y_AXIS));

Style s = UIManager.getInstance().getComponentStyle("MultiLine1");
FontImage p = FontImage.createMaterial(FontImage.MATERIAL_PORTRAIT, s);
EncodedImage placeholder = EncodedImage.createFromImage(p.scaled(p.getWidth() * 3, p.getHeight() * 3), false); (1)

InfiniteScrollAdapter.createInfiniteScroll(hi.getContentPane(), () -> { (2)
    java.util.List<Map<String, Object>> data = fetchPropertyData("Leeds"); (3)
    if(data == null) { // the fetch failed, so there is nothing more to add
        InfiniteScrollAdapter.addMoreComponents(hi.getContentPane(), new Component[0], false);
        return;
    }
    MultiButton[] cmps = new MultiButton[data.size()];
    for(int iter = 0 ; iter < cmps.length ; iter++) {
        Map<String, Object> currentListing = data.get(iter);
        if(currentListing == null) { (4)
            InfiniteScrollAdapter.addMoreComponents(hi.getContentPane(), new Component[0], false);
            return;
        }
        String thumb_url = (String)currentListing.get("thumb_url");
        String guid = (String)currentListing.get("guid");
        String summary = (String)currentListing.get("summary");
        cmps[iter] = new MultiButton(summary);
        cmps[iter].setIcon(URLImage.createToStorage(placeholder, guid, thumb_url));
    }
    InfiniteScrollAdapter.addMoreComponents(hi.getContentPane(), cmps, !data.isEmpty()); (5)
}, true); (6)
hi.show();
1Placeholder is essential for the URLImage class which this guide covers at a different place.
2The InfiniteScrollAdapter accepts a runnable which is invoked every time you reach the edge of the scrolling. You used a closure instead of the typical run() method override.
3This is a blocking call, after the method completes you will have all the data you need. Notice that this method doesn’t block the EDT illegally.
4If there is no more data you call the addMoreComponents method with a false argument. This indicates that there is no more data to fetch.
5Here you add the actual components to the end of the form. Notice that you must not invoke the add/remove method of Container. Those might conflict with the work of the InfiniteScrollAdapter.
6You pass true to show that the data isn’t "prefilled" so the method should be invoked when the Form is first shown
Don’t violate the EDT in the callback. It’s invoked on the event dispatch thread and it’s crucial

8.16.1. The InfiniteContainer

InfiniteContainer was introduced to simplify and remove some boilerplate of the InfiniteScrollAdapter. It takes a more traditional approach of inheriting the Container class to provide its functionality.

Unlike the InfiniteScrollAdapter the InfiniteContainer accepts an index and amount to fetch. This is useful for tracking your position but also important since the InfiniteContainer also implements Pull To Refresh as part of its functionality.

Converting the code above to an InfiniteContainer is pretty simple you moved all the code into the callback fetchComponents method and returned the array of Component’s as a response.

Unlike the InfiniteScrollAdapter you can’t use the ContentPane directly so you’ve to use a BorderLayout and place the InfiniteContainer there:

Form hi = new Form("InfiniteContainer", new BorderLayout());

Style s = UIManager.getInstance().getComponentStyle("MultiLine1");
FontImage p = FontImage.createMaterial(FontImage.MATERIAL_PORTRAIT, s);
EncodedImage placeholder = EncodedImage.createFromImage(p.scaled(p.getWidth() * 3, p.getHeight() * 3), false);

InfiniteContainer ic = new InfiniteContainer() {
    @Override
    public Component[] fetchComponents(int index, int amount) {
        if(index == 0) {
            // a pull to refresh asks for the start of the list again
            pageNumber = 1;
        }
        java.util.List<Map<String, Object>> data = fetchPropertyData("Leeds");
    if(data == null) { // the fetch failed, so there is nothing more to add
        return null;
    }
        MultiButton[] cmps = new MultiButton[data.size()];
        for(int iter = 0 ; iter < cmps.length ; iter++) {
            Map<String, Object> currentListing = data.get(iter);
            if(currentListing == null) {
                return null;
            }
            String thumb_url = (String)currentListing.get("thumb_url");
            String guid = (String)currentListing.get("guid");
            String summary = (String)currentListing.get("summary");
            cmps[iter] = new MultiButton(summary);
            cmps[iter].setIcon(URLImage.createToStorage(placeholder, guid, thumb_url));
        }
        return cmps;
    }
};
hi.add(BorderLayout.CENTER, ic);
hi.show();

8.17. List, MultiList, renderers & models

8.17.1. InfiniteContainer/InfiniteScrollAdapter vs. List/ContainerList

The recommendation is to always go with Container, InfiniteContainer or InfiniteScrollAdapter.

Recommend avoiding List or its subclasses/related classes specifically ContainerList & MultiList.

Recommend replacing ComboBox with Picker but that’s a different discussion.

A Container with ~5000 nested containers within it can perform on par with a List and probably exceed its performance when used.

Larger sets of data are manageable on phones or tablets so the benefits for lists are dubious.

In API you found that even experienced developers experienced a great deal of pain when wrangling the Swing styled lists and their stateless approach.

Since animation, swiping and other capabilities that are so common in mobile are so hard to do with lists you see no actual reason to use them.

8.17.2. Why isn’t list deprecated

ContainerList is deprecated because it performs badly and has some inherent complexity issues. List has some unique use cases and is still used all over Codename One.

MultiList is a reasonable version of List that’s far easier to use without most of the pains related to renderer configuration.

Some cases justify using List or MultiList, but they’re rarer than usual, hence the recommendation.

8.17.3. MVC in lists

A Codename One List doesn’t contain components, but rather arbitrary data; this seems odd at first but makes sense. If you want a list to contain components, use a Container.

The advantage of using a List in this way is that you can display it in many ways (for example: fixed focus positions, horizontally, etc.), and that you can have more than a million entries without performance overhead. You can also do some pretty nifty things, like filtering the list on the fly or fetching it dynamically from the Internet as the user scrolls down the list. To achieve these things the list uses two interfaces: ListModel and ListCellRenderer. List model represents the data; its responsibility is to return the arbitrary object within the list at a given offset. Its second responsibility is to tell the list when the data changes, so the list can refresh.

Think of the model as an array of objects that can tell you when it changes.

The list renderer is like a rubber stamp that knows how to draw an object from the model, it’s called many times per entry in an animated list and must be fast. Unlike standard Codename One components, it’s used to draw the entry in the model and is discarded, hence it has no memory overhead, but if it takes too long to process a model value it can be a big bottleneck!

Think of the render as a translation layer that takes the "data" from the model and translates it to a visual representation.

This is all generic, but a bit too much for most, doing a list correctly requires some understanding. The main source of confusion for developers is the stateless nature of the list and the transfer of state to the model (for example: a checkbox list needs to listen to action events on the list and update the model, in order for the renderer to display that state). Once you understand that it’s easy.

8.17.4. Understanding MVC

A quick recap of what MVC is:

  • Model - Represents the data for the component (list), the model can tell you how many items are in it and which item resides at a given offset within the model. This differs from a simple Vector (or array), since all access to the model is controlled (the interface is simpler), and unlike a Vector/Array, the model can tell you of changes that occur within it.

  • View - The view draws the content of the model. It’s a "dumb" layer that has no notion of what’s displayed and knows how to draw. It tracks changes in the model (the model sends events) and redraws itself when it changes.

  • Controller - The controller accepts user input and performs changes to the model, which in turn cause the view to refresh.

Image by RegisFrey - Own work Public Domain https://commons.wikimedia.org/w/index.php?curid=10298177
Figure 89. Typical MVC Diagram [2]

Codename One’s List component uses the MVC paradigm in its implementation. List itself is the Controller (with a bit of the View mixed in). The ListCellRenderer interface is the rest of the View and the ListModel is (you guessed it by now) the Model.

When the list is painted, it iterates over the visible elements in the model and asks the model for the data, it then draws them using the renderer. Notice that because of this both the model and the renderer must be fast and that’s hard.

Why is this useful

Since the model is a lightweight interface, it can be implemented by you and replaced in runtime if so desired, this allows many use cases:

  1. A list can contain thousands of entries but load the portion visible to the user. Since the model will be queried for the elements that are visible to the user, it won’t need to load the large data set into memory until the user starts scrolling down (at which point other elements may be offloaded from memory).

  2. A list can cache efficiently. For example: a list can mirror data from the server into local RAM without actually downloading all the data. Data can also be mirrored from storage for better performance and discarded for better memory use.

  3. The is no need for state copying. Since renderers allow you to display any object type, the list model interface can be implemented by the application’s data structures (for example: persistence/network engine), which would return internal application data structures saving you the need of copying application state into a list specific data structure. Note that this advantage applies with a custom renderer which is pretty difficult to get right.

  4. Using the proxy pattern you can layer logic such as filtering, sorting, caching, etc. On top of existing models without changing the model source code.

  5. You can reuse generic models for many views, for example: a model that fetches data from the server can be initialized with different arguments, to fetch different data for different views. View objects in different Forms can display the same model instance in different view instances, thus they would update automatically when you change one global model.

Most of these use cases work best for lists that grow to a larger size, or represent complex data, which is what the list object is designed to do.

8.17.5. Important - lists and Layout managers

When working with lists, you want the list to handle the scrolling (otherwise it will perform badly). This means you should place the list in a non-scrollable container (no parent can be scrollable), notice that the content pane is scrollable by default, so you should disable that.

It’s also recommended to place the list in the CENTER location of a BorderLayout to produce the most effective results. For example:

form.setScrollable(false);
form.setLayout(new BorderLayout());
form.add(BorderLayout.CENTER, myList);

8.17.6. MultiList & DefaultListModel

After this long start, here is the first sample of creating a list using the MultiList.

The MultiList is a preconfigured list that contains a ready made renderer with defaults that make sense for the most common use cases. It still retains most of the power available to the List component but reduces the complexity of one of the hardest things to grasp for most developers: rendering.

The full power of the ListModel is still available and allows you to create a million entry list with a few lines of code. For example the objects that the model returns should always be in the form of Map objects and not an arbitrary object like the standard List allows.

Here is a simple example of a MultiList containing a highly popular subject matter:

Form hi = new Form("MultiList", new BorderLayout());

ArrayList<Map<String, Object>> data = new ArrayList<>();

data.add(createListEntry("A Game of Thrones", "1996"));
data.add(createListEntry("A Clash Of Kings", "1998"));
data.add(createListEntry("A Storm Of Swords", "2000"));
data.add(createListEntry("A Feast For Crows", "2005"));
data.add(createListEntry("A Dance With Dragons", "2011"));
data.add(createListEntry("The Winds of Winter", "2016 (please, please, please)"));
data.add(createListEntry("A Dream of Spring", "Ugh"));

DefaultListModel<Map<String, Object>> model = new DefaultListModel<>(data);
MultiList ml = new MultiList(model);
hi.add(BorderLayout.CENTER, ml);
hi.show();
Basic usage of the MultiList and DefaultListModel
Figure 90. Basic usage of the MultiList & DefaultListModel]

createListEntry is trivial:

private Map<String, Object> createListEntry(String name, String date) {
    Map<String, Object> entry = new HashMap<>();
    entry.put("Line1", name);
    entry.put("Line2", date);
    return entry;
}

One major piece is missing here: the cover images for the books. A simple approach would be to place the image objects into the entries using the "icon" property as such:

private Map<String, Object> createListEntry(String name, String date, Image cover) {
    Map<String, Object> entry = new HashMap<>();
    entry.put("Line1", name);
    entry.put("Line2", date);
    entry.put("icon", cover);
    return entry;
}
With cover images in place
Figure 91. With cover images in place
Since the MultiList uses the GenericListCellRenderer internally you can use URLImage to dynamically fetch the data. This is discussed in the graphics section of this guide.
Going further with the ListModel

Suppose that GRRM was prolific and wrote 1 million books. The default list model won’t make much sense in that case but you would still be able to render everything in a list model.

You will fake it a bit but notice that 1M components won’t be created even if you somehow scroll all the way down…​

The ListModel interface can be implemented by anyone in this case you did a stupid simple implementation:

static class GRMMModel implements ListModel<Map<String, Object>> {
    private int selection;
    private final java.util.List<SelectionListener> selectionListeners = new ArrayList<>();

    @Override
    public Map<String, Object> getItemAt(int index) {
        int idx = index % 7;
        switch (idx) {
            case 0:
                return createListEntry("A Game of Thrones " + index, "1996");
            case 1:
                return createListEntry("A Clash Of Kings " + index, "1998");
            case 2:
                return createListEntry("A Storm Of Swords " + index, "2000");
            case 3:
                return createListEntry("A Feast For Crows " + index, "2005");
            case 4:
                return createListEntry("A Dance With Dragons " + index, "2011");
            case 5:
                return createListEntry("The Winds of Winter " + index, "2016 (please, please, please)");
            default:
                return createListEntry("A Dream of Spring " + index, "Ugh");
        }
    }

    @Override
    public int getSize() {
        return 1000000;
    }

    @Override
    public int getSelectedIndex() {
        return selection;
    }

    @Override
    public void setSelectedIndex(int index) {
        int old = selection;
        selection = index;
        for (SelectionListener l : selectionListeners) {
            l.selectionChanged(old, index);
        }
    }

    @Override
    public void addDataChangedListener(DataChangedListener l) {
    }

    @Override
    public void removeDataChangedListener(DataChangedListener l) {
    }

    @Override
    public void addSelectionListener(SelectionListener l) {
        selectionListeners.add(l);
    }

    @Override
    public void removeSelectionListener(SelectionListener l) {
        selectionListeners.remove(l);
    }

    @Override
    public void addItem(Map<String, Object> item) {
    }

    @Override
    public void removeItem(int index) {
    }
}

You can now replace the existing model by removing all the model related logic and changing the constructor call as such:

MultiList ml = new MultiList(new GRMMModel());
Form hi = new Form("Million Entries", new BorderLayout());
hi.add(BorderLayout.CENTER, ml);
hi.show();
It took ages to scroll this far…​ This goes to a million…​
Figure 92. It took ages to scroll this far…​ This goes to a million…​

8.17.7. List cell renderer

The Renderer is a simple interface with 2 methods:

public interface ListCellRenderer {
   //This method is called by the List for each item, when the List paints itself.
   public Component getListCellRendererComponent(List list, Object value, int index, boolean isSelected);

   //This method returns the List animated focus which is animated when list selection changes
   public Component getListFocusComponent(List list);
}

The most simple/naive implementation may choose to implement the renderer as follows:

public Component getListCellRendererComponent(List list, Object value, int index, boolean isSelected){
     return new Label(value.toString());
}

public Component getListFocusComponent(List list){
     return null;
}

This will compile and work, but won’t give you much, notice that you won’t see the List selection move on the List, this is because the renderer returns a Label with the same style regardless if it’s selected or not.

Now make it a bit more useful:

public Component getListCellRendererComponent(List list, Object value, int index, boolean isSelected){
      Label l = new Label(value.toString());
if (isSelected) {
             l.setFocus(true);
             l.getAllStyles().setBgTransparency(100);
         } else {
             l.setFocus(false);
             l.getAllStyles().setBgTransparency(0);
        }
        return l;
}   public Component getListFocusComponent(List list){
      return null;
}

In this renderer you set the Label.setFocus(true) if it’s selected, calling to this method doesn’t give the focus to the Label, it renders the label as selected.

Then you invoke Label.getAllStyles().setBgTransparency(100) to give the selection semi transparency, and 0 for full transparency if not selected.

That’s still not efficient because you create a new Label each time the method is invoked.

To make the code tighter, keep a reference to the Component or extend it as DefaultListCellRenderer does:

class MyRenderer extends Label implements ListCellRenderer {
    public Component getListCellRendererComponent(List list, Object value, int index, boolean isSelected){
        setText(value.toString());
        if (isSelected) {
            setFocus(true);
            getAllStyles().setBgTransparency(100);
        } else {
            setFocus(false);
            getAllStyles().setBgTransparency(0);
        }
        return this;
    }

    public Component getListFocusComponent(List list) {
        // this renderer highlights the selected row itself, and returning the
        // rubber stamp would draw the focus overlay with the last row's text
        return null;
    }
}

Now look at a more advanced Renderer:

class ContactsRenderer extends Container implements ListCellRenderer {

 private Label name = new Label("");
 private Label email = new Label("");
 private Label pic = new Label("");

 private Label focus = new Label("");

 public ContactsRenderer() {
     setLayout(new BorderLayout());
     addComponent(BorderLayout.WEST, pic);
     Container cnt = new Container(new BoxLayout(BoxLayout.Y_AXIS));
     name.getAllStyles().setBgTransparency(0);
     name.getAllStyles().setFont(Font.createTrueTypeFont("native:MainBold"));
     email.getAllStyles().setBgTransparency(0);
     cnt.addComponent(name);
     cnt.addComponent(email);
     addComponent(BorderLayout.CENTER, cnt);

     focus.getStyle().setBgTransparency(100);
 }

 public Component getListCellRendererComponent(List list, Object value, int index, boolean isSelected) {

     Contact person = (Contact) value;
     name.setText(person.getDisplayName());
     email.setText(person.getPrimaryEmail());
     pic.setIcon(person.getPhoto());
     return this;
 }

 public Component getListFocusComponent(List list) {
     return focus;
 }
}

In this renderer you want to render a Contact object to the Screen, you build the Component in the constructor and in the getListCellRendererComponent you update the Labels' texts according to the Contact object.

Notice that in this renderer you return a focus Label with semi transparency, as mentioned before, the focus component can be modified within this method.

For example, you can change the focus Component to have an icon:

focus.getAllStyles().setBgTransparency(100);
focus.setIcon(FontImage.createMaterial(FontImage.MATERIAL_STAR, "Label", 3.0f));
focus.setAlignment(Component.RIGHT);

8.17.8. Generic list cell renderer

As part of the GUI builder work, you needed a way to customize rendering for a List, but the renderer/model approach seemed impossible to adapt to a GUI builder (it seems the Swing GUI builders had a similar issue). Your solution was to introduce the GenericListCellRenderer, which while introducing limitations and implementation requirements still manages to make life easier, both in the GUI builder and outside of it.

GenericListCellRenderer is a renderer designed to be as simple to use as a Component-Container hierarchy, you effectively crammed most of the common renderer use cases into one class. To enable that, you need to know the content of the objects within the model, so the GenericListCellRenderer assumes the model contains Map objects. Since Maps can contain arbitrary data the list model is still generic and allows storing application specific data. Furthermore a Map can still be derived and extended to provide domain specific business logic.

The GenericListCellRenderer accepts two container instances (more later on why at least two, and not one), which it maps to individual Map entries within the model, by finding the appropriate components within the given container hierarchy. Components are mapped to the Map entries based on the name property of the component (getName/setName) and the key/value within the Map, for example:

For a model that contains a Map entry like this:

"Foo": "Bar"
"X": "Y"
"Not": "Applicable"
"Number": Integer(1)

A renderer will loop over the component hierarchy in the container, searching for components whose name matches Foo, X, Not, and Number, and assigning the appropriate value to them.

You can also use image objects as values, and they will be assigned to labels as expected. For example, you can’t assign both an image and a text to a single label, since the key will be taken. That isn’t a big problem, since two labels can be used in such a renderer.

To make matters even more attractive the renderer seamlessly supports list tickering when appropriate, and if a CheckBox appears within the renderer, it will toggle a boolean flag within the Map seamlessly.

One issue that crops up with this approach is that, if a value is missing from the Map, it’s treated as empty and the component is reset.

This can pose an issue if you hardcode an image or text within the renderer and you don’t want them replaced (for example: an arrow graphic on a Label within the renderer). The solution for this is to name the component with Fixed in the end of the name, for example: HardcodedIconFixed.

Naming a component within the renderer with $number will automatically set it as a counter component for the offset of the component within the list.

Styling the GenericListCellRenderer is slightly different, the renderer uses the UIID of the Container passed to the generic list cell renderer, and the background focus uses that same UIID with the word "Focus" appended to it.

Note that the generic list cell renderer will grant focus to the child components of the selected entry if they’re focusable, thus changing the style of said entries. For example: a Container might have a child Label that has one style when the parent container is unselected and another when it’s selected (focused), this can be achieved by defining the label as focusable. Notice that the component will never receive direct focus, since it’s still part of a renderer.

Finally, the generic list cell renderer accepts two or four instances of a Container, rather than the obvious choice of accepting one instance. This allows the renderer to treat the selected entry differently, which is important to tickering, although it’s also useful for the fisheye effect [3]. Since it might not be practical to seamlessly clone the Container for the renderer’s needs, Codename One expects the developer to provide two separate instances, they can be identical in all respects, but they must be separate instances for tickering to work. The renderer also allows for a fisheye effect, where the selected entry is actually different from the unselected entry in its structure, it also allows for a pinstripe effect, where odd/even rows have different styles (this is accomplished by providing 4 instances of the containers selected/unselected for odd/even).

The best way to learn about the generic list cell renderer and the Map model is by playing with them in the old GUI builder. Notice they can be used in code without any dependency on the GUI builder and can be useful at that.

Here is a simple example of a list with checkboxes that gets updated automatically:

list.setRenderer(new GenericListCellRenderer(createGenericRendererContainer(), createGenericRendererContainer()));
GenericListCellRenderer demo code
Figure 93. GenericListCellRenderer demo code
Custom UIID of entry in GenericListCellRenderer/MultiList

With MultiList/GenericListCellRenderer one of the common issues is making a UI where a specific component within the list renderer has a different UIID style based on data. For example: this can be helpful to mark a label within the list as red, for instance, for a list of monetary transactions.

This can be achieved with a custom renderer, but that’s a pretty difficult task.
GenericListCellRenderer (MultiList uses GenericListCellRenderer internally) has another option.

Normally, to build the model for a renderer of this type, you use something like:

map.put("componentName", "Component Value");

What if you want componentName to be red? Just use:

map.put("componentName_uiid", "red");

This will apply the UIID "red" to the component, which you can then style in the theme. Notice that once you start doing this, you need to define this entry for all entries, for example:

map.put("componentName_uiid", "blue");

Otherwise the component will stay red for the next entry (since the renderer acts like a rubber stamp).

Rendering prototype

Because of the rendering architecture of a List its pretty hard to calculate the right preferred size for such a component. The default behavior includes querying a few entries from the model then constructing their renderers to get a "sample" of the preferred size value.

As you might guess this triggers a performance penalty that’s paid with every reflow of the UI. The solution is to use setRenderingPrototype.

setRenderingPrototype accepts a "fake" value that represents a reasonably large amount of data and it will be used to calculate the preferred size. For example: for a multiList that should render 2 lines of text with 20 characters and a 5mm square icon you can do something like this:

Map<String, Object> proto = new HashMap<>();
proto.put("Line1", "WWWWWWWWWWWWWWWWWWWW");
proto.put("Line2", "WWWWWWWWWWWWWWWWWWWW");
int mm5 = Display.getInstance().convertToPixels(5, true);
proto.put("icon", Image.createImage(mm5, mm5));
myMultiList.setRenderingPrototype(proto);

8.17.9. ComboBox

The ComboBox is a specialization of List that displays a single selected entry. When clicking that entry a popup is presented allowing the user to pick an entry from the full list of entries.

The ComboBox UI paradigm isn’t as common on OSes such as iOS where there is no native equivalent to it. Recommend using either the Picker class or the AutoCompleteTextField.

ComboBox is notoriously hard to style as it relies on a complex dynamic of popup renderer and instantly visible renderer. The UIID for the ComboBox is ComboBox but if you set it to something else all the other UIID’s will also change their prefix. For example: the ComboBoxPopup UIID will become MyNewUIIDPopup.

The combo box defines the following UIID’s by default:

  • ComboBox

  • ComboBoxItem

  • ComboBoxFocus

  • PopupContentPane

  • PopupItem

  • PopupFocus

The ComboBox also defines theme constants that allow some native themes to manipulate its behavior for example:

  • popupTitleBool - shows the "label for" value as the title of the popup dialog

  • popupCancelBodyBool - Adds a cancel button into the popup dialog

  • centeredPopupBool - shows the popup dialog in the center of the screen instead of under the popup

  • otherPopupRendererBool - Uses a different list cell render for the popup than the one used for the ComboBox itself. When this is false PopupItem & PopupFocus become irrelevant. Notice that the Android native theme defines this to true.

Since a ComboBox is a List you can use everything you learned about a List to build a ComboBox including models, GenericListCellRenderer etc.

For example: the demo below uses the GRRM demo data from above to build a ComboBox:

Form hi = new Form("ComboBox", new BoxLayout(BoxLayout.Y_AXIS));
ComboBox<Map<String, Object>> combo = new ComboBox<> (
        createListEntry("A Game of Thrones", "1996"),
        createListEntry("A Clash Of Kings", "1998"),
        createListEntry("A Storm Of Swords", "2000"),
        createListEntry("A Feast For Crows", "2005"),
        createListEntry("A Dance With Dragons", "2011"),
        createListEntry("The Winds of Winter", "2016 (please, please, please)"),
        createListEntry("A Dream of Spring", "Ugh"));

combo.setRenderer(new GenericListCellRenderer<>(new MultiButton(), new MultiButton()));
hi.add(combo);
hi.show();
GRRM ComboBox
Figure 94. GRRM ComboBox

8.18. Slider

A Slider is an empty component that can be filled horizontally or vertically to allow indicating progress, setting volume etc. It can be editable to allow the user to determine its value or none editable to relay that information to the user. It can have a thumb on top to show its current position.

Slider
Figure 95. Slider

The interesting part about the slider is that it has two separate style UIID’s, Slider & SliderFull. The Slider UIID is always painted and SliderFull is rendered on top based on the amount the Slider should be filled.

Slider is highly customizable for example: a slider can be used to replicate a 5-star rating widget as such. Notice that this slider will work when its given its preferred size otherwise more stars will appear. That’s why you place it within a FlowLayout:

Form hi = new Form("Star Slider", new BoxLayout(BoxLayout.Y_AXIS));
hi.add(FlowLayout.encloseCenter(createStarRankSlider()));
hi.show();

The slider itself is initialized in the code below. Notice that you can achieve almost the same result using a theme by setting the Slider & SliderFull UIID’s (both in selected & unselected states).

In fact doing this in the theme might be superior as you could use one image that contains 5 stars already and that way you won’t need the preferred size hack below:

private void initStarRankStyle(Style s, Image star) {
    s.setBackgroundType(Style.BACKGROUND_IMAGE_TILE_BOTH);
    s.setBorder(Border.createEmpty());
    s.setBgImage(star);
    s.setBgTransparency(0);
}

private Slider createStarRankSlider() {
    Slider starRank = new Slider();
    starRank.setEditable(true);
    starRank.setMinValue(0);
    starRank.setMaxValue(10);
    Font fnt = Font.createTrueTypeFont("native:MainLight", "native:MainLight").
            derive(Display.getInstance().convertToPixels(5, true), Font.STYLE_PLAIN);
    Style s = new Style(0xffff33, 0, fnt, (byte)0);
    Image fullStar = FontImage.createMaterial(FontImage.MATERIAL_STAR, s).toImage();
    s.setOpacity(100);
    s.setFgColor(0);
    Image emptyStar = FontImage.createMaterial(FontImage.MATERIAL_STAR, s).toImage();
    initStarRankStyle(starRank.getSliderEmptySelectedStyle(), emptyStar);
    initStarRankStyle(starRank.getSliderEmptyUnselectedStyle(), emptyStar);
    initStarRankStyle(starRank.getSliderFullSelectedStyle(), fullStar);
    initStarRankStyle(starRank.getSliderFullUnselectedStyle(), fullStar);
    starRank.setPreferredSize(new Dimension(fullStar.getWidth() * 5, fullStar.getHeight()));
    return starRank;
}
private void showStarPickingForm() {
  Form hi = new Form("Star Slider", new BoxLayout(BoxLayout.Y_AXIS));
  hi.add(FlowLayout.encloseCenter(createStarRankSlider()));
  hi.show();
}
Star Slider set to 5 (its between 0 - 10)
Figure 96. Star Slider set to 5 (its between 0 - 10)
This slider goes all the way to 0 stars which is less common. You can use a Label to represent the first star and have the slider work between 0 - 8 values to provide 4 more stars.

8.19. Table

Table is a composite component (but it isn’t a lead component), this means it’s a subclass of Container. It’s effectively built from many components.

Table is based on the TableLayout class. It’s important to be familiar with that layout manager when working with Table.

Here is a trivial sample of using the standard table component:

Form hi = new Form("Table", new BorderLayout());
TableModel model = new DefaultTableModel(
new String[] {"Col 1", "Col 2", "Col 3"},
new Object[][] {
{"Row 1", "Row A", "Row X"},
{"Row 2", "Row B", "Row Y"},
{"Row 3", "Row C", "Row Z"},
{"Row 4", "Row D", "Row K"},
}) {
public boolean isCellEditable(int row, int col) {
return col != 0;
}
};
Table table = new Table(model);
hi.add(BorderLayout.CENTER, table);
hi.show();
Simple Table usage
Figure 97. Simple Table usage
In the sample above the title area and first column aren’t editable. The other two columns are editable.

The more "interesting" capabilities of the Table class can be utilized through the TableLayout. You can use the layout constraints (also exposed in the table class) to create spanning and elaborate UI’s.

For example:

Form hi = new Form("Table", new BorderLayout());
TableModel model = new DefaultTableModel(
new String[] {"Col 1", "Col 2", "Col 3"},
new Object[][] {
{"Row 1", "Row A", "Row X"},
{"Row 2", "Row B can now stretch", null},
{"Row 3", "Row C", "Row Z"},
{"Row 4", "Row D", "Row K"},
}) {
public boolean isCellEditable(int row, int col) {
return col != 0;
}
};
Table table = new Table(model) {
@Override
protected TableLayout.Constraint createCellConstraint(Object value, int row, int column) {
TableLayout.Constraint con = super.createCellConstraint(value, row, column);
if (row == 1 && column == 1) {
con.setHorizontalSpan(2);
}
con.setWidthPercentage(33);
return con;
}
};
hi.add(BorderLayout.CENTER, table);
hi.show();
Table with spanning and fixed widths to 33%
Figure 98. Table with spanning & fixed widths to 33%

To customize the table cell behavior you can derive the Table to create a "renderer like" widget, but unlike the list this component is "kept" and used as is. This means you can bind listeners to this component and work with it as you would with any other component in Codename One.

The example above can be extended to include far more capabilities:

Form hi = new Form("Table", new BorderLayout());
TableModel model = new DefaultTableModel(
new String[] {"Col 1", "Col 2", "Col 3"},
new Object[][] {
{"Row 1", "Row A", "Row X"},
{"Row 2", "Row B can now stretch", null},
{"Row 3", "Row C", "Row Z"},
{"Row 4", "Row D", "Row K"},
}) {
public boolean isCellEditable(int row, int col) {
return col != 0;
}
};
Table table = new Table(model) {
@Override
protected Component createCell(Object value, int row, int column, boolean editable) {
Component cell;
if (row == 1 && column == 1) {
Picker p = new Picker();
p.setType(Display.PICKER_TYPE_STRINGS);
p.setStrings("Row B can now stretch", "This is a good value",
"So Is This", "Better than text field");
p.setSelectedString((String)value);
p.setUIID("TableCell");
p.addActionListener(e -> getModel().setValueAt(row, column, p.getSelectedString()));
cell = p;
} else {
cell = super.createCell(value, row, column, editable);
}
if (row > -1 && row % 2 == 0) {
cell.getAllStyles().setBgColor(0xeeeeee);
cell.getAllStyles().setBgTransparency(255);
}
return cell;
}

@Override
protected TableLayout.Constraint createCellConstraint(Object value, int row, int column) {
TableLayout.Constraint con = super.createCellConstraint(value, row, column);
if (row == 1 && column == 1) {
con.setHorizontalSpan(2);
}
con.setWidthPercentage(33);
return con;
}
};
hi.add(BorderLayout.CENTER, table);
hi.show();
Table with customize cells using the pinstripe effect
Figure 99. Table with customize cells using the pinstripe effect
Picker table cell during edit
Figure 100. Picker table cell during edit

To line wrap table cells you can override the createCell method and return a TextArea instead of a TextField since the TextArea defaults to the multi-line behavior this should work seamlessly. For example:

Form hi = new Form("Table", new BorderLayout());
TableModel model = new DefaultTableModel(
        new String[] {"Name", "Description", "Status"},
        new Object[][] {
            {"Row 1", "A short value", "OK"},
            {"Row 2", "A much longer value that wraps to multiple lines", "OK"},
            {"Row 3", "Another long table cell that needs wrapping", "Pending"},
        });
Table table = new Table(model) {
    @Override
    protected Component createCell(Object value, int row, int column, boolean editable) {
        if (row > -1 && column == 1) {
            TextArea cell = new TextArea(String.valueOf(value));
            cell.setUIID("TableCell");
            cell.setEditable(false);
            cell.setGrowByContent(true);
            return cell;
        }
        return super.createCell(value, row, column, editable);
    }

    @Override
    protected TableLayout.Constraint createCellConstraint(Object value, int row, int column) {
        TableLayout.Constraint con = super.createCellConstraint(value, row, column);
        con.setWidthPercentage(column == 1 ? 50 : 25);
        return con;
    }
};
hi.add(BorderLayout.CENTER, table);
hi.show();
Notice that you don’t need to do anything else as binding to the TextArea is built-in to the Table.
You must set the column width constraint when you want multi-line to work. Otherwise the preferred size of the column might be too wide and the remaining columns might not have space left.
Multiline table cell in portrait mode
Figure 101. Multiline table cell in portrait mode
Multiline table cell in landscape mode. Notice the cell row count adapts seamlessly
Figure 102. Multiline table cell in landscape mode. Notice the cell row count adapts seamlessly

8.19.1. Sorting tables

Sorting tables by clicking the titles is something that should work out of the box by using an API like setSortSupported(true):

Form hi = new Form("Table", new BorderLayout());
TableModel model = new DefaultTableModel(
        new String[] {"Col 1", "Col 2", "Col 3"},
        new Object[][] {
            {"Row 1", "Row A", 1},
            {"Row 2", "Row B", 4},
            {"Row 3", "Row C", 7.5},
            {"Row 4", "Row D", 2.24},
        });
Table table = new Table(model);
table.setSortSupported(true);
hi.add(BorderLayout.CENTER, table);
hi.add(BorderLayout.NORTH, new Button("Button"));
hi.show();

Notice this works with numbers, Strings and might work with dates but you can support any object type by overriding the method protected Comparator createColumnSortComparator(int column) which should return a comparator for your custom object type in the column.

8.20. Tree

Tree allows displaying hierarchical data such as folders and files in a collapsible/expandable UI. Like the Table it’s a composite component (but it isn’t a lead component). Like the Table it works in consort with a model to construct its user interface on the fly but doesn’t use a stateless renderer (as List does).

The data of the Tree arrives from a model for example: this:

class StringArrayTreeModel implements TreeModel {
    String[][] arr = new String[][] {
        {"Colors", "Letters", "Numbers"},
        {"Red", "Green", "Blue"},
        {"A", "B", "C"},
        {"1", "2", "3"}
    };

    @Override
    public Vector getChildren(Object parent) {
        Vector v = new Vector();
        if (parent == null) {
            for (int iter = 0; iter < arr[0].length; iter++) {
                v.addElement(arr[0][iter]);
            }
            return v;
        }
        for (int iter = 0; iter < arr[0].length; iter++) {
            if (parent.equals(arr[0][iter]) && arr.length > iter + 1 && arr[iter + 1] != null) {
                for (int i = 0; i < arr[iter + 1].length; i++) {
                    v.addElement(arr[iter + 1][i]);
                }
            }
        }
        return v;
    }

    @Override
    public boolean isLeaf(Object node) {
        Vector v = getChildren(node);
        return v == null || v.size() == 0;
    }
}

Tree dt = new Tree(new StringArrayTreeModel());
Form hi = new Form("Tree", new BorderLayout());
hi.add(BorderLayout.CENTER, dt);
hi.show();

Will result in this:

Tree
Figure 103. Tree
Since Tree is hierarchy based you can’t have a simple model like you’ve for the Table as deep hierarchy is harder to represent with arrays.

A more practical "real world" example would be working with XML data. You can use something like this to show an XML Tree:

Form hi = new Form("XML Tree", new BorderLayout());
// Parsed inline so the sample runs as it stands; in an application this
// would come from the network or from a packaged resource.
String xml = "<project name=\"demo\">"
        + "<target name=\"compile\"><javac srcdir=\"src\"/></target>"
        + "<target name=\"jar\"><zip destfile=\"demo.jar\"/></target>"
        + "</project>";
try (Reader r = new CharArrayReader(xml.toCharArray())) {
    Element e = new XMLParser().parse(r);
    Tree tree = new Tree(new XMLTreeModel(e)) {
        @Override
        protected String childToDisplayLabel(Object child) {
            if (child instanceof Element) {
                Element el = (Element) child;
                // getTagName() throws for the elements that carry text
                if (el.isTextElement()) {
                    return el.getText();
                }
                return el.getTagName();
            }
            return child.toString();
        }
    };
    hi.add(BorderLayout.CENTER, tree);
    xmlTree = tree;
} catch (IOException err) {
    Log.e(err);
}
hi.show();
The try with resources syntax closes the Reader for you however the block ends.
XML Tree
Figure 104. XML Tree

The model for the XML hierarchy is implemented as such:

/// Walks a parsed XML document as a tree: the document element is the single
/// root, and a node's children are the element's children.
static class XMLTreeModel implements TreeModel {
    private Element root;

    XMLTreeModel(Element e) {
        root = e;
    }

    @Override
    public Vector getChildren(Object parent) {
        if (parent == null) {
            Vector c = new Vector();
            c.addElement(root);
            return c;
        }
        Vector result = new Vector();
        Element e = (Element) parent;
        for (int iter = 0; iter < e.getNumChildren(); iter++) {
            result.addElement(e.getChildAt(iter));
        }
        return result;
    }

    @Override
    public boolean isLeaf(Object node) {
        Element e = (Element) node;
        return e.getNumChildren() == 0;
    }
}

8.21. ShareButton

ShareButton is a button you can add into the UI to let a user share an image or block of text.

The ShareButton uses a set of predefined share options on the simulator. On Android & iOS the ShareButton is mapped to the OS native sharing functionality and can share the image/text with the services configured on the device (for example: Twitter, Facebook etc.).

Sharing text is trivial but to share an image you need to save it to the FileSystemStorage. Notice that saving to Storage won’t work!

In the sample code below you take a screenshot which is saved to FileSystemStorage for sharing:

Form hi = new Form("ShareButton");
ShareButton sb = new ShareButton();
sb.setText("Share Screenshot");
hi.add(sb);

Image screenshot = Image.createImage(hi.getWidth(), hi.getHeight());
hi.revalidate();
hi.setVisible(true);
hi.paintComponent(screenshot.getGraphics(), true);

String imageFile = FileSystemStorage.getInstance().getAppHomePath() + "screenshot.png";
try(OutputStream os = FileSystemStorage.getInstance().openOutputStream(imageFile);) {
    ImageIO.getImageIO().save(screenshot, os, ImageIO.FORMAT_PNG, 1);
} catch(IOException err) {
    Log.e(err);
}
sb.setImageToShare(imageFile, "image/png");
The share button running on the simulator
Figure 105. The share button running on the simulator
ShareButton behaves differently on the device…​
The share button running on the Android device and screenshot sent into twitter
Figure 106. The share button running on the Android device and screenshot sent into twitter
The ShareButton features some share service classes to allow plugging in more share services. For example, this functionality is relevant to devices where native sharing isn’t supported. This code isn’t used on iOS/Android…​

8.21.1. Share Result Callback

The share API can report what the user did with the share sheet. Register a ShareResultListener on either ShareButton or directly with Display.share(…​) and you receive a single ShareResult describing the outcome:

  • SHARED_TO(packageName) — the user picked a destination. packageName is the chosen target’s identifier: an Android package name (for example, com.whatsapp) or, on iOS, a UIActivityType such as com.apple.UIKit.activity.PostToTwitter. It may be null when the platform doesn’t expose the selection (for example, older Android, Web Share API).

  • DISMISSED — the user cancelled without picking a target. iOS reports this reliably; Android’s chooser has no public dismissal signal, so on Android the listener simply doesn’t fire on cancel.

  • FAILED — the share couldn’t be completed. getError() may carry a short platform-supplied message.

The listener is always invoked on the EDT, exactly once per share request.

ShareButton sb = new ShareButton();
sb.setTextToShare("Check this out!");
sb.setShareResultListener(result -> {
    if (result.isSharedTo()) {
        Log.p("Shared to " + result.getPackageName());
    } else if (result.isDismissed()) {
        Log.p("User dismissed the share sheet");
    } else if (result.isFailed()) {
        Log.p("Share failed: " + result.getError());
    }
});
form.add(sb);

If you call Display directly instead of using ShareButton, pass the listener as the final argument to the new overload:

Display.getInstance().share(
        "Check this out!", imagePath, "image/png", sourceRect,
        result -> handleResult(result));

When the share is dispatched through the non-native fallback dialog (platforms without isNativeShareSupported), the listener still fires: it reports DISMISSED when the user picks the Cancel button, and the underlying ShareService implementations report SHARED_TO once they call ShareService.finish(). Custom ShareService subclasses can call deliverResult(ShareResult.failed("…​")) from inside share(…​) to publish a failure explicitly; otherwise finish() falls back to a default SHARED_TO(commandName).

8.22. iOS Share Extension Authoring Helper

An iOS share extension is a separate app target that the system shows inside UIActivityViewController when the user shares from another app (Safari, Photos, etc.). It runs in a sandboxed process and persists payloads to the host app via an App Group shared NSUserDefaults suite.

Codename One’s build pipeline already wires .ios.appext zip archives under src/main/resources into the generated Xcode project. The IOSShareExtensionBuilder helper generates that archive for you so you don’t have to create the extension target in Xcode first.

8.22.1. What the helper produces

For a single call the helper writes four files at the root of the extension bundle:

  • Info.plist — declares the NSExtension dictionary, activation rules (SupportsText / SupportsWebURL / SupportsImage), and the principal class (ShareViewController).

  • <ExtensionName>.entitlements — declares com.apple.security.application-groups with the configured App Group identifier.

  • ShareViewController.swift — a SLComposeServiceViewController subclass that extracts text / URL / image attachments from extensionContext, packs them into a dictionary, and writes that dictionary to UserDefaults(suiteName: appGroupId) under the key cn1.shareExtension.payload.

  • buildSettings.properties — Xcode build setting overrides (deployment target, Swift version, entitlements path, plist path) picked up by the iOS build pipeline.

8.22.2. Generating the bundle

Call the builder from a Maven plugin, an Ant task or a one-shot main:

IOSShareExtensionBuilder lives in the Codename One Maven plugin rather than in the framework, so this runs at build time and isn’t one of the compiled examples:

new IOSShareExtensionBuilder()
        .setExtensionName("MyShareExtension")
        .setDisplayName("Share to MyApp")
        .setHostBundleId("com.example.myapp")
        .setAppGroupId("group.com.example.myapp")
        .acceptText(true)
        .acceptURLs(true)
        .acceptImages(true)
        .writeAppext(new File("src/main/resources/MyShareExtension.ios.appext"));

The next iOS build picks up the .ios.appext archive automatically; no Xcode steps are required.

If you prefer a directory layout (for example, to commit the generated sources or to feed a future ios/app_extensions/ pipeline) use writeTo(File) instead of writeAppext(File) — the file contents are identical.

8.22.3. Reading the payload from the host app

The host app has to be in that App Group too. setAppGroupId writes the entitlement for the extension only, so add the same identifier to the application with the ios.app_groups build hint — the two sides are reading and writing one container, and a mismatch produces an empty dictionary rather than an error:

codename1.arg.ios.app_groups=group.com.example.myapp

It then reads the most recent payload at startup or when it resumes:

// Inside an iOS native interface
NSUserDefaults* shared =
    [[NSUserDefaults alloc] initWithSuiteName:@"group.com.example.myapp"];
NSDictionary* payload = [shared dictionaryForKey:@"cn1.shareExtension.payload"];

The payload dictionary contains:

  • text — the user-composed text (String).

  • items — an array of { kind, value } dictionaries where kind is "text", "url" or "image". For images, value is a file URL inside the App Group container.

  • timestamp — a Double UNIX time.

Expose this to your CN1 code via a small native interface and clear the key once handled so the next share is unambiguous.

8.22.4. Activation rules and validation

The builder validates its inputs before writing anything:

  • extensionName must be a non-empty identifier (letters, digits, _, -). It becomes the Xcode target name and the .appex bundle name. The extension’s bundle id is set to <hostBundleId>.<extensionName> by the iOS build pipeline.

  • appGroupId must start with group. (an Apple requirement). Create the matching App Group in your Apple Developer account and add it to both the host app’s and the extension’s provisioning profile.

  • At least one of acceptText, acceptURLs, acceptImages must be enabled, otherwise iOS will never present your extension.

The default deployment target is iOS 12.0; override with setDeploymentTarget("13.0") if you need newer APIs in your customized controller.

8.22.5. Customising the generated controller

The generated Swift controller covers the common case (read attachments, persist to App Group, finish the request). If you need bespoke logic — custom UI, server upload, image transcoding — treat the helper’s output as a starting point: run it once, copy the directory under ios/app_extensions/MyShareExtension/, edit ShareViewController.swift, and zip it back into .ios.appext (or wait for the directory-based pipeline tracked by issue #3427).

Provisioning profiles for the extension target aren’t generated by the helper. You still need to provision the extension’s bundle id (<hostBundleId>.<extensionName>) and add the App Group capability to it on the Apple Developer portal, alongside the host app.

8.23. Tabs

The Tabs Container arranges components into groups within "tabbed" containers. Tabs is a container type that allows leafing through its children using labeled toggle buttons. The tabs can be placed in many different ways (top, bottom, left or right) with the default being determined by the platform. This class also allows swiping between components to leaf between said tabs (for this purpose the tabs themselves can also be hidden).

Since Tabs are a Container its a common mistake to try and add a Tab using the add method. That method won’t work since a Tab can have both an Image and text String associated with it:

Form hi = new Form("Tabs", new BorderLayout());

Tabs t = new Tabs();
Style s = UIManager.getInstance().getComponentStyle("Tab");
FontImage icon1 = FontImage.createMaterial(FontImage.MATERIAL_QUESTION_ANSWER, s);

Container container1 = BoxLayout.encloseY(new Label("Label1"), new Label("Label2"));
t.addTab("Tab1", icon1, container1);
t.addTab("Tab2", new SpanLabel("Some text directly in the tab"));

hi.add(BorderLayout.CENTER, t);
Simple usage of Tabs
Figure 107. Simple usage of Tabs

A common usage for Tabs is the swipe to proceed effect which is common in iOS applications. In the code below you use RadioButton and LayeredLayout with hidden tabs to produce that effect:

Form hi = new Form("Swipe Tabs", new LayeredLayout());
Tabs t = new Tabs();
t.hideTabs();

Style s = UIManager.getInstance().getComponentStyle("Button");
FontImage radioEmptyImage = FontImage.createMaterial(FontImage.MATERIAL_RADIO_BUTTON_UNCHECKED, s);
FontImage radioFullImage = FontImage.createMaterial(FontImage.MATERIAL_RADIO_BUTTON_CHECKED, s);
((DefaultLookAndFeel) UIManager.getInstance().getLookAndFeel())
        .setRadioButtonImages(radioFullImage, radioEmptyImage, radioFullImage, radioEmptyImage);

Container container1 = BoxLayout.encloseY(new Label("Swipe the tab to see more"),
        new Label("You can put anything here"));
t.addTab("Tab1", container1);
t.addTab("Tab2", new SpanLabel("Some text directly in the tab"));

RadioButton firstTab = new RadioButton("");
RadioButton secondTab = new RadioButton("");
firstTab.setUIID("Container");
secondTab.setUIID("Container");
new ButtonGroup(firstTab, secondTab);
firstTab.setSelected(true);
Container tabsFlow = FlowLayout.encloseCenter(firstTab, secondTab);

hi.add(t);
hi.add(BorderLayout.south(tabsFlow));

t.addSelectionListener((i1, i2) -> {
    switch (i2) {
        case 0:
            if (!firstTab.isSelected()) {
                firstTab.setSelected(true);
            }
            break;
        case 1:
            if (!secondTab.isSelected()) {
                secondTab.setSelected(true);
            }
            break;
        default:
            break;
    }
});
Swipeable Tabs with an iOS carousel effect page 1
Figure 108. Swipeable Tabs with an iOS carousel effect page 1
Swipeable Tabs with an iOS carousel effect page 2
Figure 109. Swipeable Tabs with an iOS carousel effect page 2
Notice that you used setRadioButtonImages to explicitly set the radio button images to the look you want for the carousel.

8.23.1. Animated tab indicator

Modern Material 3 (NavigationBar) and iOS 26 tab bars animate a small underline between tabs when the user changes selection. Tabs ships this as an opt-in feature gated by the tabsAnimatedIndicatorBool theme constant; the iOS Modern and Android Material themes turn it on by default, so apps shipping against those themes get the effect for free.

To enable in a custom theme:

#Constants {
    tabsAnimatedIndicatorBool: true;
    tabsAnimatedIndicatorDurationInt: 200;    /* tween duration in ms */
    tabsAnimatedIndicatorThicknessMm: 1;      /* underline thickness  */
}

TabIndicator {
    /* The indicator picks up its color from this UIID's fg. If the
       UIID isn't defined or has fgColor == 0, the indicator falls
       back to the currently-selected tab's fgColor. */
    color: #007aff;
    background-color: transparent;
    padding: 0;
    margin: 0;
}

To toggle programmatically (for example, add it to a Tabs instance whose theme hasn’t enabled it):

Tabs tabs = new Tabs();
tabs.setAnimatedIndicator(true);

The indicator animates its x / width from the previously selected tab’s bounds to the new selection’s bounds using a Motion.createEaseInOutMotion over the configured duration (200ms default, matching Material 3’s spec). Rapid double-taps start the animation from the current interpolated position rather than from a stale baseline, so the indicator chains cleanly.

8.24. MediaManager & MediaPlayer

MediaPlayer is a peer component, understanding this is crucial if your application depends on such a component. You can learn about peer components and their issues here.

The MediaPlayer allows you to control video playback. To use the MediaPlayer you need to first load the Media object from the MediaManager.

The MediaManager is the core class responsible for media interaction in Codename One.

You should also check out the Capture class for things that aren’t covered by the MediaManager.

In the demo code below you use the gallery functionality to pick a video from the device’s video gallery:

final Form hi = new Form("MediaPlayer", new BorderLayout());
hi.setToolbar(new Toolbar());
Style s = UIManager.getInstance().getComponentStyle("Title");
FontImage icon = FontImage.createMaterial(FontImage.MATERIAL_VIDEO_LIBRARY, s);
hi.getToolbar().addCommandToRightBar("", icon, (evt) -> {
    Display.getInstance().openGallery((e) -> {
        if(e != null && e.getSource() != null) {
            String file = (String)e.getSource();
            try {
                Media video = MediaManager.createMedia(file, true);
                hi.removeAll();
                hi.add(BorderLayout.CENTER, new MediaPlayer(video));
                hi.revalidate();
            } catch(IOException err) {
                Log.e(err);
            }
        }
    }, Display.GALLERY_VIDEO);
});
hi.show();
Video playback running on the simulator
Figure 110. Video playback running on the simulator
Video playback running on an Android device. Notice the native playback controls that appear when the video is tapped
Figure 111. Video playback running on an Android device. Notice the native playback controls that appear when the video is tapped
Video playback in the simulator will work with JavaFX enabled. This is the default for Java 8 or newer so recommend using that.

8.25. ImageViewer

The ImageViewer allows you to inspect, zoom and pan into an image. It also allows swiping between images if you have a set of images (using an image list model).

The ImageViewer is a complex rich component designed for user interaction. If you want to display an image use Label if you want the image to scale seamlessly use ScaleImageLabel.

You can use the ImageViewer as a tool to view a single image which allows you to zoom in/out to that image as such:

Image duke = FontImage.createMaterial(FontImage.MATERIAL_INFO, "Label", 3.0f);
Form hi = new Form("ImageViewer", new BorderLayout());
ImageViewer iv = new ImageViewer(duke);
hi.add(BorderLayout.CENTER, iv);
hi.show();
You can simulate pinch to zoom on the simulator by dragging the right button away from the top left corner to zoom in and towards the top left corner to zoom out. On Mac touchpads you can drag two fingers to achieve that.
ImageViewer as the demo loads with the image from the default icon
Figure 112. ImageViewer as the demo loads with the image from the default icon
ImageViewer zoomed in
Figure 113. ImageViewer zoomed in

You can work with a list of images to produce a swiping effect for the image viewer where you can swipe from one image to the next and also zoom in/out on a specific image:

Form hi = new Form("ImageViewer", new BorderLayout());

Image red = Image.createImage(100, 100, 0xffff0000);
Image green = Image.createImage(100, 100, 0xff00ff00);
Image blue = Image.createImage(100, 100, 0xff0000ff);
Image gray = Image.createImage(100, 100, 0xffcccccc);

ImageViewer iv = new ImageViewer(red);
iv.setImageList(new DefaultListModel<>(red, green, blue, gray));
hi.add(BorderLayout.CENTER, iv);
An ImageViewer with many elements is indistinguishable from a single ImageViewer except for swipe
Figure 114. An ImageViewer with many elements is indistinguishable from a single ImageViewer except for swipe

Notice that you use a ListModel to allow swiping between images.

ImageViewer also supports optional side arrows (material font icons) and an optional thumbnail strip for direct image navigation:

Image red = FontImage.createMaterial(FontImage.MATERIAL_LOOKS_ONE, "Label", 6.0f);
Image green = FontImage.createMaterial(FontImage.MATERIAL_LOOKS_TWO, "Label", 6.0f);
Image blue = FontImage.createMaterial(FontImage.MATERIAL_LOOKS_3, "Label", 6.0f);
Image gray = FontImage.createMaterial(FontImage.MATERIAL_LOOKS_4, "Label", 6.0f);
ImageViewer iv = new ImageViewer(red);
iv.setImageList(new DefaultListModel<>(red, green, blue, gray));
iv.setNavigationArrowsVisible(true);
iv.setThumbnailsVisible(true);
iv.setThumbnailBarHeight(6f); // Optional, defaults to 6mm
Form hi = new Form("ImageViewer", new BorderLayout());
hi.add(BorderLayout.CENTER, iv);
hi.show();

When arrows are enabled, tapping near the left/right edge will move to the previous/next image. When thumbnails are enabled, tapping a thumbnail jumps directly to that image.

All three options can be configured with theme constants (using the ImageViewer UIID prefix):

  • imageviewerNavigationArrowsBool=true|false

  • imageviewerThumbnailsBool=true|false

  • imageviewerThumbnailBarHeightMM=<floating point millimeters>

EncodedImage’s aren’t always fully loaded and so when you swipe if the images are large you might see delays!

You can dynamically download images directly into the ImageViewer with a custom list model like this:

Style s = UIManager.getInstance().getComponentStyle("Label");
Form hi = new Form("ImageViewer", new BorderLayout());
final EncodedImage placeholder = EncodedImage.createFromImage(
        FontImage.createMaterial(FontImage.MATERIAL_SYNC, s).
                scaled(300, 300), false);

class ImageList implements ListModel<Image> {
    private int selection;
    private final java.util.List<SelectionListener> selectionListeners = new ArrayList<>();
    private String[] imageURLs = {
        "https://awoiaf.westeros.org/images/thumb/9/93/AGameOfThrones.jpg/300px-AGameOfThrones.jpg",
        "https://awoiaf.westeros.org/images/thumb/3/39/AClashOfKings.jpg/300px-AClashOfKings.jpg",
        "https://awoiaf.westeros.org/images/thumb/2/24/AStormOfSwords.jpg/300px-AStormOfSwords.jpg",
        "https://awoiaf.westeros.org/images/thumb/a/a3/AFeastForCrows.jpg/300px-AFeastForCrows.jpg",
        "https://awoiaf.westeros.org/images/7/79/ADanceWithDragons.jpg"
    };
    private Image[] images;
    private EventDispatcher listeners = new EventDispatcher();

    public ImageList() {
        this.images = new EncodedImage[imageURLs.length];
    }

    public Image getItemAt(final int index) {
        if(images[index] == null) {
            images[index] = placeholder;
            Util.downloadUrlToStorageInBackground(imageURLs[index], "list" + index, (e) -> {
                    try {
                        try(InputStream is = Storage.getInstance().createInputStream("list" + index)) {
                            // EncodedImage.create reads the stream but does not close it
                            images[index] = EncodedImage.create(is);
                        }
                        listeners.fireDataChangeEvent(index, DataChangedListener.CHANGED);
                    } catch(IOException err) {
                        err.printStackTrace();
                    }
            });
        }
        return images[index];
    }

    public int getSize() {
        return imageURLs.length;
    }

    public int getSelectedIndex() {
        return selection;
    }

    public void setSelectedIndex(int index) {
        int old = selection;
        selection = index;
        // ImageViewer swaps the displayed image from this event
        for(SelectionListener l : selectionListeners) {
            l.selectionChanged(old, index);
        }
    }

    public void addDataChangedListener(DataChangedListener l) {
        listeners.addListener(l);
    }

    public void removeDataChangedListener(DataChangedListener l) {
        listeners.removeListener(l);
    }

    public void addSelectionListener(SelectionListener l) {
        selectionListeners.add(l);
    }

    public void removeSelectionListener(SelectionListener l) {
        selectionListeners.remove(l);
    }

    public void addItem(Image item) {
    }

    public void removeItem(int index) {
    }
};

ImageList imodel = new ImageList();

ImageViewer iv = new ImageViewer(imodel.getItemAt(0));
iv.setImageList(imodel);
hi.add(BorderLayout.CENTER, iv);
hi.show();
Dynamically fetching an image URL from the internet
Figure 115. Dynamically fetching an image URL from the internet [4]

This fetches the images in the URL asynchronously and fires a data change event when the data arrives to automatically refresh the ImageViewer when that happens.

8.26. ScaleImageLabel & ScaleImageButton

ScaleImageLabel & ScaleImageButton allow you to position an image that will grow/shrink to fit available space. In that sense they differ from Label & Button which keeps the image at the same size.

The default UIID of ScaleImageLabel is Label, but the default UIID of ScaleImageButton is ScaleImageButton. The reasoning for the difference is that the Button UIID includes a border and a lot of legacy.

You can use ScaleImageLabel/ScaleImageButton interchangeably. The major difference between these components is the buttons ability to handle click events/focus.

Here is a simple example that also shows the difference between the scale to fill and scale to fit modes:

TableLayout tl = new TableLayout(2, 2);
Form hi = new Form("ScaleImageButton/Label", tl);
Style s = UIManager.getInstance().getComponentStyle("Button");
Image icon = FontImage.createMaterial(FontImage.MATERIAL_WARNING, s);
ScaleImageLabel fillLabel = new ScaleImageLabel(icon);
fillLabel.setBackgroundType(Style.BACKGROUND_IMAGE_SCALED_FILL);
ScaleImageButton fillButton = new ScaleImageButton(icon);
fillButton.setBackgroundType(Style.BACKGROUND_IMAGE_SCALED_FILL);
hi.add(tl.createConstraint().widthPercentage(20), new ScaleImageButton(icon)).
        add(tl.createConstraint().widthPercentage(80), new ScaleImageLabel(icon)).
        add(fillLabel).
        add(fillButton);
hi.show();
ScaleImageLabel/Button the top row includes scale to fit versions (the default) whereas the bottom row includes the scale to fill versions
Figure 116. ScaleImageLabel/Button, the top row includes scale to fit versions (the default) whereas the bottom row includes the scale to fill versions
When styling these components keep in mind that changing attributes such as background behavior might cause an issue with their functionality or might not work.

8.27. Toolbar

The Toolbar API provides deep customization of the title bar area with more flexibility for example: placing a TextField for search or buttons in arbitrary title area positions. The Toolbar API replicates some native functionality available on Android/iOS and integrates with features such as the side menu to provide fine grained control over the title area behavior.

The Toolbar needs to be installed into the Form in order for it to work. You can setup the Toolbar in one of these three ways:

  1. form.setToolbar(new Toolbar()); - allows you to activate the Toolbar to a specific Form and not for the entire application

  2. Toolbar.setGlobalToolbar(true); - enables the Toolbar for all the forms in the app

  3. Theme constant globalToobarBool - this is equivalent to Toolbar.setGlobalToolbar(true);

The basic functionality of the Toolbar includes the ability to add a command to the following 4 places:

  • Left side of the title - addCommandToLeftBar

  • Right side of the title - addCommandToRightBar

  • Side menu bar (the drawer that opens when you click the icon on the top left or swipe the screen from left to right) - addCommandToSideMenu

  • Overflow menu (the menu that opens when you tap the 3 vertical dots in the top right corner) - addCommandToOverflowMenu

The code below provides a brief overview of these options:

Style s = UIManager.getInstance().getComponentStyle("TitleCommand");
Image icon = FontImage.createMaterial(FontImage.MATERIAL_INFO, s);
Toolbar.setGlobalToolbar(true);

Form hi = new Form("Toolbar", new BoxLayout(BoxLayout.Y_AXIS));
hi.getToolbar().addCommandToLeftBar("Left", icon, (e) -> Log.p("Clicked"));
hi.getToolbar().addCommandToRightBar("Right", icon, (e) -> Log.p("Clicked"));
hi.getToolbar().addCommandToOverflowMenu("Overflow", icon, (e) -> Log.p("Clicked"));
hi.getToolbar().addCommandToSideMenu("Sidemenu", icon, (e) -> Log.p("Clicked"));
hi.show();
The Toolbar
Figure 117. The Toolbar
The default sidemenu of the Toolbar
Figure 118. The default sidemenu of the Toolbar
The overflow menu of the Toolbar
Figure 119. The overflow menu of the Toolbar

You can set a title with a String but if you would want the component to be a text field or a multi line label you can use setTitleComponent(Component) which allows you to install any component into the title area.

The code below demonstrates searching using custom code but the Toolbar also has built-in support for search covered in the next section

The customization of the title area allows for some pretty powerful UI effects for example: the code below allows searching dynamically within a set of entries and uses some neat tricks:

Toolbar.setGlobalToolbar(true);
Style s = UIManager.getInstance().getComponentStyle("Title");

Form hi = new Form("Toolbar", new BoxLayout(BoxLayout.Y_AXIS));
TextField searchField = new TextField("", "Toolbar Search"); (1)
searchField.getHintLabel().setUIID("Title");
searchField.setUIID("Title");
searchField.getAllStyles().setAlignment(Component.LEFT);
hi.getToolbar().setTitleComponent(searchField);
FontImage searchIcon = FontImage.createMaterial(FontImage.MATERIAL_SEARCH, s);
searchField.addDataChangeListener((i1, i2) -> { (2)
    String t = searchField.getText();
    if (t.length() < 1) {
        for (Component cmp : hi.getContentPane()) {
            cmp.setHidden(false);
            cmp.setVisible(true);
        }
    } else {
        String needle = t.toLowerCase();
        for (Component cmp : hi.getContentPane()) {
            String val;
            if (cmp instanceof Label) {
                val = ((Label) cmp).getText();
            } else {
                if (cmp instanceof TextArea) {
                    val = ((TextArea) cmp).getText();
                } else {
                    val = (String) cmp.getPropertyValue("text");
                }
            }
            boolean show = val != null && val.toLowerCase().indexOf(needle) > -1;
            cmp.setHidden(!show);
            cmp.setVisible(show); (3)
        }
    }
    hi.getContentPane().animateLayout(250);
});
hi.getToolbar().addCommandToRightBar("", searchIcon, (e) -> { (4)
    searchField.startEditingAsync();
});

hi.add("A Game of Thrones").
        add("A Clash Of Kings").
        add("A Storm Of Swords").
        add("A Feast For Crows").
        add("A Dance With Dragons").
        add("The Winds of Winter").
        add("A Dream of Spring");
hi.show();
1You use a TextField the whole time and style it to make it (and its hint) look like a regular title. An alternative way is to replace the title component dynamically.
2You use the DataChangedListener to update the search results as you type them.
3Hidden & Visible use the opposite flag values to say similar things (for example: when hidden is set to false you would want to set visible to true).
Visible indicates whether a component can be seen. It will still occupy the physical space on the screen even when it isn’t visible. Hidden will remove the space occupied by the component from the screen, but some code might still try to paint it., visible is redundant but you use it with hidden for good measure.
4The search button is totally unnecessary here. You can click the TextField!
For example, that isn’t intuitive to most users so a button is added to start editing.
Search field within the toolbar
Figure 120. Search field within the toolbar
Search field after typing a couple of letters
Figure 121. Search field after typing a couple of letters

8.27.1. Search mode

While you can implement search manually, using the built-in search offers a simpler and uniform UI.

built-in toolbar search functionality
Figure 122. built-in toolbar search functionality

You can customize the appearance of the search bar by using the UIID’s: ToolbarSearch, TextFieldSearch & TextHintSearch.

In the sample below you fetch all the contacts from the device and enable search through them, notice it expects and image called duke.png which is the default Codename One icon renamed and placed in the src folder:

int fiveMM = Display.getInstance().convertToPixels(5);
// a material icon, so the sample needs no bundled asset
final Image finalDuke = FontImage.createMaterial(FontImage.MATERIAL_PORTRAIT, "Label", 3.0f)
        .scaledWidth(fiveMM);
Toolbar.setGlobalToolbar(true);
Form hi = new Form("Search", BoxLayout.y());
hi.add(new InfiniteProgress());
Display.getInstance().scheduleBackgroundTask(()-> {
    // this will take a while...
    Contact[] cnts = Display.getInstance().getAllContacts(true, true, true, true, false, false);
    Display.getInstance().callSerially(() -> {
        hi.removeAll();
        if(cnts == null) {
            // the platform has no contacts API, or access was refused
            hi.add(new Label("Contacts are unavailable"));
            hi.revalidate();
            return;
        }
        for(Contact c : cnts) {
            MultiButton m = new MultiButton();
            m.setTextLine1(c.getDisplayName());
            m.setTextLine2(c.getPrimaryPhoneNumber());
            Image pic = c.getPhoto();
            if(pic != null) {
                m.setIcon(pic.fill(finalDuke.getWidth(), finalDuke.getHeight()));
            } else {
                m.setIcon(finalDuke);
            }
            hi.add(m);
        }
        // the query may have been typed while the contacts were loading
        filterContacts(hi, currentSearch);
        hi.revalidate();
    });
});

hi.getToolbar().addSearchCommand(e -> {
    currentSearch = (String)e.getSource();
    filterContacts(hi, currentSearch);
}, 4);

hi.show();

The filter itself, shared by the search command and the load callback so a query typed while the contacts are still arriving is reapplied once they do:

String currentSearch;

void filterContacts(Form hi, String text) {
    if(text == null || text.length() == 0) {
        // clear search
        for(Component cmp : hi.getContentPane()) {
            cmp.setHidden(false);
            cmp.setVisible(true);
        }
        hi.getContentPane().animateLayout(150);
        return;
    }
    text = text.toLowerCase();
    for(Component cmp : hi.getContentPane()) {
        if(!(cmp instanceof MultiButton)) {
            // the loading indicator is still there until the contacts arrive
            continue;
        }
        MultiButton mb = (MultiButton)cmp;
        String line1 = mb.getTextLine1();
        String line2 = mb.getTextLine2();
        boolean show = line1 != null && line1.toLowerCase().indexOf(text) > -1 ||
                line2 != null && line2.toLowerCase().indexOf(text) > -1;
        mb.setHidden(!show);
        mb.setVisible(show);
    }
    hi.getContentPane().animateLayout(150);
}

8.27.2. South Component

A common feature in side menu bar is the ability to add a component to the "south" part of the side menu.

Notice that this feature works with the on-top and permanent versions of the side menu and not with the legacy versions:

toolbar.setComponentToSideMenuSouth(myComponent);

This places the component below the side menu bar. Notice that this component controls its entire UIID & is separate from the SideNavigationPanel UIID so if you set that component you might want to place it within a container that has the SideNavigationPanel UIID so it will blend with the rest of the UI.

8.27.3. Title animations

Modern UI’s often animate the title upon scrolling to balance the highly functional smaller title advantage with the gorgeous large image based title. This is pretty easy to do with the Toolbar API through the Title animation API.

The code below shows off an attractive title based on a book by GRRM on top of text [5] that’s scrollable. As the text is scrolled the title fades out:

Toolbar.setGlobalToolbar(true);

Form hi = new Form("Toolbar", new BoxLayout(BoxLayout.Y_AXIS));
EncodedImage placeholder = EncodedImage.createFromImage(Image.createImage(hi.getWidth(), hi.getWidth() / 5, 0xffff0000), true);
URLImage background = URLImage.createToStorage(placeholder, "400px-AGameOfThrones.jpg",
        "http://awoiaf.westeros.org/images/thumb/9/93/AGameOfThrones.jpg/400px-AGameOfThrones.jpg");
background.fetch();
Style stitle = hi.getToolbar().getTitleComponent().getUnselectedStyle();
stitle.setBgImage(background);
stitle.setBackgroundType(Style.BACKGROUND_IMAGE_SCALED_FILL);
stitle.setPaddingUnit(Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS);
stitle.setPaddingTop(15);
SpanButton credit = new SpanButton("This excerpt is from A Wiki Of Ice And Fire. Please check it out by clicking here!");
credit.addActionListener((e) -> Display.getInstance().execute("http://awoiaf.westeros.org/index.php/A_Game_of_Thrones"));
hi.add(new SpanLabel("A Game of Thrones is the first of seven planned novels in A Song of Ice and Fire, an epic fantasy series by American author George R. R. Martin. It was first published on 6 August 1996. The novel was nominated for the 1998 Nebula Award and the 1997 World Fantasy Award,[1] and won the 1997 Locus Award.[2] The novella Blood of the Dragon, comprising the Daenerys Targaryen chapters from the novel, won the 1997 Hugo Award for Best Novella. ")).
        add(new Label("Plot introduction", "Heading")).
        add(new SpanLabel("A Game of Thrones is set in the Seven Kingdoms of Westeros, a land reminiscent of Medieval Europe. In Westeros the seasons last for years, sometimes decades, at a time.\n\n" +
            "Fifteen years prior to the novel, the Seven Kingdoms were torn apart by a civil war, known alternately as \"Robert's Rebellion\" and the \"War of the Usurper.\" Prince Rhaegar Targaryen kidnapped Lyanna Stark, arousing the ire of her family and of her betrothed, Lord Robert Baratheon (the war's titular rebel). The Mad King, Aerys II Targaryen, had Lyanna's father and eldest brother executed when they demanded her safe return. Her second brother, Eddard, joined his boyhood friend Robert Baratheon and Jon Arryn, with whom they had been fostered as children, in declaring war against the ruling Targaryen dynasty, securing the allegiances of House Tully and House Arryn through a network of dynastic marriages (Lord Eddard to Catelyn Tully and Lord Arryn to Lysa Tully). The powerful House Tyrell continued to support the King, but House Lannister and House Martell both stalled due to insults against their houses by the Targaryens. The civil war climaxed with the Battle of the Trident, when Prince Rhaegar was killed in battle by Robert Baratheon. The Lannisters finally agreed to support King Aerys, but then brutally... ")).
        add(credit);

ComponentAnimation title = hi.getToolbar().getTitleComponent().createStyleAnimation("Title", 200);
hi.getAnimationManager().onTitleScrollAnimation(title);
hi.show();
The Toolbar starts with the large URLImage fetched from the web
Figure 123. The Toolbar starts with the large URLImage fetched from the web
As you scroll down the image fades and the title shrinks in size returning to the default UIID look
Figure 124. As you scroll down the image fades and the title shrinks in size returning to the default UIID look
As scrolling continues the title reaches standard size
Figure 125. As scrolling continues the title reaches standard size

Most the code above creates the "look" of the application. The key piece of code above is this:

ComponentAnimation title = hi.getToolbar().getTitleComponent().createStyleAnimation("Title", 200);
hi.getAnimationManager().onTitleScrollAnimation(title);

In the first line you create a style animation that will translate the style from the current settings to the destination UIID (the first argument) within 200 pixels of scrolling. You then bind this animation to the title scrolling animation event.

8.28. BrowserComponent & WebBrowser

BrowserComponent is a peer component, understanding this is crucial if your application depends on such a component. You can learn about peer components and their issues here.

The WebBrowser component shows the native device web browser when supported by the device and the HTMLComponent when the web browser isn’t supported on the given device. If you intend to target smartphones you should use the BrowserComponent directly instead of the WebBrowser.

The BrowserComponent can point at an arbitrary URL to load it:

Form hi = new Form("Browser", new BorderLayout());
BrowserComponent browser = new BrowserComponent();
browser.setURL("https://www.codenameone.com/");
hi.add(BorderLayout.CENTER, browser);
Browser Component showing the Codename One website on the simulator
Figure 126. Browser Component showing the Codename One website on the simulator
The scrollbars appear in the simulator, device versions of the browser component act differently and support touch scrolling.
A BrowserComponent should be in the center of a BorderLayout. Otherwise its preferred size might be zero before the HTML finishes loading/layout in the native layer and layout might be wrong as a result.

You can use WebBrowser and BrowserComponent interchangeably for most basic usage. For example, if you need access to JavaScript or native browser functionality then there is no use in going through the WebBrowser abstraction.

The BrowserComponent has full support for executing local web pages from within the jar. The basic support uses the jar:/// URL as such:

BrowserComponent wb = new BrowserComponent();
wb.setURL("jar:///Page.html");
On Android a native indicator might show up when the web page is loading. This can be disabled using the Display.getInstance().setProperty("WebLoadingHidden", "true"); call. You need to invoke this once.

8.28.1. Troubleshooting "Failed to create CEF browser" on Linux

In the Simulator, BrowserComponent is rendered by the bundled CEF (Chromium Embedded Framework) port. On Linux, BrowserComponent.isNativeBrowserSupported() may return true and yet creating the component throws RuntimeException: Failed to create CEF browser, with a root cause similar to:

java.lang.UnsatisfiedLinkError: .../codenameone-cef-*-linux64.zip-extracted/lib/linux64/libjcef.so:
    .../lib/linux64/libjawt.so: version `SUNWprivate_1.1' not found
    (required by .../lib/linux64/libjcef.so)

The native CEF library (libjcef.so) is loaded with a sibling libjawt.so shipped inside the CEF archive. That copy of libjawt.so expects symbols (SUNWprivate_1.1) provided by the JDK’s own libjawt.so and the matching libjvm.so. When the JVM running the Simulator doesn’t expose those symbols at load time — typically because the dynamic linker doesn’t have the JDK’s native library directories on its search path — the load fails before any browser is created. This is purely a Simulator/desktop concern; the same code runs unchanged on Android and iOS.

The fix is to launch the IDE (and therefore the Simulator JVM) with JAVA_HOME and LD_LIBRARY_PATH pointing at a supported JDK. For example, on Linux Mint / Ubuntu wrap the IDE startup script:

#!/bin/bash
export JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64
export LD_LIBRARY_PATH=$JAVA_HOME/lib:$JAVA_HOME/lib/server${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}
exec /path/to/your/ide "$@"

After relaunching the IDE through this wrapper, BrowserComponent instantiation succeeds in the Simulator. Any JDK from 11 through 25 that’s supported for running the Simulator works — the important part is that LD_LIBRARY_PATH resolves to that JDK’s lib and lib/server directories so the bundled libjcef.so finds a compatible libjawt/libjvm pair.

If BrowserComponent instantiation fails on Linux, log the environment with CN.getProperty("java.home", "<unset>"), CN.getProperty("JAVA_HOME", "<unset>") and CN.getProperty("LD_LIBRARY_PATH", "<unset>"). An <unset> value for LD_LIBRARY_PATH while the IDE was launched from a desktop shortcut is the typical fingerprint of this problem — desktop launchers don’t source your shell profile.
This issue doesn’t affect packaged native applications, only the desktop Simulator running on Linux.

8.28.2. BrowserComponent hierarchy

When Codename One packages applications into native apps it hides a lot of details to make the process simpler. One of the things hidden is the fact that you aren’t dealing with a JAR anymore, so getResource/getResourceAsStream are problematic…​ Both of these APIs support hierarchies and a concept of package relativity both of which might not be supported on all OSes.

Codename One has its own getResourceAsSteam in the Display class and that works fine, but it requires that all files be in the src root directory.

That’s why recommend that you place files inside res files. A resource file allows you to add arbitrary data files and you can have as many resource files as you need.

For web developers this isn’t enough since hierarchies are used often to represent the various dependencies, this means that many links & references are relative. To work with such hierarchies place all your resources in a hierarchy under the HTML package in the project source directory (src/html). The build server will tar the entire content of that package and add an html.tar file into the native package. This tar is seamlessly extracted on the device when you actually need the resources and with new application versions (not on every launch). Assuming the resources are under the HTML root package they can be displayed with code like this:

try {
    browserComponent.setURLHierarchy("/htmlFile.html");
} catch(IOException err) {
    /* omitted */
}

Notice that the path is relative to the HTML directory and starts with / but inside the HTML files you should use relative (not absolute) paths.

Also notice that an IOException can be thrown due to the process of untarring. Its unlikely to happen but is entirely possible.

8.28.3. NavigationCallback

At the core of the BrowserComponent you have the BrowserNavigationCallback. It might not seem like the most important interface within the browser but it’s the "glue" that allows the JavaScript code to communicate back into the Java layer.

You can bind a BrowserNavigationCallback by invoking setBrowserNavigationCallback on the BrowserComponent. At that point with every navigation within the browser the callback will get invoked.

The shouldNavigate method from the BrowserNavigationCallback is invoked in a native thread and NOT ON THE EDT!
it’s crucial that this method returns and that it won’t do any changes on the UI.

The shouldNavigate indicates to the native code whether navigation should proceed or not. For example: if a user clicks a specific link you might choose to do something in the Java code so you can return false and block the navigation. You can invoke callSerially to do the actual task in the Java side:

Form hi = new Form("BrowserComponent", new BorderLayout());
BrowserComponent bc = new BrowserComponent();
bc.setPage( "<html lang=\"en\">\n" +
            "    <head>\n" +
            "        <meta charset=\"utf-8\">\n" +
            "        <script>\n" +
            "          function  fnc(message) {\n" +
            "         document.write(message);\n" +
            "            };\n" +
            "        </script>\n" +
            "    </head>\n" +
            "    <body >\n" +
            "        <p><a href=\"http://click\">Demo</a></p>\n" +
            "    </body>\n" +
            "</html>", null);
hi.add(BorderLayout.CENTER, bc);
bc.setBrowserNavigationCallback((url) -> {
    if(url.startsWith("http://click")) {
        Display.getInstance().callSerially(() -> bc.execute("fnc('<p>You clicked!</p>')"));
        return false;
    }
    return true;
});
Before the link is clicked for the "shouldNavigate" call
Figure 127. Before the link is clicked for the "shouldNavigate" call
After the link is clicked for the "shouldNavigate" call
Figure 128. After the link is clicked for the "shouldNavigate" call
The JavaScript Bridge is implemented on top of the BrowserNavigationCallback.

8.28.4. JavaScript

The JavaScript bridge is sometimes confused with the JavaScript Port. The JavaScript bridge allows you to communicate with JavaScript from Java (and vice versa). The JavaScript port allows you to compile the Codename One application into a JavaScript application that runs in a standard web browser without code changes (think GWT without source changes and with thread support).+ You discuss the JavaScript port further later in the guide.

Use the BrowserComponent API to interact with JavaScript. It replaces the deprecated com.codename1.javascript package.

What was wrong with the old API

The old API provided a synchronous wrapper around an inherently asynchronous process, and made extensive use of invokeAndBlock() underneath the covers. This resulted in a nice API with high-level abstractions that played with a synchronous programming model, but it came with a price-tag in performance, complexity, and predictability. Let’s take a simple example, getting a reference to the "window" object:

JSObject window = (JSObject)ctx.get("window");

This code looks harmless enough, but this is actually expensive. It issues a command to the BrowserComponent, and uses invokeAndBlock() to wait for the command to go through and send back a response. invokeAndBlock() is a magical tool that allows you to "block" without blocking the EDT, but it has its costs, and shouldn’t be overused. Most of the Codename One APIs that use invokeAndBlock() show this in their name. For example: Component.animateLayoutAndWait(). This provides you the expectation that this call could take some time, and helps to alert you to the underlying cost.

The problem with the ctx.get("window") call is that it looks the same as a call to Map.get(key). There’s no sign that this call is expensive and could take time. One call like this probably isn’t a big deal, but it doesn’t take long before you have dozens or even hundreds of calls like this littered throughout your codebase, and they can be hard to pick out.

The new API

The new API fully embraces the asynchronous nature of JavaScript. It uses callbacks instead of return values, and provides convenience wrappers with the appropriate "AndWait()" naming convention to allow for synchronous usage. Let’s look at a simple example:

In all the sample code below, you can assume that variables named bc represent an instance of BrowserComponent:
bc.execute(
    "callback.onSuccess(3+4)",
    res -> Log.p("The result was "+res.getInt())
);

This code should output "The result was 7" to the console. It’s fully asynchronous, so you can include this code anywhere without worrying about it "bogging down" your code. The full signature of this form of the execute() method is:

public void execute(String js, SuccessCallback<JSRef> callback)

The first parameter is a JavaScript expression. This JavaScript MUST call either callback.onSuccess(result) or callback.onError(message, errCode) at some point in order for your callback to be called.

The second parameter is your callback that’s executed from the JavaScript side, when callback.onSuccess(res) is called. The callback takes a single parameter of type JSRef which is a generic wrapper around a JavaScript variable. JSRef has accessors to retrieve the value as some primitive types. For example: getBoolean(), getDouble(), getInt(), toString(), and it provides some introspection through the getType() method.

It’s worth noting that the callback method can take a single parameter. If you need to pass many parameters, you may consider including them in a single string which you parse in your callback.
Synchronous wrappers

As mentioned before, the new API also provides an executeAndWait() wrapper for execute() that will work synchronously. It, as its name suggests, uses invokeAndBlock under the hood so as not to block the EDT while it’s waiting.

For example:

JSRef res = bc.executeAndWait("callback.onSuccess(3+4)");
Log.p("The result was "+res.getInt());

Prints The result was 7.

When using the andWait() variant, it’s critical that your JavaScript calls your callback method at some point - otherwise it will block indefinitely. Codename One provides variants of executeAndWait() that include a timeout in case you want to hedge against this possibility.
Multi-use callbacks

The callbacks you pass to execute() and executeAndWait() are single-use callbacks. You can’t, for example, store the callback variable on the JavaScript side for later use (for example: to respond to a button click event). If you need a "multi-use" callback, you should use the addJSCallback() method instead. Its usage looks identical to execute(), the difference is that the callback will live on after its first use. For example: Consider the following code:

bc.execute(
    "$('#somebutton').click(function(){callback.onSuccess('Button was clicked')})",
    res -> Log.p(res.toString())
);

The above example, assumes that jQuery is loaded in the webpage that you’re interacting with, and you’re adding a click handler to a button with ID "somebutton." The click handler calls your callback.

If you run this example, the first time the button is clicked, you’ll see "Button was clicked" printed to the console as expected. For example, the 2nd time, you’ll get an exception. This is because the callback passed to execute() is single-use.

You need to change this code to use the addJSCallback() method as follows:

bc.addJSCallback(
    "$('#somebutton').click(function(){callback.onSuccess('Button was clicked')})",
    res -> Log.p(res.toString())
);

Now it will work no matter how many times the button is clicked.

Passing parameters to JavaScript

Often, the JavaScript expressions that you execute will include parameters from your Java code. Escaping these parameters is tricky at worst, and annoying at best. For example: If you’re passing a string, you need to make sure that it escapes quotes and new lines or it will cause the JavaScript to have a syntax error. Codename One provides variants of execute() and addJSCallback() that allow you to pass your parameters and have them automatically escaped.

For example, suppose you want to pass a string with text to set in a textarea within the webpage. You can do something like:

bc.execute(
    "jQuery('#bio').text(${0}); jQuery('#age').text(${1})",
    new Object[]{
       "A multi-line\n string with \"quotes\"",
       27
    }
);

The gist is that you embed placeholders in the JavaScript expression that are replaced by the corresponding entry in an array of parameters. The ${0} placeholder is replaced by the first item in the parameters array, the ${1} placeholder is replaced by the 2nd, etc.

Proxy objects

The new API also includes a JSProxy class that encapsulates a JavaScript object simplify the getting and setting of properties on JavaScript objects - and the calling of their methods. It provides essentially three core methods, along with many variants of each to allow for async or synchronous usages, parameters, and timeouts.

For example: You might want to create a proxy for the window.location object so that you can access its properties more from Java:

JSProxy location = bc.createJSProxy("window.location");

Then you can retrieve its properties using the get() method:

location.get("href", res -> Log.p("location.href="+res));

Or synchronously:

JSRef href = location.getAndWait("href");
Log.p("location.href="+href);

You can also set its properties:

location.set("href", "https://www.google.com");

And call its methods:

location.call("replace", new Object[]{"https://www.google.com"},
    res -> Log.p("Return value was "+res)
);
Legacy JSObject support

This section describes the now deprecated JSObject approach. It’s here for reference by developers working with older code. Use the new API when starting a new project.

BrowserComponent can communicate with the HTML code using JavaScript calls. For example: you can create HTML like this:

Form hi = new Form("BrowserComponent", new BorderLayout());
BrowserComponent bc = new BrowserComponent();
bc.setPage( "<html lang=\"en\">\n" +
            "    <head>\n" +
            "        <meta charset=\"utf-8\">\n" +
            "        <script>\n" +
            "          function  fnc(message) {\n" +
            "         document.write(message);\n" +
            "            };\n" +
            "        </script>\n" +
            "    </head>\n" +
            "    <body >\n" +
            "        <p>Demo</p>\n" +
            "    </body>\n" +
            "</html>", null);
TextField tf = new TextField();
hi.add(BorderLayout.CENTER, bc).
        add(BorderLayout.SOUTH, tf);
bc.addWebEventListener("onLoad", (e) ->  bc.execute("fnc('<p>Hello World</p>')"));
tf.addActionListener((e) -> bc.execute("fnc('<p>" + tf.getText() +"</p>')"));
hi.show();
JavaScript code was invoked to append text into the browser image above
Figure 129. JavaScript code was invoked to append text into the browser image above
Notice that opening an alert in an embedded native browser might not work

You use the execute method above to execute custom JavaScript code. You also have an executeAndReturnString method that allows you to receive a response value from the JavaScript side.

Coupled with shouldNavigate you can effectively do everything which is what the JavaScript Bridge tries to do.

The JavaScript bridge

While it’s possible to build everything on top of execute and shouldNavigate, both of these methods have their limits. That’s why Codename One introduced the JavaScript package, it allows you to communicate with JavaScript using intuitive code/syntax.

The JavascriptContext class lays the foundation by enabling you to call JavaScript code directly from Java. It provides automatic type conversion between Java and JavaScript types as follows:

Table 4. Java to JavaScript
Java TypeJavaScript Type

String

String

Double/Integer/Float/Long

Number

Boolean

Boolean

JSObject

Object

null

null

Other

Not Allowed

Table 5. JavaScript to Java
JavaScript TypeJava Type

String

String

Number

Double

Boolean

Boolean

Object

JSObject

Function

JSObject

Array

JSObject

null

null

undefined

null

This conversion table is more verbose than necessary, since JavaScript functions and arrays are, in fact Objects themselves, so those rows are redundant. All JavaScript objects are converted to JSObject.

You can access JavaScript variables from the context by using code like this:

Form hi = new Form("BrowserComponent", new BorderLayout());
BrowserComponent bc = new BrowserComponent();
bc.setPage( "<html lang=\"en\">\n" +
            "    <head>\n" +
            "        <meta charset=\"utf-8\">\n" +
            "    </head>\n" +
            "    <body >\n" +
            "        <p>This will appear twice...</p>\n" +
            "    </body>\n" +
            "</html>", null);
hi.add(BorderLayout.CENTER, bc);
bc.addWebEventListener("onLoad", (e) -> {
    // Create a JavaScript context for this BrowserComponent
    JavascriptContext ctx = new JavascriptContext(bc);

    String pageContent = (String)ctx.get("document.body.innerHTML");
    hi.add(BorderLayout.SOUTH, pageContent);
    hi.revalidate();
});
hi.show();
The contents were copied from the DOM and placed in the south position of the form
Figure 130. The contents were copied from the DOM and placed in the south position of the form

Notice that when you work with numeric values or anything related to the types mentioned above your code must be aware of the typing. For example: in this case the type is Double and not String:

Double outerWidth = (Double)ctx.get("window.outerWidth");

You can also query the context for objects and change their value for example:

Form hi = new Form("BrowserComponent", new BorderLayout());
BrowserComponent bc = new BrowserComponent();
bc.setPage( "<html lang=\"en\">\n" +
            "    <head>\n" +
            "        <meta charset=\"utf-8\">\n" +
            "    </head>\n" +
            "    <body >\n" +
            "        <p>Please Wait...</p>\n" +
            "    </body>\n" +
            "</html>", null);
hi.add(BorderLayout.CENTER, bc);
bc.addWebEventListener("onLoad", new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        // the destination fires onLoad too, so stop listening before navigating
        bc.removeWebEventListener("onLoad", this);

        // Create a JavaScript context for this BrowserComponent
        JavascriptContext ctx = new JavascriptContext(bc);

        JSObject jo = (JSObject)ctx.get("window");
        jo.set("location", "https://www.codenameone.com/");
    }
});
hi.show();

This code effectively navigates to the Codename One home page by fetching the DOM’s window object and setting its location property to https://www.codenameone.com/.

8.28.5. Cordova/PhoneGap integration

PhoneGap was one of the first web app packager tools in the market: a tool that’s effectively a browser component within a native wrapper coupled with native access APIs, and Cordova is the open source extension of this popular project.

Codename One supports embedding PhoneGap/Cordova applications directly into Codename One applications. This is easy to do with the BrowserComponent and JavaScript integration. The main aspect that this integration requires is support for Cordova plugins & its JavaScript APIs.

The effort to integrate Cordova/PhoneGap support into Codename One is handled within an open-source GitHub project here. The chief benefits of picking Codename One rather than using Cordova directly are:

  • Build Cloud

  • Better Native Code Support

  • Better Protection Of IP

  • IDE Integration Java - JavaScript - HTML

  • Easy, doesn’t Require A Mac, Automates Certificates/Signing

  • Migration To Java

This is discussed further in the original announcement.

8.29. Text editors

RichTextArea and CodeEditor are introduced here as components, but editing is broad enough to have its own chapter. See Chapter 10, Rich Text and Code Editing for rich HTML, syntax highlighting, completion, diagnostics, touch and desktop selection, scrolling, bidirectional text, input methods, backend selection, and the port-level TextInputClient contract.

8.30. AutoCompleteTextField

The AutoCompleteTextField allows you to write text into a text field and select a completion entry from the list in a similar way to a search engine.

This is easy to incorporate into your code, replace your usage of TextField with AutoCompleteTextField and define the data that the autocomplete should work from. A default implementation accepts a String array or a ListModel for completion strings, this can work well for a "small" set of thousands (or tens of thousands) of entries.

For example: This is a trivial use case that can work well for smaller sample sizes:

Form hi = new Form("Auto Complete", new BoxLayout(BoxLayout.Y_AXIS));
AutoCompleteTextField ac = new AutoCompleteTextField("Short", "Shock", "Sholder", "Shrek");
ac.setMinimumElementsShownInPopup(5);
hi.add(ac);
Autocomplete Text Field
Figure 131. Autocomplete Text Field

For example, if you wish to query a database or a web service you will need to derive the class and perform more advanced filtering by overriding the filter method:

  Form hi = new Form("Autocomplete", new BoxLayout(BoxLayout.Y_AXIS));
public void showForm() {
  final DefaultListModel<String> options = new DefaultListModel<>();
  AutoCompleteTextField ac = new AutoCompleteTextField(options) {
      @Override
      protected boolean filter(String text) {
          if(text.length() == 0) {
              // an emptied field must not keep showing the last query's matches
              options.removeAll();
              return false;
          }
          String[] l = searchLocations(text);
          if(!text.equals(getText())) {
              // the wait above pumps the EDT, so the field may have moved on
              // and a newer query may already have filled the model
              return false;
          }
          if(l == null || l.length == 0) {
              // otherwise the popup keeps showing the previous query's matches
              options.removeAll();
              return false;
          }

          options.removeAll();
          for(String s : l) {
              options.addItem(s);
          }
          return true;
      }

  };
  ac.setMinimumElementsShownInPopup(5);
  hi.add(ac);
  hi.add(new SpanLabel("This demo requires a valid google API key to be set below "
           + "you can get this key for the webservice (not the native key) by following the instructions here: "
           + "https://developers.google.com/places/web-service/get-api-key"));
  hi.add(apiKey);
  hi.getToolbar().addCommandToRightBar("Get Key", null, e -> Display.getInstance().execute("https://developers.google.com/places/web-service/get-api-key"));
  hi.show();
}

TextField apiKey = new TextField();

String[] searchLocations(String text) {
    try {
        if(text.length() > 0) {
            ConnectionRequest r = new ConnectionRequest();
            r.setPost(false);
            r.setUrl("https://maps.googleapis.com/maps/api/place/autocomplete/json");
            r.addArgument("key", apiKey.getText());
            r.addArgument("input", text);
            NetworkManager.getInstance().addToQueueAndWait(r);
            Map<String,Object> result = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(r.getResponseData()), "UTF-8"));
            String[] res = Result.fromContent(result).getAsStringArray("//description");
            return res;
        }
    } catch(Exception err) {
        Log.e(err);
    }
    return null;
}
Autocomplete Text Field with a webservice
Figure 132. Autocomplete Text Field with a webservice

8.30.1. Using images in AutoCompleteTextField

One question that comes up frequently is "How do you customize the results of the auto complete field"?

This sounds difficult to most people as you can work with Strings so how do you represent more data or format the date correctly?

The answer is actually pretty simple, you still need to work with Strings because autocomplete is fundamentally a text field. For example, that doesn’t preclude your custom renderer from fetching data that might be placed in a different location and associated with the result.

The following source code presents an autocomplete text field with images in the completion popup and two lines for every entry:

final String[] characters = { "Tyrion Lannister", "Jaime Lannister", "Cersei Lannister", "Daenerys Targaryen",
    "Jon Snow", "Petyr Baelish", "Jorah Mormont", "Sansa Stark", "Arya Stark", "Theon Greyjoy"
    // snipped the rest for clarity
};

Form current = new Form("AutoComplete", BoxLayout.y());

AutoCompleteTextField ac = new AutoCompleteTextField(characters);

final int size = Display.getInstance().convertToPixels(7);
final EncodedImage placeholder = EncodedImage.createFromImage(Image.createImage(size, size, 0xffcccccc), true);

final String[] actors = { "Peter Dinklage", "Nikolaj Coster-Waldau", "Lena Headey"}; (1)
final Image[] pictures = {
    URLImage.createToStorage(placeholder, "tyrion","http://i.lv3.hbo.com/assets/images/series/game-of-thrones/character/s5/tyrion-lannister-512x512.jpg"),
    URLImage.createToStorage(placeholder, "jaime","http://i.lv3.hbo.com/assets/images/series/game-of-thrones/character/s5/jamie-lannister-512x512.jpg"),
    URLImage.createToStorage(placeholder, "cersei","http://i.lv3.hbo.com/assets/images/series/game-of-thrones/character/s5/cersei-lannister-512x512.jpg")
};

ac.setCompletionRenderer(new ListCellRenderer() {
    private final Label focus = new Label(); (2)
    private final Label line1 = new Label(characters[0]);
    private final Label line2 = new Label(actors[0]);
    private final Label icon = new Label(pictures[0]);
    private final Container selection = BorderLayout.center(
            BoxLayout.encloseY(line1, line2)).add(BorderLayout.EAST, icon);

    @Override
    public Component getListCellRendererComponent(com.codename1.ui.List list, Object value, int index, boolean isSelected) {
        for(int iter = 0 ; iter < characters.length ; iter++) {
            if(characters[iter].equals(value)) {
                line1.setText(characters[iter]);
                if(actors.length > iter) {
                    line2.setText(actors[iter]);
                    icon.setIcon(pictures[iter]);
                } else {
                    line2.setText(""); (3)
                    icon.setIcon(placeholder);
                }
                break;
            }
        }
        return selection;
    }

    @Override
    public Component getListFocusComponent(com.codename1.ui.List list) {
        return focus;
    }
});
current.add(ac);

current.show();
1you have duplicate arrays that are partial for clarity. This is a separate list of data element but you can fetch the more data from anywhere
2You create the renderer UI instantly in the fields with the helper methods for wrapping elements which is pretty cool & terse
3In a renderer it’s important to always set the value if you don’t have a value in place
Auto complete with images
Figure 133. Auto complete with images

8.31. Picker

Picker occupies the limbo between native widget and lightweight widget. Picker is more like TextField/TextArea in the sense that it’s a Codename One widget that calls the native code during editing.

The reasoning for this is the highly native UX and functionality related to this widget type which should be obvious from the screenshots below.

At this time there are 4 types of pickers:

  • Time

  • Date & Time

  • Date

  • Strings

If a platform doesn’t support native pickers an internal fallback implementation is used. This is the implementation you always use in the simulator so assume different behavior when building for the device.

While Android supports Date, Time native pickers it doesn’t support the Date & Time native picker UX and will fall back in that case.

The sample below includes al picker types:

Form hi = new Form("Picker", new BoxLayout(BoxLayout.Y_AXIS));
Picker datePicker = new Picker();
datePicker.setType(Display.PICKER_TYPE_DATE);
Picker dateTimePicker = new Picker();
dateTimePicker.setType(Display.PICKER_TYPE_DATE_AND_TIME);
Picker timePicker = new Picker();
timePicker.setType(Display.PICKER_TYPE_TIME);
Picker stringPicker = new Picker();
stringPicker.setType(Display.PICKER_TYPE_STRINGS);
Picker durationPicker = new Picker();
durationPicker.setType(Display.PICKER_TYPE_DURATION);
Picker minuteDurationPicker = new Picker();
minuteDurationPicker.setType(Display.PICKER_TYPE_DURATION_MINUTES);
Picker hourDurationPicker = new Picker();
hourDurationPicker.setType(Display.PICKER_TYPE_DURATION_HOURS);

datePicker.setDate(new Date());
dateTimePicker.setDate(new Date());
timePicker.setTime(10 * 60); // 10:00AM = Minutes since midnight
stringPicker.setStrings("A Game of Thrones", "A Clash Of Kings", "A Storm Of Swords", "A Feast For Crows",
        "A Dance With Dragons", "The Winds of Winter", "A Dream of Spring");
stringPicker.setSelectedString("A Game of Thrones");

hi.add(datePicker).add(dateTimePicker).add(timePicker)
  .add(stringPicker).add(durationPicker)
  .add(minuteDurationPicker).add(hourDurationPicker);
hi.show();
The various picker components
Figure 134. The various picker components
The date & time picker on the simulator
Figure 135. The date & time picker on the simulator
The date picker component on the Android device
Figure 136. The date picker component on the Android device
Date and time picker on Android. Notice it didn’t use a built-in widget since there is none
Figure 137. Date & time picker on Android. Notice it didn’t use a built-in widget since there is none
String picker on the native Android device
Figure 138. String picker on the native Android device
Time picker on the Android device
Figure 139. Time picker on the Android device
Duration picker on Android device
Figure 140. Duration picker on Android device
Hours Duration picker on Android device
Figure 141. Hours Duration picker on Android device
Minutes Duration picker on Android device
Figure 142. Minutes Duration picker on Android device

The text displayed by the picker on selection is generated automatically by the updateValue() method. You can override it to display a custom formatted value and call setText(String) with the correct display string.

A common use case is to format date values based on a specific appearance and Picker has built-in support for a custom display formatter. Just use the setFormatter(SimpleDateFormat) method and set the appearance for the field.

When using lightweight picker mode (setUseLightweightPopup(true)), you can add custom quick-action buttons to the popup. This is useful for actions like setting the date to "Today" or "+7 Days" without scrolling the wheels manually:

Picker picker = new Picker();
picker.setType(Display.PICKER_TYPE_DATE);
picker.setUseLightweightPopup(true);
picker.setDate(new Date());

picker.addLightweightPopupButton("Today", () -> picker.setDate(new Date()));

picker.addLightweightPopupButton("+7 Days", () -> {
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DAY_OF_MONTH, 7);
    picker.setDate(cal.getTime());
}, Picker.LightweightPopupButtonPlacement.BELOW_SPINNER);
Form hi = new Form("Picker", new BoxLayout(BoxLayout.Y_AXIS));
hi.add(picker);
hi.show();

Button placement options are:

  • Picker.LightweightPopupButtonPlacement.BETWEEN_CANCEL_AND_DONE (default)

  • Picker.LightweightPopupButtonPlacement.ABOVE_SPINNER

  • Picker.LightweightPopupButtonPlacement.BELOW_SPINNER

8.32. SwipeableContainer

The SwipeableContainer allows you to place a component such as a MultiButton on top of more "options" that can be exposed by swiping the component to the side.

This swipe gesture is commonly used in touch interfaces to expose features such as delete, edit etc. It’s trivial to use this component by determining the components placed on top and bottom (the revealed component):

SwipeableContainer swip = new SwipeableContainer(bottom, top);

You can combine some demos above including the Slider stars demo to rank GRRM’s books in an interactive way:

Form hi = new Form("Swipe", new BoxLayout(BoxLayout.Y_AXIS));
hi.add(createRankWidget("A Game of Thrones", "1996")).
    add(createRankWidget("A Clash Of Kings", "1998")).
    add(createRankWidget("A Storm Of Swords", "2000")).
    add(createRankWidget("A Feast For Crows", "2005")).
    add(createRankWidget("A Dance With Dragons", "2011")).
    add(createRankWidget("The Winds of Winter", "TBD")).
    add(createRankWidget("A Dream of Spring", "TBD"));
hi.show();
public SwipeableContainer createRankWidget(String title, String year) {
    MultiButton button = new MultiButton(title);
    button.setTextLine2(year);
    return new SwipeableContainer(FlowLayout.encloseCenterMiddle(createStarRankSlider()),
            button);
}
SwipeableContainer showing a common use case of ranking on swipe
Figure 143. SwipeableContainer showing a common use case of ranking on swipe

8.33. EmbeddedContainer

EmbeddedContainer solves a problem that exists within the GUI builder and the class makes no sense outside of the context of the GUI builder. The necessity for EmbeddedContainer came about due to iPhone inspired designs that relied on tabs (iPhone style tabs at the bottom of the screen) where different features of the application are within a different tab.

This didn’t mesh well with the GUI builder navigation logic and so it needed a rethink. The aim was to reuse GUI as much as possible while still enjoying the advantage of navigation being managed for you.

Android does this with Activities and the iPhone itself has a view controller, both approaches are problematic for Codename One. The problem is that you have what’s effectively two incompatible hierarchies to mix and match.

The Component/Container hierarchy is powerful enough to represent such a UI but you needed a "marker" to show to the UIBuilder where a "root" component exists so navigation occurs within the given "root." Here EmbeddedContainer comes into play, its a simple container that can contain another GUI from the GUI builder. Nothing else. You can place it in any form of UI and effectively have the UI change appropriately and navigation would default to "sensible values."

Navigation replaces the content of the embedded container; it finds the embedded container based on the component that broadcast the event. If you want to navigate manually use the showContainer() method which accepts a component, you can give any component that’s under the EmbeddedContainer you want to replace and Codename One will be smart enough to replace that component.

The nice part about using the EmbeddedContainer is that the resulting UI can be refactored to provide a more traditional form based UI without duplicating effort and can be adapted to a more tablet oriented UI (with a sidebar) again without much effort.

8.34. MapComponent

The MapComponent uses a somewhat outdated tiling API which isn’t as rich as modern native maps. Recommend using the GoogleMap’s Native cn1lib to integrate native mapping functionality into the Codename One app.

The MapComponent uses the OpenStreetMap webservice by default to display a navigatable map.

The code was contributed by Roman Kamyk and was originally used for a LWUIT application.

Map Component
Figure 144. Map Component

The screenshot above was produced using the following code:

Form map = new Form("Map");
map.setLayout(new BorderLayout());
map.setScrollable(false);
final MapComponent mc = new MapComponent();

try {
   //get the current location from the Location API
   Location loc = LocationManager.getLocationManager().getCurrentLocation();

   // null until the device has a fix, so the map opens without the marker
   if(loc != null) {
       Coord lastLocation = new Coord(loc.getLatitude(), loc.getLongtitude());
       // a material icon rather than an asset you would have to add
       Image i = FontImage.createMaterial(FontImage.MATERIAL_PLACE, "Label", 4.0f);
       PointsLayer pl = new PointsLayer();
       pl.setPointIcon(i);
       PointLayer p = new PointLayer(lastLocation, "You Are Here", i);
       p.setDisplayName(true);
       mc.addLayer(pl);
       pl.addPoint(p);
   }
} catch (IOException ex) {
   ex.printStackTrace();
}
mc.zoomToLayers();

map.addComponent(BorderLayout.CENTER, mc);
map.show();

The example below shows how to integrate the MapComponent with the Google Location API. Make sure to get your secret API key from the Google Location data API at: https://developers.google.com/maps/documentation/places/

MapComponent with Google Location API
Figure 145. MapComponent with Google Location API

8.35. Chart Component

The charts package enables Codename One developers to add charts and visualizations to their apps without having to include external libraries or embedding web views. You also wanted to harness the new features in the graphics pipeline to maximize performance.

8.35.1. Device support

Since the charts package makes use of 2D transformations and shapes, it requires some graphics features that aren’t yet available on all platforms. The following platforms are supported:

  1. Simulator

  2. Android

  3. iOS

8.35.2. Features

  1. Built-in support for many common types of charts including bar charts, line charts, stacked charts, scatter charts, pie charts and more.

  2. Pinch Zoom - The ChartComponent class includes optional pinch zoom support.

  3. Panning Support - The ChartComponent class includes optional support for panning.

8.35.3. Chart types

The com.codename1.charts package includes models and renderers for many different types of charts. It’s also extensible so that you can add your own chart types if required. The following screenshots show a small sampling of the types of charts that can be created.

Line Charts
Figure 146. Line Charts
Cubic Line Charts
Figure 147. Cubic Line Charts
Bar Charts
Figure 148. Bar Charts
Stacked Bar Charts
Figure 149. Stacked Bar Charts
Range Bar Charts
Figure 150. Range Bar Charts
Pie Charts
Figure 151. Pie Charts
Doughnut Charts
Figure 152. Doughnut Charts
Scatter Charts
Figure 153. Scatter Charts
Dial Charts
Figure 154. Dial Charts
Combined Charts
Figure 155. Combined Charts
Bubble Charts
Figure 156. Bubble Charts
Time Charts
Figure 157. Time Charts
The above screenshots were taken from the ChartsDemo app. You can start playing with this app by checking it out from your git repository.

8.35.4. How to create a chart

Adding a chart to your app involves four steps:

  1. Build the model. You can construct a model (aka data set) for the chart using one of the existing model classes in the com.codename1.charts.models package. Essentially, this is where you add the data that you want to display.

  2. Set up a renderer. You can create a renderer for your chart using one of the existing renderer classes in the com.codename1.charts.renderers package. The renderer allows you to specify how the chart should look. For example: the colors, fonts, styles, to use.

  3. Create the Chart View. Use one of the existing view classes in the com.codename1.charts.views package.

  4. Create a ChartComponent. To add your chart to the UI, you need to wrap it in a ChartComponent object.

You can check out the ChartsDemo app for specific examples, but here is a high-level view of some code that creates a Pie Chart:

/**
 * Creates a renderer for the specified colors.
 */
private DefaultRenderer buildCategoryRenderer(int[] colors) {
    DefaultRenderer renderer = new DefaultRenderer();
    renderer.setLabelsTextSize(15);
    renderer.setLegendTextSize(15);
    renderer.setMargins(new int[]{20, 30, 15, 0});
    for (int color : colors) {
        SimpleSeriesRenderer r = new SimpleSeriesRenderer();
        r.setColor(color);
        renderer.addSeriesRenderer(r);
    }
    return renderer;
}

/**
 * Builds a category series using the provided values.
 *
 * @param titles the series titles
 * @param values the values
 * @return the category series
 */
protected CategorySeries buildCategoryDataset(String title, double[] values) {
    CategorySeries series = new CategorySeries(title);
    int k = 0;
    for (double value : values) {
        series.add("Project " + ++k, value);
    }

    return series;
}

public Form createPieChartForm() {

    // Generate the values
    double[] values = new double[]{12, 14, 11, 10, 19};

    // Set up the renderer
    int[] colors = new int[]{ColorUtil.BLUE, ColorUtil.GREEN, ColorUtil.MAGENTA, ColorUtil.YELLOW, ColorUtil.CYAN};
    DefaultRenderer renderer = buildCategoryRenderer(colors);
    renderer.setZoomButtonsVisible(true);
    renderer.setZoomEnabled(true);
    renderer.setChartTitleTextSize(20);
    renderer.setDisplayValues(true);
    renderer.setShowLabels(true);
    SimpleSeriesRenderer r = renderer.getSeriesRendererAt(0);
    r.setGradientEnabled(true);
    r.setGradientStart(0, ColorUtil.BLUE);
    r.setGradientStop(0, ColorUtil.GREEN);
    r.setHighlighted(true);

    // Create the chart ... pass the values and renderer to the chart object.
    PieChart chart = new PieChart(buildCategoryDataset("Project budget", values), renderer);

    // Wrap the chart in a Component so we can add it to a form
    ChartComponent c = new ChartComponent(chart);

    // Create a form and show it.
    Form f = new Form("Budget");
    f.setLayout(new BorderLayout());
    f.addComponent(BorderLayout.CENTER, c);
    return f;

}

8.35.5. Animating a change in the data

Replacing a series' numbers and repainting redraws the chart in one jump. The com.codename1.charts.transitions package tweens the change instead: pick the transition that matches the model — XYSeriesTransition for one XYSeries, XYMultiSeriesTransition for a whole XYMultipleSeriesDataset, XYValueSeriesTransition for an XYValueSeries — and write the new numbers into its buffer rather than into the series itself.

XYSeriesTransition transition = new XYSeriesTransition(chart, readings);
transition.setEasing(SeriesTransition.EASING_IN_OUT);
transition.setDuration(600);

// The buffer starts out empty. Write the NEW shape of the series into
// it -- every point, not only the ones that changed -- because the
// buffer is what the series is tweened towards.
XYSeries next = transition.getBuffer();
next.add(0, 12);
next.add(1, 19);
next.add(2, 7);

transition.animateChart();

The buffer holds the shape you want to end up with, so put every point in it and not only the ones that moved: a point the buffer doesn’t mention keeps whatever the series already had, while a point the series doesn’t have yet grows in from zero. animateChart() registers the transition with the chart’s top-level container and drives it to that shape over setDuration(…​) milliseconds, easing as setEasing(…​) says — EASING_LINEAR, EASING_IN, EASING_OUT or EASING_IN_OUT. The buffer is drained when the animation finishes, so the same transition can be used again for the next update.

updateChart() applies the buffer the same way and repaints at once, with no animation, which is what you want for a change the user didn’t trigger.

XYSeriesTransition transition = new XYSeriesTransition(chart, readings);
transition.getBuffer().add(3, 22);
transition.updateChart();

8.36. Calendar

The Calendar class allows you to display a traditional calendar picker and optionally highlight days in various ways.

Prefer the Picker UI over the calendar for picking a date. It looks better on the devices.

Simple usage of the Calendar class looks something like this:

Form hi = new Form("Calendar", new BorderLayout());
Calendar cld = new Calendar();
cld.addActionListener((e) -> Log.p("You picked: " + new Date(cld.getSelectedDay())));
hi.add(BorderLayout.CENTER, cld);
hi.show();
The Calendar component
Figure 158. The Calendar component

8.37. ToastBar

The ToastBar class allows you to display none-obtrusive status messages to the user at the bottom of the screen. This is useful for such things as informing the user of a long-running task (like downloading a file in the background), or popping up an error message that doesn’t require a response from the user.

Simple usage of the ToastBar class looks something like this:

Status status = ToastBar.getInstance().createStatus();
status.setMessage("Downloading your file...");
status.show();

//  ... Later on when download completes
status.clear();
ToastBar with message
Figure 159. ToastBar with message

You can show a progress indicator in the ToastBar like this:

Status status = ToastBar.getInstance().createStatus();
status.setMessage("Hello world");
status.setShowProgressIndicator(true);
status.show();
Status Message with Progress Bar
Figure 160. Status Message with Progress Bar

You can automatically clear a status message/progress after a timeout using the setExpires method as such:

Status status = ToastBar.getInstance().createStatus();
status.setMessage("Hello world");
status.setExpires(3000);  // only show the status for 3 seconds, then have it automatically clear
status.show();

You can also delay the showing of the status message using showDelayed as such:

Status status = ToastBar.getInstance().createStatus();
status.setMessage("Hello world");
status.showDelayed(300); // Wait 300 ms to show the status

// ... Some time later, clear the status... This may be before it shows at all
status.clear();
ToastBar with a multiline message
Figure 161. ToastBar with a multiline message

8.37.1. Actions in ToastBar

Probably the best usage example for actions in toast is in the gmail style undo. If you aren’t a gmail user then the gmail app essentially never prompts for confirmation!

It does whatever you ask and pops a "toast message" with an option to undo. If you clicked by mistake you have 3-4 seconds to take that back.

This simple example shows you how you can undo any addition to the UI in a similar way to gmail:

Form hi = new Form("Undo", BoxLayout.y());
Button add = new Button("Add");

add.addActionListener(e -> {
    Label l = new Label("Added this");
    hi.add(l);
    hi.revalidate();
    ToastBar.showMessage("Added, click here to undo...", FontImage.MATERIAL_UNDO,
            ee -> {
                l.remove();
                hi.revalidate();
            });
});
hi.add(add);
hi.show();

8.38. SignatureComponent

The SignatureComponent provides a widget that allows users to draw their signature in the app.

Simple usage of the SignatureComponent class looks like:

Form hi = new Form("Signature Component");
hi.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
hi.add("Enter Your Name:");
hi.add(new TextField());
hi.add("Signature:");
SignatureComponent sig = new SignatureComponent();
sig.addActionListener((evt)-> {
    System.out.println("The signature was changed");
    Image img = sig.getSignatureImage();
    // Now we can do whatever we want with the image of this signature.
});
hi.addComponent(sig);
hi.show();
The Signature Component
Figure 162. The signature Component

8.39. Accordion

The Accordion displays collapsible content panels.

Simple usage of the Accordion class looks like:

Form f = new Form("Accordion", new BoxLayout(BoxLayout.Y_AXIS));
f.setScrollableY(true);
Accordion accr = new Accordion();
accr.addContent("Item1", new SpanLabel("The quick brown fox jumps over the lazy dog\n"
        + "The quick brown fox jumps over the lazy dog"));
accr.addContent("Item2", new SpanLabel("The quick brown fox jumps over the lazy dog\n"
        + "The quick brown fox jumps over the lazy dog\n "
        + "The quick brown fox jumps over the lazy dog\n "
        + "The quick brown fox jumps over the lazy dog\n "
        + ""));

accr.addContent("Item3", BoxLayout.encloseY(new Label("Label"), new TextField(), new Button("Button"), new CheckBox("CheckBox")));

f.add(accr);
f.show();
The Accordion Component
Figure 163. The Accordion Component

8.40. Floating hint

FloatingHint wraps a text component with a special container that can animate the hint label into a title label when the text component is edited or has content within it:

Form hi = new Form("Floating Hint", BoxLayout.y());
TextField first = new TextField("", "First Field");
TextField second = new TextField("", "Second Field");
hi.add(new FloatingHint(first)).
        add(new FloatingHint(second)).
        add(new Button("Go"));
hi.show();
Floating hint
Figure 164. The hint floats on the field being edited and stays inside the one that isn’t

8.41. Floating Button

The material design floating action button is a powerful tool for promoting an action within your application.

FloatingActionButton is a round button that resides on top of the UI typically in the bottom right-hand side.
It has a drop shadow to distinguish it from the UI underneath and it can hide two or more actions under the surface. For example: you can create a simple single click button such as this:

FloatingActionButton fab = FloatingActionButton.createFAB(FontImage.MATERIAL_ADD);
fab.addActionListener(e -> ToastBar.showErrorMessage("Not implemented yet..."));
fab.bindFabToContainer(form.getContentPane());

Which will place a + sign button that will perform the action. Or you can create a nested action where a click on the button will produce a submenu for users to pick from for example:

FloatingActionButton fab = FloatingActionButton.createFAB(FontImage.MATERIAL_ADD);
fab.createSubFAB(FontImage.MATERIAL_PEOPLE, "");
fab.createSubFAB(FontImage.MATERIAL_IMPORT_CONTACTS, "");
fab.bindFabToContainer(form.getContentPane());
FloatingActionButton with submenu expanded
Figure 165. FloatingActionButton with submenu expanded

Those familiar with this widget know that there are many nuances to this UI that may be implemented/exposed in the future. The current API is intentionally simple and minimal for the common use cases, with the plan to refine it based on feedback.

8.41.1. Using floating Button as a badge

Floating buttons can also be used to badge an arbitrary component in the style popularized by iOS/macOS. A badge appears in the top right corner and includes special numeric details such as unread count..

The code below adds a simple badge to a chat button:

Form hi = new Form("Badge");

Button chat = new Button("Chat");
FontImage.setMaterialIcon(chat, FontImage.MATERIAL_CHAT, 7);

FloatingActionButton badge = FloatingActionButton.createBadge("33");
hi.add(badge.bindFabToContainer(chat, Component.RIGHT, Component.TOP));

TextField changeBadgeValue = new TextField("33");
changeBadgeValue.addDataChangedListener((i, ii) -> {
badge.setText(changeBadgeValue.getText());
badge.getParent().revalidate();
});
hi.add(changeBadgeValue);

hi.show();

The code above results in this, notice you can type into the text field to change the badge value:

Badge floating button in action
Figure 166. Badge floating button in action

8.42. SplitPane

The split pane component is a bit desktop specific but works reasonably well on devices. To get the image below you changed SalesDemo.java in the kitchen sink by changing this:

private Container encloseInMaximizableGrid(Component cmp1, Component cmp2) {
    GridLayout gl = new GridLayout(2, 1);
    Container grid = new Container(gl);
    gl.setHideZeroSized(true);

    grid.add(encloseInMaximize(grid, cmp1)).
            add(encloseInMaximize(grid, cmp2));
    return grid;
}

To:

private Container encloseInMaximizableGrid(Component cmp1, Component cmp2) {
    return new SplitPane(SplitPane.VERTICAL_SPLIT, cmp1, cmp2, "25%", "50%", "75%");
}
Split Pane in the Kitchen Sink Demo
Figure 167. Split Pane in the Kitchen Sink Demo

This is self-explanatory but "mostly." you have 5 arguments the first 3 make sense:

  • Split orientation

  • Components to split

The last 3 arguments seem weird but they also make sense once you understand them, they’re:

  • The least position of the split - 1/4 of available space

  • The default position of the split - middle of the screen

  • The most position of the split - 3/4 of available space

The units don’t have to be percentages they can be mm (millimeters) or px (pixels).

9. Component selector

The ComponentSelector class is a new class that brings the power of jQuery to Codename One. While it isn’t actually jQuery, it’s influenced by it. If you’re not familiar with jQuery, here is the 10 second intro.

jQuery is a JavaScript library, created by John Resig in 2006, that has become a staple of browser-based UI development. As of March 2017, over 70% of websites are using jQuery. The initial problem that jQuery solved was browser incompatibility issues. It provided a consistent API for most useful DOM methods so that the developer didn’t have to spend all their days and nights fighting with browser compatibility issues. In a way, it did for JavaScript, what Codename One does for mobile apps.

The other thing jQuery did was provide an elegant way to select and manipulate DOM elements (that is, HTML tags in a web page). It enabled developers to form sets of elements using a CSS-like syntax, and to operate on all elements of those sets, as if they were single elements, and they provided a fluent API to enable developers to chain multiple calls together, and delay onset of carpel tunnel for at least a few extra years.

With the new ComponentSelector class, you’ve adopted the following aspects of jQuery:

  1. CSS-like Selection Syntax - Support for a CSS-like syntax for "selecting" Components to be included in a set.

  2. Fluent API - The API is fluent, meaning you can chain multiple method calls together and reduce typing.

  3. Working on Sets - Methods of this class operate on sets of components as if they’re a single component. As you’ll see, this can be incredibly powerful.

  4. Effects - Support for common effects on components such as fadeIn(), fadeOut(), slideDown(), and slideUp().

9.1. Motivation by example

The following snippet creates a button, that, when pressed, will fade itself and all its sibling components out, and then fade them back in:

// ...

Button slideUp = $(new Button("Slide Up")) (1)
    .setIcon(FontImage.MATERIAL_EXPAND_LESS) (2)
    .addActionListener(e->{ (3)
        $(e) (4)
            .getParent() (5)
            .find(">*") (6)
            .slideUpAndWait(1000) (7)
            .slideDownAndWait(1000); (8)
    })
    .asComponent(Button.class); (9)
1- Creates a new Button and wraps it in a ComponentSelector so that you can use ComponentSelector’s fluent API to change the button.
2- Sets the icon on the button
3- Adds an action listener to the button
4- Wraps the source of the action event (which is the button) in a ComponentSelector so you can use fluent API.
5- Gets button’s parent component. (Actually it’s a set of components, size=1)
6- Gets all the direct children of the button’s parent container.
7- Hides all the children of the button’s parent (that is, the button and siblings) using a slide-up effect. Duration is 1000ms. Blocks until complete.
8- Shows the button and its siblings using a slide-down effect.
9- Returns the button itself to assign to the slideUp local variable.
For people like Shai who don’t like the jQuery $ syntax used for method names, you can or use the select() method as an alias for $().

Take a close look at that example, and imagine implementing that functionality the "old" way. It actually gets pretty hairy. That example should be enough to get you interested in using ComponentSelector.

Now look at some details of how it works and how to use it.

9.2. Selecting components

The first thing you’ll want to do with ComponentSelector, is to select the components that will be in your set. You can do this in many ways:

  1. You can use the CSS selector syntax. For example, $("Label, Button, #MyCalendar") = The set of all components on the current form with UIID=Label, or UIID=Button, or Name=MyCalendar.

  2. You can explicitly wrap one or more components. For example, $(myButton, myLabel, myCalendar) = A set with 3 components, myButton, myLabel, and myCalendar.

  3. You can change an existing set to create a new one. For example, $("Label").add("Button", true).add($("#MyCalendar")); = the same set formed in 1 above. (Labels, Buttons, and components with Name=MyCalendar)

9.2.1. Specifying the roots for queries

You can specify the roots for a query to limit the scope of the search. If you don’t provide a root, then the current form will be used as a root. If there is no current form yet, then a RuntimeException will be thrown. It’s always a good idea to provide a root if you’ve one.

For example, $(`Label, myContainer)` = The set of components with UIID="Label" inside the myContainer. This will scour the full subtree of myContainer for components that match the provided selector.

You can provide multiple roots as well. For example, $("Label", myContainer, anotherContainer) = The set of components with UIID="Label" inside either myContainer or anotherContainer.

You could also provide set of components, and by extension a ContainerSelector (since it implements java.util.Set<Component>) as the roots. For example, $("CalendarDay", $("Calendar")) = The set of all components with UIID "CalendarDay" inside containers with UIID=Calendar.

Finally, ComponentSelector provides a find() method that implicitly uses the current set as the roots. For example, $("Calendar").find("CalendarDay") is equivalent to $("CalendarDay", $("Calendar")).

9.2.2. Selector syntax

Until now the selector syntax has only been described as like CSS. It’s like CSS, but it differs where Codename One’s component model differs from the JavaScript DOM. Rather than a formal grammar, the examples below show what the syntax can express.

  1. $("Label") - The set of all components on the form with UIID "Label"

  2. $("#MyField") - The set of all components on the form with Name MyField.

  3. $(".some-tag") - The set of all components on the form with the tag "some-tag." (You’ll discuss tags below).

  4. $("Label#MyField") - The set of all components on the form with both UIID=Label and Name=MyField.

  5. $("Label#MyField.some-tag") - The set of all components on the form with UIID=Label, Name=MyField, and tag "some-tag."

  6. $("*") - The set of all components on the form.

  7. $(".some-tag.some-other-tag") - All components with both tags "some-tag" and "some-other-tag"

  8. $("#MyContainer *") - All components contained in the subtree whose root has Name=MyContainer. The "MyContainer" wouldn’t be included in this set. Only its descendants.

  9. $("#MyContainer > *") - Direct children of components with Name=MyContainer. (The "MyContainer" component would not be included in this set. Only its children.)

  10. $("#MyContainer > * > Label") - Direct grandchildren of components with Name=MyContainer. Only grand children with UIID="Label" are included.

9.2.3. Tags

Some examples above mention the use of "tags." Tags are analogous to "classes" in CSS. The goal was to provide the same kind of functionality as CSS classes, but in Java the term "class" is a little busy, so the term "tag" is used instead. You can add as many tags to a component as you like. You can then use those tags to assist in your queries. Tags are added using the addTags() method, and they’re removed using the removeTags() method.

Here is an example that uses tags to implement table striping so that even rows are a different color than odd rows in a table:

TableLayout tl = new TableLayout(numRows, numCols);
Container table = new Container(tl);
int rowNum = 0;
for (String[] row : data) {
    int colNum = 0;
    for (String cell : row) {
        table.add(
            tl.createConstraint(rowNum, colNum),
            $(new Button(cell))
                .setUIID("Label")
                .addTags(rowNum % 2 == 0 ? "even" : "odd")
                .asComponent()
        );
        colNum++;
    }
    rowNum++;
}
$(".even", table)
    .setBgColor(0xcccccc)
    .setBgTransparency(255);
Table striping screenshot

In the above example you add a tag to each label when you add it to the table or either "even" or "odd." You then use the "even" in your ComponentSelector to set the background color and transparency of all labels in even rows. In this example, you actually build the table and set the striping in the same place, but consider the situation when the table is constructed by another API. This approach would allow the API to provide more extensibility by tagging the elements and allowing the library user to decide how to style the even and odd rows.

9.3. Modifying styles

ComponentSelector includes wrappers for most of the methods of com.codename1.ui.plaf.Style so that you can change the styles of selected components using a fluent API. This was demonstrated a little bit in the table striping example (setBgColor() and setBgTransparency() were called on even rows of the table). It’s worth going over this in a little more detail though as Codename One styles have "state." For example, For the snippet of code:

$(".even", table)
    .setBgColor(0xcccccc)
    .setBgTransparency(255);

Were you setting these values on the "selected" style, the "unselected" style, the "disabled" style, "ALL" styles? In fact you were setting these values on the "current" style. That is, the call to setBgColor() caused something like the following loop to happen on all the components in the set:

for (Component c : evenComponents) {
    c.getStyle().setBgColor(0xcccccc);
}

If a component was in "selected" state, then this would change the selected style. If it was in pressed state, then it would change the "pressed" style. Etc. What if you wanted to specifically change the styles in the "pressed" state. Then you would call selectPressedStyle() prior calling your style mutation methods. For example:

$(".even", table)
    .selectPressedStyle()
    .setBgColor(0xcccccc)
    .setBgTransparency(255);

Or, ComponentSelector supports a "state" pseudo-selector that will initialize the selected style so that you don’t have to call selectXXXStyle() before making changes. For example, The following snippet is equivalent to the previous:

$(".even:pressed", table)
    .setBgColor(0xcccccc)
    .setBgTransparency(255);

The following "state" pseudo-selectors are available:

  1. :pressed - Selects the "pressed" style

  2. :selected - Selects the "selected" style

  3. :unselected - Selects the "unselected" style

  4. :disabled - Selects the "disabled" style

  5. :all - Selects the ALLStyles proxy for each component (so that you can target all styles together)

  6. :* - Same as :all

If you want to access Style objects directly, you can use one of:

  1. getPressedStyle() - Returns a proxy style with all the pressed styles of components in the set.

  2. getSelectedStyle()

  3. getUnselectedStyle()

  4. getDisabledStyle()

  5. getAllStyles()

9.4. Effects and transitions

As mentioned above, and demonstrated in the first example of this article, ComponentSelector provides a simple way to add eye-candy to your apps. It implements the fadeIn(), fadeOut(), slideUp(), and slideDown() methods and their AndWait() derivations for showing and hiding components in your UI with style. You no longer have any excuse not to use a transition for showing and hiding elements in your UIs. Using a transition always feels nicer to the user.

Also to these basic effects, ComponentSelector wraps all the existing animation functionality of the Component and Container classes but with proper accommodations for animating multiple elements simultaneously.

For example, Consider this example, that shows a button that replaces itself and all siblings with replacement labels, and then replaces them back:

Button replace = $(new Button("Replace Fade/Slide"))
    .setIcon(FontImage.MATERIAL_REDEEM)
    .addActionListener(e->{
        $(e).getParent()
            .find(">*")  (1)
            .replaceAndWait(c->{ (2)
                return $(new Label("Replacement")) (3)
                    .putClientProperty("origComponent", c) (4)
                    .asComponent();
            }, CommonTransitions.createFade(1000)) (5)
            .replaceAndWait(c->{
                Component orig = (Component)c.getClientProperty("origComponent");
                if (orig != null) {
                    c.putClientProperty("origComponent", null);
                    return orig; (6)
                }
                return c;
            }, CommonTransitions.createCover(CommonTransitions.SLIDE_HORIZONTAL, false, 1000)); (7)
    })
    .asComponent(Button.class);
1Finds all siblings of the source button
2Call replaceAndWait() with a mapping function to define the component that should replace each component. This will replace each component in the set with a replacement component in its respective container. This will also return a new ComponentSelector with the set of replacement components.
3In your "mapper" callback, you will return a new Label component to replace each existing component.
4You store the original component in the replacement’s client properties so that you can swap it back afterwards.
5You use the "Fade" transition for the replacement.
6In the second replaceAndWait() call’s mapper method, you return the original component which you retrieved from the replacement’s client properties.
7You use a cover transition for the replacement.

9.5. Component method wrappers

Most mutator methods in Component and Container include a corresponding wrapper method in ComponentSelector. Some more common component subclasses have corresponding wrappers as well. For example, addActionListener(event) will add the event to all Buttons in the set. setText(txt) will set the text on all labels, text areas, and buttons. If there are other commonly used methods that you would like to see included in ComponentSelector, file an issue, but you should find the current state to be comprehensive.

9.5.1. Tree navigation

Component and Container include a few tree navigation methods. For example, Component.getParent() returns the parent container of the current component. In cases like this, where ComponentSelector wraps such a method, it will return a set of corresponding components resulting from calling those methods on the components in the current set.

For example, $(comp1, comp2).getParent() will include both the parent of comp1 and comp2 (and if they have the same parent, then the set will include a single element.

This can get interesting when you start combining these methods. For example, $(comp1, comp2).getParent().getComponentAt(10) will be the set of components that are the 11th children of comp1 and `comp2’s parents. If neither of their parents have that many children, then it will be an empty set. If one of them has that many, then it will be a set of size 1.

9.6. More demos

A demo app exercises several of the features covered here. Most of the interesting code is in StyleBuilderDemo.java.

A short screencast of the demo app is on YouTube:

10. Rich Text and Code Editing

Codename One includes two full-document editors. Use RichTextArea when users compose formatted prose and the application stores HTML. Use CodeEditor for source code, configuration files, queries, or any text that benefits from syntax highlighting, line numbers, completion, and diagnostics. Both are lightweight Codename One components and share the same editing, selection, scrolling, undo, and platform-input infrastructure. When you only need to display formatted text — no editing — use RichTextComponent, the read-only, word-wrapping renderer described later in this chapter; it reuses the same document model and styling engine.

RichTextArea and CodeEditor rendered together
Figure 168. The rich-text and code editors rendered by the same lightweight engine

10.1. Editor architecture and backend selection

Both components extend AbstractEditorComponent. The public components send semantic commands and queries to one of two backends:

  • A port can provide a native peer through CodenameOneImplementation.createNativeEditorPeer(…​).

  • Otherwise the components use the pure Codename One engine in com.codename1.ui.editor. It paints text, selections, carets, gutters, diagnostics, and completion UI with Graphics and Font, and it drives keyboard and IME input through the low-level text-input contract.

Backend selection is transparent to application code. isNativeEditor() reports the native-peer case. The pure engine is the default renderer on every platform; there is no browser fallback.

Editor initialization can be asynchronous for a native peer. Commands issued immediately after construction are queued. Use onReady(Runnable) or a ready listener when work must run only after the backend exists. Reads use callbacks (getHtml(…​), getText(…​), and getCursorPosition(…​)) so the same application code works with either backend.

10.1.1. The editor package

The com.codename1.ui.editor package separates editing mechanics from feature-specific rendering. EditorDocument owns normalized UTF-16 text and line offsets. EditorView owns the caret, selection, composition range, scrolling, hit testing, clipboard commands, and undo transactions. CodeView and RichView extend that surface instead of creating independent input implementations.

The code layer adds incremental tokenization, palettes, completion, diagnostics, indentation, and the line-number gutter. The rich layer keeps InlineStyles, RichBlocks, hyperlink targets, and image runs parallel to the text. Every mutation, including undo and redo, updates those parallel models in the same transaction. HtmlImporter and HtmlSerializer are model adapters; they don’t implement a second HTML tokenizer. Fragment parsing and entity decoding go through the framework’s tolerant HTMLParser, which extends XMLParser. The parser’s fragment mode retains modern attributes such as data-* while the legacy HTMLComponent path keeps its existing validation behavior.

EditorHost is the narrow bridge between a view and its owner. It starts and stops platform text input, pushes updated editing state to the port, and reports semantic editor events. This split lets the same document and interaction engine run inside the full editors and inside the lightweight EditField component.

10.2. Focus, change events, and editability

focusEditor() moves focus into the editing surface and opens the virtual keyboard when appropriate. blurEditor() relinquishes focus and dismisses the active platform input session. setEditable(false) keeps the document visible while preventing edits; CodeEditor.setReadOnly(true) is the code-oriented equivalent.

Register an addChangeListener(…​) listener to observe user edits and programmatic mutations. Avoid saving on every keystroke when serialization or storage is expensive; debounce the listener, then read the document through the asynchronous callback.

10.3. Platform text input and input methods

The pure editor doesn’t treat a key release as text. Modern input can come from a virtual keyboard, autocorrect, dictation, handwriting, a hardware keyboard, or an input method editor (IME). The platform therefore drives a TextInputClient with semantic operations:

  • commitText(…​) inserts final text, including accepted autocorrect and dictation results.

  • setComposingText(…​) replaces the current marked-text range while an IME is still composing. finishComposing() finalizes that range.

  • deleteSurroundingText(…​) implements soft-keyboard deletion without manufacturing key codes.

  • onKeyCommand(…​) carries navigation, selection, clipboard, undo, and redo commands.

  • Geometry methods map UTF-16 offsets to caret and selection rectangles so native candidate windows, selection handles, and accessibility UI align with the lightweight rendering.

TextInputConfig tells the port which keyboard constraint, return-key action, autocorrection, capitalization, and multiline behavior the client needs. Rich prose enables normal language assistance; source editing disables autocorrection and automatic capitalization. The immutable TextInputState returns the authoritative text, selection, and composing range to the port after each edit.

TextInputState.getSelectionStart() and getSelectionEnd() return an ordered range for existing input bridges. getSelectionAnchor() and getSelectionFocus() retain direction: a backward selection has an anchor greater than its focus. The Apple bridge uses those directional getters; UIKit normalizes its native range, while macOS retains the anchor alongside AppKit’s ordered range.

On macOS, pure editors receive word movement and deletion, visual line and paragraph boundaries, document boundaries, and page movement through onKeyCommand(…​). AppKit interprets the key event first. Paragraph boundary commands use MOD_ALT with KEY_HOME or KEY_END. Paragraph selection uses MOD_ALT with KEY_UP or KEY_DOWN and retains MOD_SHIFT. The editor owns its visual line layout; the port waits for its updated state before replaying later native edits. Logical word commands carry MOD_ALT; spatial AppKit word-left/right commands use KEY_WORD_LEFT and KEY_WORD_RIGHT and follow the rendered directional runs. Document Home/End commands carry MOD_CTRL, and selection commands also carry MOD_SHIFT. KEY_SCROLL_PAGE_UP and KEY_SCROLL_PAGE_DOWN scroll the viewport without changing the caret or selection; they’re distinct from caret-moving KEY_PAGE_UP and KEY_PAGE_DOWN, which use cumulative line heights and visual columns for rich content. Fallback geometry snapshots sample around the active selection focus, including backward selections. Word navigation classifies Unicode letters, decimal digits and underscore consistently across ports. Combining marks inherit their base character’s classification, so emoji variation selectors stay attached during word deletion. It keeps surrogate pairs intact. It doesn’t perform dictionary segmentation. Boundary word deletions are no-ops. Character movement remains on the native composed-character path so accents, emoji variation selectors and ZWJ sequences stay intact. Unmodified character movement collapses a selection to its ordered edge. Select All explicitly creates a forward selection before later shift-arrow commands. These callbacks don’t change the legacy TextArea editing path.

The native Linux port binds this contract to GTK’s GtkIMContext. The document stays in the lightweight canvas while GTK handles composed text and input-method candidate UI. Navigation, deletion, clipboard, and undo shortcuts are delivered as semantic commands. Native TextField/TextArea editing takes over the input session when one of those fields starts native editing. A dialog’s initially focused editor can bind before its native window is shown. Temporary native window focus loss cancels an unfinished composition and pauses input without discarding the component’s session; returning to that window resumes it. A GTK text composition ending without a commit restores the original selection instead of finalizing a deletion. Pure editors implement TextInputClient.CompositionCancellation to restore rich attributes and undo state as well as text. Custom clients can implement the same optional contract; the fallback restores text and selection through their existing composition methods. Explicit commits work whether GTK ends the composition before or after the commit callback.

Linux queues native input onto the EDT with a session identifier and edit sequence. Callbacks from a closed session are discarded. The port supplies surrounding text only after Java has acknowledged all queued edits; an older state update can’t overwrite the latest context. Password and sensitive fields don’t expose surrounding text to the input method. Autocorrect enables spelling and completion hints; password, sensitive and non-predictive fields suppress them. Numeric password fields request GTK’s PIN purpose. Explicit capitalization constraints take precedence over the boolean fallback. GTK’s character-based composition and deletion offsets are converted to UTF-16. Deletion requests for a disconnected range that doesn’t touch the caret are declined because deleteSurroundingText can’t represent them. Input-method availability depends on the GTK modules installed on the user’s system. Local GTK composition tests don’t certify every installed input-method engine or a complete language-specific editor.

All offsets in this contract are UTF-16 indices, matching Java String, Android Editable, and Apple string indices. The document canonicalizes CRLF and bare CR line endings to LF before it updates the caret, undo history, formatting runs, or platform state. Port authors must deliver composition updates on the EDT and must stop the input session when the client loses focus.

TextInputClient, TextInputConfig, and TextInputState are general port-level APIs. Custom lightweight editing components can implement the same protocol, but ordinary applications normally use RichTextArea or CodeEditor and don’t bind an input client directly.

10.4. Lightweight fields with EditField

TextArea and TextField keep their established native editing behavior. When an application wants Codename One to retain control of painting, selection, scrolling, focus, and clipboard handling for a plain field, use EditField. It offers an API familiar from TextField — hint text, constraint, single-line or multiline mode, rows and columns, data-change listeners, and action events — but renders and edits entirely through the pure com.codename1.ui.editor engine, with no native peer. Adoption is opt-in per component; existing TextField and TextArea usages are unaffected.

EditField title = new EditField("", "Title", TextArea.ANY);
title.setSingleLineTextArea(true);
title.setColumns(80);

EditField notes = new EditField();
notes.setSingleLineTextArea(false);
notes.setRows(5);
notes.setColumns(30);

EditField extends EditorView directly, so selection, caret navigation, arrow-key movement, undo, and clipboard commands are the same mechanics the full editors use. A single-line EditField fires its action event on the return key and strips embedded newlines; a multiline EditField grows to its configured row count. Because there is no native overlay, the field behaves identically on every platform that implements the low-level text-input contract.

10.5. Selection, bidirectional text, and scrolling

On touch devices, a tap places the caret, a long press selects a word, and draggable handles adjust the selection. The loupe follows a handle or long-press placement gesture. A normal one-finger drag scrolls the document and doesn’t turn the swipe into a selection. On desktop, mouse drag selects text, double-click selects a word, triple-click selects a line, and the mouse wheel or trackpad scrolls the document. Standard command/control shortcuts handle copy, cut, paste, select all, undo, and redo.

Hebrew, Arabic, and mixed left-to-right/right-to-left lines use Unicode bidirectional layout. Glyph painting, hit testing, caret movement, and selection rectangles share the same visual runs. Set the component’s RTL flag to choose the paragraph base direction.

10.6. RichTextArea

RichTextArea accepts and returns an HTML fragment. The importer maps common paragraph, heading, blockquote, preformatted, list, link, image, bold, italic, underline, strike-through, color, highlight, and relative-size markup into a document model. getHtml(…​) emits canonical HTML from that model; it preserves meaning rather than the input’s exact whitespace, tag aliases, or attribute order.

Form hi = new Form("Compose", new BorderLayout());
RichTextArea editor = new RichTextArea();
editor.setPlaceholder("Write something...");
editor.setHtml("<h2>Trip itinerary</h2><p>Meet at the <b>main lobby</b>.</p>");

Toolbar tb = hi.getToolbar();
tb.addCommandToRightBar("B", null, e -> editor.bold());
tb.addCommandToRightBar("I", null, e -> editor.italic());
tb.addCommandToRightBar("List", null, e -> editor.insertUnorderedList());
tb.addCommandToRightBar("Save", null, e ->
        editor.getHtml(html -> Log.p("User wrote: " + html)));

hi.add(BorderLayout.CENTER, editor);
hi.show();
RichTextArea with formatted itinerary content
Figure 169. RichTextArea rendering headings, inline formatting, and a list

The formatting methods act on the current selection: bold(), italic(), underline(), strikeThrough(), ordered and unordered lists, indentation, alignment, foreground and highlight colors, block formats, and font sizes. queryCommandState(…​) keeps toolbar toggles synchronized with the selection. removeFormat() clears inline formatting; undo() and redo() restore text together with inline styles, paragraph attributes, links, and image runs.

Use setHtml(…​) to replace the document and insertHtml(…​) to insert a fragment at the selection. Fragment insertion retains its formatting and block structure. createLink(url) stores the target in the model, and removeLink() removes it. insertImage(url) accepts normal URLs, data URIs, and supported application resources; the source is retained so getHtml(…​) can emit an img element when the document is saved and reloaded.

10.6.1. HTML, RTF, Markdown, and AsciiDoc

setContent(…​) and insertContent(…​) accept a RichTextFormat. HTML is parsed directly with the shared HTMLParser. Markdown and AsciiDoc use their own bidirectional model adapters; they never pass through HTML. Headings, emphasis, inline code, links, images, lists, quotes, and literal blocks are mapped directly to the rich model and serialized directly back with getMarkdown(…​) or getAsciiDoc(…​). The RTF importer likewise maps paragraph breaks, Unicode escapes, bold, italic, underline, strike-through, and skips metadata destinations such as font and color tables.

Editing and reading the same format returns canonical output for that format. Requesting a different output format performs an explicit model conversion, just as getHtml(…​) canonicalizes a visual rich-text document.

editor.setContent("# Release notes\n\nThis is **ready**.", RichTextFormat.MARKDOWN);
editor.insertContent("{\\rtf1\\ansi {\\i pasted notes}}", RichTextFormat.RTF);
editor.insertContent("== Details\n\n* Portable\n* Lightweight", RichTextFormat.ASCIIDOC);

Rich paste uses ClipboardContent, a MIME-keyed container exposed by Display.copyToClipboard(…​) and Display.getClipboardContent(). RichTextClipboardData is its convenience subtype for text/plain, text/html, text/rtf, text/markdown, and text/asciidoc. A writer publishes all representations in one operation and a reader selects the richest format it understands; plain EditorView consumers use text/plain. Copying a rich selection publishes canonical HTML, RTF, Markdown, AsciiDoc, and the required plain fallback. Java SE publishes native DataFlavor values, Android publishes native plain and HTML clip data, the JavaScript port uses ClipboardItem when the browser allows it, and iOS publishes pasteboard types. A port that only has a text clipboard still publishes plain text externally and retains the complete ClipboardContent for in-application use.

The negotiation API belongs at the implementation boundary, not inside RichTextArea. Port authors override clipboard handling in CodenameOneImplementation and return the formats actually present on the system clipboard. Applications can use the same API for domain-specific formats without changing the editor.

A password, a one-time code or a recovery key shouldn’t linger on the clipboard. ClipboardContent.setSensitive(true) marks a copy as sensitive: Android 13 and newer keep its text out of the copy preview and the keyboard’s suggestions (ClipDescription.EXTRA_IS_SENSITIVE), and iOS publishes it local only, so Universal Clipboard never sends it to the user’s other devices. The simulator and the browser have no such marker. setClearAfter(millis) takes the copy off the clipboard again after that time. iOS hands the expiry to the pasteboard, which removes the copy even if the application was suspended or closed meanwhile. The other ports clear it from the application when the time is up, and only if the application copied nothing else since; Android also checks that the clip on the clipboard is still its own, so a later copy from another application stays.

RTF is also recognized when a clipboard provider returns it as a string beginning with an RTF header. Format import is intentionally a practical interchange subset, not a layout-compatible word processor: unsupported RTF destinations and advanced Markdown or AsciiDoc extensions degrade to the supported text and structure rather than controlling document layout.

Treat imported HTML as document data, not as a browser page. The pure importer doesn’t execute scripts. Keep image URLs and link destinations subject to the same trust and validation rules used by the rest of the application.

10.7. Read-only rich text with RichTextComponent

RichTextComponent (in com.codename1.ui) is the read-only counterpart to RichTextArea. It renders multi-styled, word-wrapped text — headings, bold, italic, underline, strike-through, inline code, colored and highlighted spans, per-paragraph alignment and indentation, ordered and unordered lists, block quotes, preformatted blocks, inline images, and tappable hyperlinks — without any of the editing machinery. It sits between a single-style SpanLabel (one style for the whole component) and a full BrowserComponent (a native web view): a lightweight native component that keeps a distinct style per character, measures and paints text directly, and reports an accurate height-for-width preferred size, so it embeds cleanly inside ordinary layouts. It’s the modern replacement for the deprecated HTMLComponent.

It shares the editor’s document model and the RichRunPainter styling primitive, so styled text rendered read-only matches what the editor produces for the same content.

Content is supplied in any of the interchange formats the rich model understands, or built up programmatically from styled runs:

RichTextComponent view = new RichTextComponent();

// From Markdown, HTML, or any RichTextFormat:
view.setMarkdown("# Trip summary\n\n"
        + "Departs **09:40**, arrives *11:15*. See the [itinerary](app://itinerary) for details.\n\n"
        + "- Window seat\n"
        + "- Carry-on only");
// view.setHtml("<h1>Trip summary</h1><p>Departs <b>09:40</b> ...</p>");
// view.setContent(source, RichTextFormat.ASCIIDOC);

// Or assembled run by run with editor TextStyle values:
RichTextComponent built = new RichTextComponent();
built.append("Status: ", TextStyle.DEFAULT)
        .append("confirmed", TextStyle.DEFAULT.withBold(true).withForeColor(0x1a7f37));

form.add(view);

Hyperlinks in the content fire an ActionListener whose event source is the link target string, so the application decides what a link means:

view.addLinkListener(e -> Display.getInstance().execute((String) e.getSource()));

The component resolves inline images through an ImageResolver, keeping image loading and caching policy in the application rather than the component. Return null to render a placeholder:

view.setImageResolver(src -> myImageCache.get(src));

By default (SizeMode.SHRINK) the component is exactly as tall as its wrapped content at the width it is given, which is ideal inside a scrollable Form. SizeMode.SCROLL instead keeps the size the parent assigns and scrolls the content vertically. setTextAlign(…​) overrides the alignment of every paragraph, and preferredSizeForWidth(width) is a stateless height-for-width query for custom layout managers.

The same trust guidance applies as for RichTextArea — imported HTML is document data, not a browser page; validate link targets and image sources with the application’s own rules.

10.8. CodeEditor

CodeEditor provides incremental highlighting for java, kotlin, javascript, python, css, xml, json, and c. It includes a line-number gutter, light and dark palettes, automatic bracket and quote closing, tab expansion, automatic indentation, horizontal and vertical scrolling, and read-only viewing.

Form hi = new Form("Editor", new BorderLayout());
CodeEditor editor = new CodeEditor();
editor.setLanguage("java");
editor.setTheme("light");          // or "dark"
editor.setShowLineNumbers(true);
editor.setText("public class Main {\n\n}");
hi.add(BorderLayout.CENTER, editor);
hi.show();
CodeEditor showing highlighted Java source
Figure 170. CodeEditor with Java syntax highlighting and line numbers

Choose the language with setLanguage(…​), select "light" or "dark" with setTheme(…​), toggle the gutter with setShowLineNumbers(…​), and configure indentation with setTabSize(…​). insertAtCursor(…​) replaces the active selection, while getCursorPosition(…​) reports the current UTF-16 caret offset asynchronously.

The Codename One Playground uses CodeEditor directly for its Java and CSS source panes. This uses the same language highlighting, line-number gutter, keyboard navigation, diagnostics, and diagnostic tooltips available to applications. Compiler diagnostics are passed to setDiagnostics(…​) with their source ranges; status messages use lightweight Codename One components beneath the editor. The Playground doesn’t install or bundle a separate editor engine. Source editing disables platform spelling and autocorrection; the only wavy underlines the editor draws are diagnostics supplied through setDiagnostics(…​).

10.8.1. Custom syntax highlighters

Built-in languages use grammar-specific incremental lexical analyzers. JSON doesn’t accept single-quoted strings, CSS doesn’t interpret // as a comment, XML tracks tags and attributes, Python carries triple-quoted strings across lines, and C-family numeric prefixes are validated by radix. These rules are lexical by design; a compiler or language server remains the authority for diagnostics.

Third-party libraries can register a SyntaxHighlighter under any language ID. The highlighter receives one line and the state returned for the preceding line, then returns ordered token spans and the next state. Tokens can use the built-in semantic kinds or provide explicit light and dark RGB colors. Registration is global and the pure renderer invokes the Java highlighter directly, so a custom language needs no platform-specific grammar.

SyntaxHighlighter properties = (line, state) -> {
    List<SyntaxToken> tokens = new ArrayList<>();
    int equals = line.indexOf('=');
    if (equals > 0) {
        tokens.add(new SyntaxToken(0, equals, SyntaxToken.PROPERTY,
                0x005cc5, 0x9cdcfe));
    }
    return new SyntaxHighlightResult(tokens, 0);
};
CodeEditor.registerSyntaxHighlighter("properties", properties);

CodeEditor editor = new CodeEditor("properties", "accent=#0a66c2");

10.8.2. Asynchronous code completion

A CodeCompletionProvider receives the complete source and caret offset, then delivers proposals through its callback. The callback can run after a local analysis or network/language-server request; the editor doesn’t block the EDT while proposals are produced.

editor.setCompletionProvider((sourceEditor, code, cursor, results) -> {
    List<CodeCompletion> proposals = new ArrayList<>();
    proposals.add(new CodeCompletion("println(String value)", "println()")
            .setType("method")
            .setDetail("void"));
    proposals.add(new CodeCompletion("private").setType("keyword"));
    results.onSucess(proposals);
});

Return an empty list or null to dismiss the popup. A proposal can use different display and insertion text, plus a type badge and detail string.

10.8.3. Diagnostics

setDiagnostics(…​) accepts 1-based source ranges. Errors, warnings, and informational entries appear under only the supplied character range, with a gutter marker for the affected line. Hover the range or marker on desktop, or tap it on touch devices, to display its message.

editor.setDiagnostics(Arrays.asList(
        new CodeDiagnostic(6, 9, 6, 16, "Cannot resolve method prinln")
                .setSeverity(CodeDiagnostic.ERROR),
        new CodeDiagnostic(3, 5, "Value is never read")
                .setSeverity(CodeDiagnostic.WARNING)
));

Replace the list whenever a compiler, linter, or language server publishes a newer analysis. Passing an empty list clears the current diagnostics.

10.9. Port integration checklist

The pure engine drives the editors on every platform, so a port must implement the low-level text-input contract: isTextInputSupported(), startTextInput(…​), updateTextInputState(…​), and stopTextInput(…​) in CodenameOneImplementation. The binding must distinguish committed from composing text, preserve UTF-16 offsets, map native navigation and clipboard actions to TextInputClient.KEY_*, update native selection state after programmatic edits, and anchor candidate UI with the supplied caret geometry.

Some native protocols, including iOS UITextInput, request geometry synchronously on the native UI thread. That thread must not wait for the Codename One EDT: the EDT may already be waiting for native drawing or font measurement. The iOS port captures an immutable TextInputGeometry on the EDT when starting or updating input and after painting layout or scroll changes, then answers native geometry queries from that snapshot. Native selection changes also refresh the snapshot after the editor scrolls its caret into view.

Custom editors can implement TextInputGeometry.Provider to collect visible caret positions in a single layout pass. getGeometrySnapshot() runs on the EDT and returns a non-null immutable snapshot. Caret records contain a UTF-16 document offset followed by absolute screen pixel coordinates {offset, x, y, width, height}; selection rectangles use {x, y, width, height}. Include visible insertion positions in document order, including line endpoints, and supply the active caret as the fallback for offsets outside the snapshot. The default capture samples a bounded range around the visible area and caret. Editors with expensive per-offset geometry should provide their own snapshot to avoid repeating layout work for each character.

The built-in EditorView, CodeView and RichView collect their visible geometry by line and font run. Font.getTextRunPositions(text, rtl) lets the Apple ports shape each run once with Core Text, including styled and directional runs, instead of measuring thousands of prefixes on every input update. Other ports have a compatibility fallback. Editor subclasses that change character measurement should override measureLineCaretPositions() alongside measureColumnX().

A port with a better platform editor can instead supply a native peer and implement the existing semantic command/query channel. In both cases application code, change listeners, ready handling, and asynchronous queries remain the same.

11. Accessibility Semantics

Codename One components are lightweight: they’re painted by Codename One instead of being represented by a native widget on every platform. The accessibility semantics API builds an explicit, immutable virtual tree from those components and presents it to VoiceOver, TalkBack, Windows UI Automation, AT-SPI, Java Access Bridge, and web accessibility APIs.

The semantic tree is separate from the visual tree. This is important for renderer-backed controls, merged cards, decorative content, custom controls, and applications that need a reading order different from paint order.

11.1. Built-in semantics

Standard components work without extra configuration. Button, CheckBox, RadioButton, Slider, text fields, lists, tables, tabs, labels, dialogs, and containers infer appropriate roles, values, states, collection metadata, and standard actions. Renderer-backed List rows are exposed as stable virtual children even though no Component exists for each painted row.

Component.setAccessibilityText() remains supported. It’s a compatibility alias for the semantic label. New code should use getSemantics() when it needs more than a label.

Button save = new Button("Save");
save.getSemantics()
        .setHint("Saves the edited profile")
        .setIdentifier("profile-save");

Changes to text, selection, focus, enabled state, bounds, scrolling, ranges, tabs, and the current Form automatically invalidate the native semantic tree. Custom components should call accessibilityChanged() after a semantic value changes outside a standard setter.

11.2. Roles, names, values, and state

AccessibilityRole contains portable control roles including buttons, toggle buttons, switches, checkboxes, radio buttons, headings, links, images, text and search fields, sliders, progress indicators, lists, grids, rows, cells, headers, tabs, dialogs, alerts, menus, toolbars, combo boxes, trees, and separators. A port maps an unsupported role to the closest native role without discarding its label or state.

wifiSwitch.getSemantics()
        .setRole(AccessibilityRole.SWITCH)
        .setLabel("Wi-Fi")
        .setChecked(AccessibilityCheckedState.CHECKED)
        .setEnabled(Boolean.TRUE)
        .setHint("Double tap to turn Wi-Fi off");

title.getSemantics() .setHeadingLevel(2) .setIdentifier("network-heading");

Tri-state controls use UNCHECKED, CHECKED, or MIXED. Nullable Boolean properties distinguish an explicit state from an unspecified state. Available properties include selected, expanded, enabled, invalid, busy, read-only, required, multiline, obscured, pressed, and current. setValidationError() supplies both the error message and invalid state. setPaneTitle() describes a newly displayed pane or screen, and setModal(true) identifies a modal scope.

Use setRoleDescription() only when the platform role isn’t sufficiently specific. Localize labels, hints, descriptions, errors, pane titles, role descriptions, and custom action labels.

11.3. Ranges and editable values

AccessibilityRange describes minimum, maximum, current value, increment, and an optional spoken value. The spoken value is useful for ranges such as ratings and durations where a raw number is ambiguous.

rating.getSemantics()
        .setRole(AccessibilityRole.SLIDER)
        .setLabel("Rating")
        .setRange(new AccessibilityRange(0, 5, 3, 1, "3 out of 5"));

Editable controls can provide SET_VALUE or SET_TEXT actions. Sliders and other adjustable controls should expose INCREMENT and DECREMENT. Standard components infer these actions.

11.4. Custom accessibility actions

An AccessibilityAction has a stable ID, a localized label, an enabled state, and a handler. Handlers always execute on the Codename One EDT, including when the action originates on a native accessibility thread.

card.getSemantics().addAction(new AccessibilityAction(
        "archive",
        "Archive message",
        new AccessibilityAction.Handler() {
            public boolean perform(Component component, Object argument) {
                archiveMessage();
                return true;
            }
        }
));

Use the standard IDs in AccessibilityAction for activation, long press, increment, decrement, set value, set text, selection, character or word cursor movement, focus, show-on-screen, dismiss, expand, collapse, scrolling, and clipboard operations. A custom ID must be stable and its label must not be null.

11.5. Grouping and virtual descendants

AccessibilityGrouping controls how a component participates in the semantic tree:

  • AUTO uses normal component inference.

  • LEAF exposes the component but none of its descendants.

  • GROUP exposes the component as a semantic container and retains its descendants.

  • MERGE_DESCENDANTS combines descendant labels, descriptions, values, state, and actions into one node.

  • EXCLUDE removes the component but promotes its descendants to the semantic parent.

  • EXCLUDE_SUBTREE removes the component and all descendants.

summaryCard.getSemantics()
        .setRole(AccessibilityRole.GENERIC)
        .setGrouping(AccessibilityGrouping.MERGE_DESCENDANTS);

For content that’s painted without child components, attach an AccessibilityChildProvider, or add standalone AccessibilityNode children. Every virtual node must use a stable virtualKey. Stable keys preserve native focus while rows are updated or recycled.

chart.getSemantics().setChildProvider(new AccessibilityChildProvider() {
    public List<AccessibilityNode> getAccessibilityChildren(Component owner) {
        List<AccessibilityNode> result = new ArrayList<AccessibilityNode>();
        for (ChartPoint point : points) {
            AccessibilityNode node = new AccessibilityNode("point-" + point.getId());
            node.setRole(AccessibilityRole.IMAGE)
                    .setLabel(point.getLabel())
                    .setValue(point.getFormattedValue())
                    .setBounds(point.getBounds());
            result.add(node);
        }
        return result;
    }
});

Virtual bounds are relative to the owning component. Component nodes use their clipped absolute bounds.

11.6. Traversal order

Visual order is the default reading order. setSortKey() assigns an ordered semantic key among siblings. setTraversalBefore() and setTraversalAfter() express a direct relationship when a numeric order would be fragile.

cancel.getSemantics().setSortKey(1);
continueButton.getSemantics().setSortKey(2);
help.getSemantics().setTraversalAfter(continueButton);

Keep traversal relationships within the same semantic parent. The tree builder resolves these constraints deterministically and preserves stable node IDs.

11.7. Live regions and screen changes

Set AccessibilityLiveRegion.POLITE for non-urgent updates and ASSERTIVE for errors or urgent status. OFF is the default. Live changes produce the corresponding platform notification or ARIA live update.

status.getSemantics()
        .setRole(AccessibilityRole.ALERT)
        .setLiveRegion(AccessibilityLiveRegion.POLITE);
status.setText("Upload complete");

Form changes and nodes with a pane title produce screen or pane transition notifications. Display.announceForAccessibility() remains available for an exceptional announcement that isn’t represented by persistent UI. Prefer a live region for state that’s visible on screen.

11.8. User accessibility preferences

Semantics describe what a control means. Accessibility preferences describe how the user wants the interface presented. Read these preferences through Display or the matching static shortcuts in CN:

APIMeaning

isHighContrastEnabled()

The user requests stronger foreground and background contrast.

isDifferentiateWithoutColorEnabled()

The user requests labels, shapes, or patterns in addition to color.

getColorVisionDeficiency()

Returns NONE, PROTANOPIA, DEUTERANOPIA, TRITANOPIA, MONOCHROMACY, or UNKNOWN.

isReduceMotionEnabled()

Nonessential motion should be removed or replaced with an instant or cross-fade change.

isReduceTransparencyEnabled()

Blur and translucent surfaces should use an opaque alternative.

isBoldTextEnabled()

The system requests a heavier text weight.

isInvertColorsEnabled() and isGrayscaleEnabled()

The operating system is transforming the displayed colors.

isOnOffSwitchLabelsEnabled()

Switches should include a visible on/off distinction.

isScreenReaderEnabled()

A screen reader or touch-exploration service is active.

An unavailable preference returns false; an unavailable color-vision mode returns UNKNOWN. Don’t hide accessibility support behind isScreenReaderEnabled(). A screen reader can start after the application launches, and other assistive technologies consume the same semantic tree.

if (CN.isHighContrastEnabled()) {
    animatedChart.setUIID("HighContrastChart");
}

// Important state always uses text or an icon as well as color. The
// preference is an extra signal, not permission to use color alone.
if (CN.isDifferentiateWithoutColorEnabled()
        || CN.getColorVisionDeficiency() != AccessibilityColorVisionDeficiency.NONE) {
    connectionStatus.setText("Disconnected: action required");
}

if (CN.isReduceMotionEnabled()) {
    animatedChart.putClientProperty("animate", Boolean.FALSE);
}
if (CN.isReduceTransparencyEnabled()) {
    animatedChart.setUIID("OpaqueChart");
}
Never use getColorVisionDeficiency() == NONE as permission to convey information only through color. The setting can be unavailable, a person might not enable a system filter, and contrast can change with lighting and display hardware. Design the default interface with redundant cues, then use preferences for further adaptation.

Preference detection uses each platform’s public signals. iOS and macOS expose contrast, differentiate-without-color, motion, transparency, bold text, inversion, grayscale, switch labels, and VoiceOver; Apple doesn’t expose the selected color-filter type, so the deficiency value is UNKNOWN. Android reads high-text contrast, display inversion and color-correction mode, animation scale, font-weight adjustment, and touch exploration. Windows reads High Contrast, client-area animation, and screen-reader settings. Linux detects the GTK HighContrast theme, disabled GTK animation, and ATK bridge activation. JavaScript uses forced-colors, prefers-contrast, prefers-reduced-motion, and prefers-reduced-transparency. The Java SE simulator provides deterministic controls for every portable signal.

11.9. Collections

AccessibilityCollectionInfo describes row and column counts, hierarchy, and selection mode. AccessibilityCollectionItemInfo describes row and column index, spans, position and size in a set, nesting level, and header status.

grid.getSemantics().setCollectionInfo(
        new AccessibilityCollectionInfo(20, 3, false,
                AccessibilityCollectionInfo.SELECTION_MULTIPLE));

cell.getSemantics().setCollectionItemInfo( new AccessibilityCollectionItemInfo( 4, 1, 2, 1, 5, 20, 1, false));

Row and column indexes are zero-based. Position and set size are one-based; use -1 when unknown. Lists, tables, tabs, and their items infer this metadata where possible.

Renderer-backed lists keep the full model size in their collection metadata but materialize only the visible rows, a small navigation buffer, and the selected row as virtual children. Forward and backward semantic scroll actions move the window. This keeps accessibility-tree work proportional to the viewport instead of invoking a cell renderer for every row whenever a large list scrolls.

11.10. Inspecting and testing semantics

AccessibilityInspector returns an immutable snapshot. A snapshot is safe to inspect without racing native accessibility callbacks and includes stable IDs, hierarchy, bounds, resolved state, actions, range and collection data. toJson() is suitable for diagnostic reports and tooling.

Semantic setters always mark the cached tree dirty. Pull-based native ports rebuild it on the Codename One EDT only while assistive technology is active or when a tool explicitly requests a snapshot; the browser keeps its off-screen ARIA projection synchronized continuously. Applications should still publish complete semantics unconditionally—this runtime optimization is transparent to application code.

AccessibilityTreeSnapshot tree =
        AccessibilityInspector.snapshot(myForm);

AccessibilityAssertions.assertNoErrors(tree); AccessibilityAssertions.assertNoUnlabeledInteractiveNodes(tree);

String diagnosticJson = tree.toJson(); AccessibilityNodeSnapshot hit = tree.getNodeAt(screenX, screenY);

AccessibilityAssertions.audit() reports machine-readable AccessibilityIssue values for unlabeled controls, invalid ranges, duplicate identifiers or actions, invalid collection positions, missing parents, cycles, unnamed dialogs, and unlabeled custom actions. Warnings also identify suspicious role/state combinations and empty bounds.

The Java SE Component Inspector provides Copy Accessibility Tree JSON and Audit Accessibility Tree actions. Tests should assert resolved semantic properties instead of platform-specific spoken sentences. The scripts/hellocodenameone suite contains the cross-port conformance fixture used by native CI.

11.11. Diagnosing and correcting an inaccessible screen

Accessibility review works best as a repeatable loop instead of a final checklist:

  1. Use the keyboard to reach every operation. Verify visible focus, logical order, escape from modal UI, and operation without pointer gestures.

  2. Open Tools → Component Inspector. Select the form or a suspicious component, then choose Audit Accessibility Tree. Start with errors, such as an unlabeled interactive node, invalid range, or unnamed dialog.

  3. Choose Copy Accessibility Tree JSON and inspect the resolved role, label, value, state, actions, bounds, and child order. This catches cases where the visual component hierarchy doesn’t match the virtual accessibility hierarchy.

  4. Use Simulate → Accessibility Preferences to test high contrast, reduced motion, reduced transparency, inversion, grayscale, and each color-vision filter. Also test Simulate → Larger Text at Accessibility 5. Look for clipped text, color-only state, invisible focus, unreadable overlays, and motion that remains essential to understanding the result.

  5. Correct the component API or theme. Run the audit again, add a focused assertion, and verify the native screen reader before considering the issue closed.

The simulator menu changes the values returned by Display and CN. Color-vision, inversion, and grayscale choices also filter the simulator canvas, so screenshots show approximately what remains distinguishable. These filters are diagnostic approximations; they don’t replace testing with platform display filters or users.

Java SE simulator with the Accessibility Preferences menu open
Figure 171. Accessibility preferences in the Java SE simulator

The following icon-only custom control is painted and responds to a pointer, but initially has no usable name, role, or keyboard-equivalent action. The audit reports it as an unlabeled interactive node. Repair the semantic contract at the custom-control boundary:

iconOnlyButton.getSemantics()
        .setRole(AccessibilityRole.BUTTON)
        .setLabel("Delete message")
        .setHint("Removes this message from the conversation")
        .setIdentifier("message-delete")
        .addAction(new AccessibilityAction(
                AccessibilityAction.ACTIVATE,
                null,
                new AccessibilityAction.Handler() {
                    public boolean perform(Component component, Object argument) {
                        deleteMessage();
                        return true;
                    }
                }));

Don’t fix the warning by adding a label alone if the role, current state, range, or available actions are still wrong. For example, a custom switch needs SWITCH, checked state, and activation; a chart needs virtual descendants for its meaningful data points; a renderer-backed grid needs collection and item metadata.

Component Inspector showing an accessibility audit
Figure 172. Auditing the semantic tree in the Component Inspector

11.11.1. Assertions that prevent regressions

Snapshot the finished form and assert behavior that matters to a user. Prefer stable identifiers and resolved semantics over implementation class names or platform-specific speech:

AccessibilityTreeSnapshot tree = AccessibilityInspector.snapshot(form);
AccessibilityAssertions.assertNoErrors(tree);
AccessibilityAssertions.assertNoUnlabeledInteractiveNodes(tree);

AccessibilityNodeSnapshot save = tree.getNodeByIdentifier("profile-save");
assert save.getRole() == AccessibilityRole.BUTTON;
assert save.getAction(AccessibilityAction.ACTIVATE) != null;

Keep targeted assertions for traversal order, validation errors, live-region behavior, ranges, and stable virtual keys. The scripts/hellocodenameone accessibility fixture invokes every portable preference API and exercises the resolved semantic tree on each native CI platform.

11.11.2. Native verification

The simulator finds portable problems, but the final pass must use VoiceOver, TalkBack, Narrator, Orca, or the browser accessibility tree. Navigate in both directions, activate every action, change adjustable values, enter and leave collections, trigger errors, and confirm that focus moves sensibly after a dialog, navigation, deletion, or live update. Record the platform, assistive-technology version, input method, and failed semantic node in the bug report; attach the inspector JSON when the native result differs from the portable snapshot.

11.12. Platform mappings

TargetNative representationNotable behavior

iOS, iPadOS, and macOS

UIAccessibilityElement instances owned by the rendering view

Traits, values, frames, custom actions, adjustable actions, live announcements, and screen/layout transitions

Android

AccessibilityNodeProvider virtual descendants

Class/role mapping, checked and mixed state, headings, pane titles, errors, ranges, collections, focus, hit testing, and custom actions

Windows native

UI Automation fragment-root provider

Virtual fragments, control types, names, values, state, bounds, navigation, focus lookup, hit testing, and action dispatch

Linux native

Transparent GTK semantic widgets exposed through ATK/AT-SPI

Roles, names, descriptions, state, hierarchy, bounds, and action dispatch

Java SE simulator and desktop

Swing AccessibleContext virtual children

Roles, states, values, geometry, accessible actions, and Component Inspector integration

JavaScript

A synchronized off-screen DOM tree

ARIA roles, names, state, ranges, live regions, collection metadata, traversal order, and action routing; the painted canvas is hidden from the accessibility tree

The API intentionally goes beyond a label-only model: it includes stable virtual children, explicit traversal constraints, collection spans and set metadata, pane transitions, machine-readable inspection, and built-in semantic audits. Platform accessibility tools remain the final verification step because screen readers can apply platform-specific presentation rules.

For underlying platform guidance, see the Apple UIAccessibility protocol, Android accessibility principles, Microsoft UI Automation provider overview, and W3C WAI-ARIA.

12. Animations

There are many ways to animate and liven the data within a Codename One application, layout animations are probably chief among them. But first you need to understand some basics such as layout reflows.

12.1. Layout reflow

Layout in tools such as HTML is implicit, when you add something into the UI it’s automatically placed. Other tools such as Codename One use explicit layout, that means you’ve to explicitly request the UI to layout itself after making changes!

Like many such rules exceptions occur. For example, if the device is rotated or window size changes a layout will occur automatically.

When adding a component to a UI that’s already visible, the component won’t show by default.

When adding a component to a form which isn’t shown on the screen, there is no need to tell the UI to repaint or reflow. This happens implicitly.

The chief advantage of explicit layout is performance.

For example, imagine adding 100 components to a form. If the form was laid out automatically, layout would have happened 100 times instead of once when adding was finished. In fact layout reflows are often considered the #1 performance issue for HTML/JavaScript applications.

Smart layout reflow logic can alleviate some pains of the automatic layout reflows but since the process is implicit it’s almost impossible to optimize complex usages across browsers/devices. A major JavaScript performance tip is to use absolute positioning which is akin to not using layouts at all!

That’s why, when you add components to a form that’s already showing, you should invoke revalidate() or animate the layout appropriately. This also enables the layout animation behavior explained below.

12.2. Layout animations

To understand animations you need to understand a couple of things about Codename One components. When you add a component to a container, it’s added but not positioned anywhere. A novice might notice the setX/setY/setWidth/setHeight methods on a component and try to position it.

This won’t work since these methods are meant for the layout manager, which is implicitly invoked when a form is shown (internally in Codename One). The layout manager uses these methods to position/size the components based on the hints given to it.

If you add components to a form that’s showing, it’s your responsibility to invoke revalidate/layoutContainer to arrange the newly added components (see Layout Reflows).

animateLayout() method is a fancy form of revalidate that animates the components into their laid out position. After changing the layout & invoking this method the components move to their new sizes/positions seamlessly. Form exposes convenience wrappers such as animateLayout*() that forward to the underlying content pane, so you can call the methods directly on the form unless you specifically need to animate a nested container.

This sort of behavior creates a special case where setting the size/position makes sense. When you set the size/position in the demo code here you’re positioning the components at the animation start position above the frame:

Form hi = new Form("Layout Animations", new BoxLayout(BoxLayout.Y_AXIS));
Button fall = new Button("Fall"); (1)
fall.addActionListener((e) -> {
    for (int iter = 0; iter < 10; iter++) {
        Label b = new Label("Label " + iter);
        b.setWidth(fall.getWidth());
        b.setHeight(fall.getHeight());
        b.setY(-fall.getHeight());
        hi.add(b);
    }
    hi.animateLayout(20000); (2)
});
hi.add(fall);

Notice these things about this example:

1You used a button to do the animation rather than doing it on show. Since show() implicitly lays out the components it wouldn’t have worked.
2You used hi.animateLayout(20000);, which delegates to the Form content pane. If you need to animate a specific container (for example, a nested layout), call animateLayout() on that container instead.

This results in:

Frame 1 Frame 2 Frame 3 Frame 4 Frame 5 Frame 6 Frame 7

12.2.1. Unlayout animations

While layout animations are powerful effects for adding elements into the UI and drawing attention to them. The inverse of removing an element from the UI is often more important. For example, when you delete or remove an element you want to animate it out.

Layout animations don’t do that since they will try to bring the animated item into place. The exact opposite of a layout animation is the "unlayout animation." Container.animateUnlayout(int, int, Runnable) and the Form.animateUnlayout*() helpers trigger this transition either asynchronously (with a completion callback) or synchronously via the AndWait variants.

The "unlayout animation" takes a valid laid out state and shifts the components to an invalid state that you defined in advance. For example, you can fix the example above to flip the "fall" button into a "rise" button when the buttons come into place and this will allow the buttons to float back up to where they came from in the exact reverse order.

An unlayout animation always leaves the container in an invalidated state.
Form hi = new Form("Layout Animations", new BoxLayout(BoxLayout.Y_AXIS));
Button fall = new Button("Fall");
fall.addActionListener((e) -> {
    if (hi.getContentPane().getComponentCount() == 1) {
        fall.setText("Rise");
        for (int iter = 0; iter < 10; iter++) {
            Label b = new Label("Label " + iter);
            b.setWidth(fall.getWidth());
            b.setHeight(fall.getHeight());
            b.setY(-fall.getHeight());
            hi.add(b);
        }
        hi.animateLayout(20000);
    } else {
        fall.setText("Fall");
        for (int iter = 1; iter < hi.getContentPane().getComponentCount(); iter++) { (1)
            Component c = hi.getContentPane().getComponentAt(iter);
            c.setY(-fall.getHeight()); (2)
        }
        hi.animateUnlayoutAndWait(20000, 255); (3)
        hi.removeAll(); (4)
        hi.add(fall);
        hi.revalidate();
    }
});
hi.add(fall);

You will notice some similarities with the unlayout animation but the differences represent the exact opposite of the layout animation:

1You loop over existing components (not newly created ones)
2You set the desired end position not the desired starting position
3You used the animateUnlayoutAndWait(…​) variant to block until completion; animateUnlayout(duration, opacity, callback) provides the non-blocking alternative when you want to continue and run code from a callback instead.
4After the animation completes you need to actually remove the elements since the UI is now in an invalid position with elements outside of the screen but still physically there!

12.2.2. Hiding & visibility

A common trick for animating Components in Codename One is to set their preferred size to 0 and then invoke animateLayout() thus triggering an animation to hide said Component. several issues with this trick but one of the biggest ones is the fact that setPreferredSize has been deprecated for quite a while.

Instead of using that trick you can use setHidden/isHidden who effectively encapsulate this functionality and a bit more.

One of the issues setHidden tries to solve is the fact that preferred size doesn’t include the margin in the total and thus a component might still occupy space despite being hidden. When you request the margin change the current margins are cached, the component is given zero margins while hidden, and those cached values are restored when it’s shown again—without resetting the UIID or other style state.

This functionality might be undesirable which is why there is a version of the setHidden method that accepts a boolean flag indicating whether the margin cache should be manipulated. You can effectively hide/show a component without deprecated code using something like this:

Button toHide = new Button("Will Be Hidden");
Button hide = new Button("Hide It");
hide.addActionListener((e) -> {
    hide.setEnabled(false);
    boolean t = !toHide.isHidden();
    toHide.setHidden(t);
    toHide.getParent().animateLayoutAndWait(200);
    toHide.setVisible(!t);
    hide.setEnabled(true);
});
Notice that the code above uses setVisible(), which shouldn’t be confused with setHidden. setVisible() toggles the visibility of the component it would still occupy the same amount of space

12.2.3. Synchronicity in animations

Most animations have two or three variants:

  • Standard animation for example, animateLayout(int) or the non-blocking animateUnlayout(int, int, Runnable)

  • And wait variant for example, animateLayoutAndWait(int) / animateUnlayoutAndWait(int, int)

  • Callback variant for example, animateLayoutFade(int, int, Runnable)

The standard animation is invoked when you don’t care about the completion of the animation. You can do this for a standard animation.

Unlayout animations always leave the container in an invalid state, so even the standard helper expects you to tidy up either in the callback or after the animation finishes.

The AndWait variant blocks the calling thread until the animation completes. This is useful for sequencing animations one after the other e.g this code from the kitchen sink demo:

arrangeForInterlace(effects);
effects.animateUnlayoutAndWait(800, 20);
effects.animateLayoutFade(800, 20);

First the UI goes through an "unlayout" animation, once that completes the layout itself is performed.

The AndWait calls needs to be invoked on the Event Dispatch Thread despite being "blocking." This is a common convention in Codename One powered by a unique capability of Codename One: invokeAndBlock.
You can learn more about invokeAndBlock in the EDT section.

The callback variant is like the invokeAndBlock variant but uses a more conventional callback semantic which is more familiar to some developers. It accepts a Runnable callback that will be invoked after the fact. For example, you can change the unlayout call from before to use the callback semantics as such:

hi.animateUnlayout(20000, 255, () -> {
    hi.removeAll();
    hi.add(fall);
    hi.revalidate();
});
Animation fade and hierarchy

There are several more variations on the standard animate methods. Several methods accept a numeric fade argument. This is useful to fade out an element in an "unlayout" operation or fade in a regular animation.

The value for the fade argument is a number between 0 and 255 where 0 represents full transparency and 255 represents full opacity.

Some animate layout methods are hierarchy based. They work like the regular animateLayout methods but recurse into the entire Container hierarchy. These methods work well when you have components in a nested hierarchy that need to animate into place. This is demonstrated in the opening sequence of the kitchen sink demo:

for(int iter = 0 ; iter < demoComponents.size() ; iter++) {
    Component cmp = (Component)demoComponents.elementAt(iter);
    if(iter < componentsPerRow) {
        cmp.setX(-cmp.getWidth());
    } else {
        if(iter < componentsPerRow * 2) {
            cmp.setX(dw);
        } else {
            cmp.setX(-cmp.getWidth());
        }
    }
}
boxContainer.setShouldCalcPreferredSize(true);
boxContainer.animateHierarchyFade(3000, 30);

The demoComponents Vector contains components from separate containers and this code would not work with a simple animate layout.

Avoid the hierarchy version where possible. Its slower but more importantly, it’s flaky. Since the size/position of the Container might be affected by the layout the animation could get clipped and skip. These are hard issues to debug.

12.2.4. Sequencing animations via AnimationManager

All the animations go through a per-form queue: the AnimationManager. This effectively prevents two animations from mutating the UI in parallel so you won’t have collisions between two conflicting sides. Things get more interesting when you try to do something like this:

cnt.add(myButton);
int componentCount = cnt.getComponentCount();
cnt.animateLayout(300);
cnt.removeComponent(myButton);
if(componentCount == cnt.getComponentCount()) {
    // this will happen...
}

The reason this happens is that the second remove gets postponed to the end of the animation so it won’t break the animation. This works for remove and add operations on a Container as well as other animations.

The simple yet problematic fix would be:

cnt.add(myButton);
int componentCount = cnt.getComponentCount();
cnt.animateLayoutAndWait(300);
cnt.removeComponent(myButton);
if(componentCount == cnt.getComponentCount()) {
    // this probably won't happen...
}

Why might that still fail?

Events come in constantly during the run of the EDT [6], so an event might come in that might trigger an animation in your code. Even if you’re on the EDT keep in mind that you don’t actually block it and an event might come in.

In those cases an animation might start and you might be unaware of that animation and it might still be in action when you expect remove to work.

Animation manager to the rescue

AnimationManager has built-in support to fix this exact issue.

You can flush the animation queue and run synchronously after all the animations finished and before new ones come in by using something like this:

cnt.add(myButton);
int componentCount = cnt.getComponentCount();
cnt.animateLayout(300);
cnt.getAnimationManager().flushAnimation(() -> {
    cnt.removeComponent(myButton);
    if(componentCount == cnt.getComponentCount()) {
        // this shouldn't happen...
    }
});

12.3. Low-level animations

The Codename One event dispatch thread has a special animation "pulse" allowing an animation to update its state and draw itself. Code can make use of this pulse to implement repetitive polling tasks that have little to do with drawing.

This is helpful since the callback will always occur on the event dispatch thread.

Every component in Codename One contains an animate() method that returns a boolean value, you can also implement the Animation interface in an arbitrary component to implement your own animation. To receive animation events you need to register yourself within the parent form, it’s the responsibility of the parent for to call animate().

If the animate method returns true then the animation will be painted (the paint method of the Animation interface would be invoked).

It’s important to deregister animations when they aren’t needed to conserve battery life.

If you derive from a component, which has its own animation logic you might damage its animation behavior by deregistering it, so use care with the low-level API’s.

For example, you can add more animation logic using code like this:

myForm.registerAnimated(this);
private int spinValue;
@Override
public boolean animate() {
   if(userStatusPending) {
       spinValue++;
       super.animate();
       return true;
   }
   return super.animate();
}

12.3.1. Why not just write code in paint

Animations comprise two parts, the logic (deciding the position, etc.) and the painting. The paint method should be dedicated to painting, not to the actual moving of the components.

The separation of concerns allows you to avoid redundant painting for example, if animate didn’t trigger a change return false to avoid the overhead related to animations.

You discuss low-level animations in more details within the animation section of the clock demo.

12.4. Transitions

Transitions allow you to replace one component with another, most typically forms or dialogs are replaced with a transition but a transition can be applied to replace any arbitrary component.

Developers can implement their own custom transition and install it to components by deriving the Transition class, although most commonly the built in CommonTransitions class is used for almost everything.

You can define transitions for forms/dialogs/menus globally either via the theme constants or via the LookAndFeel class. Or you can install a transition on top-level components via setter methods.

In/Out Transitions

When defining a transition you define the entering transition and the exiting transition. For most cases only one of those is necessary and you default to the exiting (out transition) as a convention.

For most cases the method setFormTransitonIn should go unused. That API exists for some elaborate custom transitions that might need to have a special effect both when transitioning in and out of a specific form. But, most of these effects are easier to achieve with layout animations (for example, components dropping into place etc.).

For Dialog the transition in shows its appearance and the transition out shows its disposal. In that case both transitions make a lot of sense.

Back/Forward Transitions

Transitions have a direction and can all be played either in incoming or outgoing direction. A transition can be flipped (played in reverse) when use an RTL language [7] or when you traverse backwards in the form navigation hierarchy.

Normally Form.show() displays the next Form with an incoming transition based on the current RTL mode. If you use Form.showBack() it will play the transition in reverse.

When working with high-level animations you can select Slow Motion option in the simulator to slow down animations and inspect their details

Themes define the default transitions used when showing a form, these differ based on the OS. In most platforms the default is Slide whereas in iOS the default is SlideFade which slides the content pane and title while fading in/out the content of the title area.

SlideFade is problematic without a title area. If you have a Form that lacks a title area you would recommend to disable SlideFade at least for that Form.

Check out the full set of theme constants in the Theme Constants Section.

12.4.1. Replace

To apply a transition to a component you can use the Container.replace() method as such:

Form hi = new Form("Replace", new BoxLayout(BoxLayout.Y_AXIS));
Button replace = new Button("Replace Pending");
Label replaceDestiny = new Label("Destination Replace");
hi.add(replace);
replace.addActionListener((e) -> {
    replace.getParent().replaceAndWait(replace, replaceDestiny, CommonTransitions.createCover(CommonTransitions.SLIDE_VERTICAL, true, 800));
    replaceDestiny.getParent().replaceAndWait(replaceDestiny, replace, CommonTransitions.createUncover(CommonTransitions.SLIDE_VERTICAL, true, 800));
});
Replace even works when you have a layout constraint in place for example, replacing a component in a border layout will do the "right thing." But, some layouts such as TableLayout might be tricky in such cases so recommend wrapping a replaceable Component in a border layout and replacing the content.

Container.replace() can also be used with a null transition at which point it replaces instantly with no transition.

12.4.2. Slide transitions

The slide transitions are used to move the Form/Component in a sliding motion to the side or up/down. Four basic types of slide transitions exist:

  1. Slide - the most commonly used transition

  2. Fast Slide - historically this provided better performance for old device types. It’s no longer recommended for newer devices

  3. Slide Fade - the iOS default where the title area features a fade transition

  4. Cover/Uncover - a kind of slide transition where the source or destination form slides while the other remains static in place

The code below demonstrates the usage of all the main transitions:

    Toolbar.setGlobalToolbar(true);
    Form hi = new Form("Transitions", new BoxLayout(BoxLayout.Y_AXIS));
    Style bg = hi.getContentPane().getUnselectedStyle();
    bg.setBgTransparency(255);
    bg.setBgColor(0xff0000);
    Button showTransition = new Button("Show");
    Picker pick = new Picker();
    pick.setStrings("Slide", "SlideFade", "Cover", "Uncover", "Fade", "Flip");
    pick.setSelectedString("Slide");
    TextField duration = new TextField("10000", "Duration", 6, TextArea.NUMERIC);
    CheckBox horizontal = CheckBox.createToggle("Horizontal");
    pick.addActionListener((e) -> {
        String s = pick.getSelectedString().toLowerCase();
        horizontal.setEnabled(s.equals("slide") || s.indexOf("cover") > -1);
    });
    horizontal.setSelected(true);
    hi.add(showTransition).
        add(pick).
        add(duration).
        add(horizontal);

    Form dest = new Form("Destination");
    bg = dest.getContentPane().getUnselectedStyle();
    bg.setBgTransparency(255);
    bg.setBgColor(0xff);
    dest.setBackCommand(
            dest.getToolbar().addCommandToLeftBar("Back", null, (e) -> hi.showBack()));

    showTransition.addActionListener((e) -> {
        int h = CommonTransitions.SLIDE_HORIZONTAL;
        if(!horizontal.isSelected()) {
            h = CommonTransitions.SLIDE_VERTICAL;
        }
        switch(pick.getSelectedString()) {
            case "Slide":
                hi.setTransitionOutAnimator(CommonTransitions.createSlide(h, true, duration.getAsInt(3000)));
                dest.setTransitionOutAnimator(CommonTransitions.createSlide(h, true, duration.getAsInt(3000)));
                break;
            case "SlideFade":
                hi.setTransitionOutAnimator(CommonTransitions.createSlideFadeTitle(true, duration.getAsInt(3000)));
                dest.setTransitionOutAnimator(CommonTransitions.createSlideFadeTitle(true, duration.getAsInt(3000)));
                break;
            case "Cover":
                hi.setTransitionOutAnimator(CommonTransitions.createCover(h, true, duration.getAsInt(3000)));
                dest.setTransitionOutAnimator(CommonTransitions.createCover(h, true, duration.getAsInt(3000)));
                break;
            case "Uncover":
                hi.setTransitionOutAnimator(CommonTransitions.createUncover(h, true, duration.getAsInt(3000)));
                dest.setTransitionOutAnimator(CommonTransitions.createUncover(h, true, duration.getAsInt(3000)));
                break;
            case "Fade":
                hi.setTransitionOutAnimator(CommonTransitions.createFade(duration.getAsInt(3000)));
                dest.setTransitionOutAnimator(CommonTransitions.createFade(duration.getAsInt(3000)));
                break;
            case "Flip":
                hi.setTransitionOutAnimator(new FlipTransition(-1, duration.getAsInt(3000)));
                dest.setTransitionOutAnimator(new FlipTransition(-1, duration.getAsInt(3000)));
                break;
        }
        dest.show();
    });
    hi.show();
The slide transition moves both incoming and outgoing forms together
Figure 173. The slide transition moves both incoming and outgoing forms together
The slide transition can be applied vertically as well
Figure 174. The slide transition can be applied vertically as well
Slide fade fades in the destination title while sliding the content pane its the default on iOS
Figure 175. Slide fade fades in the destination title while sliding the content pane it’s the default on iOS
SlideFade is problematic without a title area. If you have a Form that lacks a title area you would recommend to disable SlideFade at least for that Form.
With cover transitions the source form stays in place as it’s covered by the destination. This transition can be played both horizontally and vertically
Figure 176. With cover transitions the source form stays in place as it’s covered by the destination. This transition can be played both horizontally and vertically
Uncover is the inverse of cover. The destination form stays in place while the departing form moves away
Figure 177. Uncover is the inverse of cover. The destination form stays in place while the departing form moves away

12.4.3. Fade and flip transitions

The fade transition is pretty trivial and accepts a time value since it has no directional context.

Fade transition is probably the simplest one around
Figure 178. Fade transition is probably the simplest one around

The FlipTransition is also pretty simple but unlike the others it isn’t a part of the CommonTransitions. It has its own FlipTransition class.

This transition looks different on devices as it uses native perspective transforms available there
Fade transition is probably the simplest one around
Figure 179. Fade transition is probably the simplest one around

12.4.4. Bubble transition

BubbleTransition morphs a component into another component using a circular growth motion.

The BubbleTransition accepts the component that will grow into the bubble effect as one of its arguments. It’s primarily designed for Dialog transitions although it could work for more creative use cases:

The code below manipulates styles and look. This is done to make the code more "self contained." Real world code should probably use the theme
    Form hi = new Form("Bubble");
    Button showBubble = new Button("+");
    showBubble.setName("BubbleButton");
    Style buttonStyle = showBubble.getAllStyles();
    buttonStyle.setBorder(Border.createEmpty());
    buttonStyle.setFgColor(0xffffff);
    buttonStyle.setBgPainter((g, rect) -> {
        g.setColor(0xff);
        int actualWidth = rect.getWidth();
        int actualHeight = rect.getHeight();
        int xPos, yPos;
        int size;
        if(actualWidth > actualHeight) {
            yPos = rect.getY();
            xPos = rect.getX() + (actualWidth - actualHeight) / 2;
            size = actualHeight;
        } else {
            yPos = rect.getY() + (actualHeight - actualWidth) / 2;
            xPos = rect.getX();
            size = actualWidth;
        }
        g.setAntiAliased(true);
        g.fillArc(xPos, yPos, size, size, 0, 360);
    });
    hi.add(showBubble);
    hi.setTintColor(0);
    showBubble.addActionListener((e) -> {
        Dialog dlg = new Dialog("Bubbled");
        dlg.setLayout(new BorderLayout());
        SpanLabel sl = new SpanLabel("This dialog should appear with a bubble transition from the button", "DialogBody");
        sl.getTextUnselectedStyle().setFgColor(0xffffff);
        dlg.add(BorderLayout.CENTER, sl);
        dlg.setTransitionInAnimator(new BubbleTransition(500, "BubbleButton"));
        dlg.setTransitionOutAnimator(new BubbleTransition(500, "BubbleButton"));
        dlg.setDisposeWhenPointerOutOfBounds(true);
        dlg.getTitleStyle().setFgColor(0xffffff);

        Style dlgStyle = dlg.getDialogStyle();
        dlgStyle.setBorder(Border.createEmpty());
        dlgStyle.setBgColor(0xff);
        dlgStyle.setBgTransparency(0xff);
        dlg.showPacked(BorderLayout.NORTH, true);
    });

    hi.show();
Bubble transition converting a circular button to a Dialog
Figure 180. Bubble transition converting a circular button to a Dialog

12.4.5. Morph transitions

Android’s material design has a morphing effect where an element from the previous form (activity) animates into a different component on a new activity. Codename One has a morph effect in the Container class but it doesn’t work as a transition between forms and doesn’t allow for multiple separate components to transition at once.

Morph Transition
Figure 181. Morph Transition

To support this behavior you have the MorphTransition class that provides this same effect coupled with a fade to the rest of the UI (see Figure 181, “Morph Transition”).

Since the transition is created before the form exists you can’t reference explicit components within the form when creating the morph transition (to show which component becomes which) so you need to refer to them by name. This means you need to use setName(String) on the components in the source/destination forms so the transition will be able to find them:

Form demoForm = new Form(currentDemo.getDisplayName());
demoForm.setScrollable(false);
demoForm.setLayout(new BorderLayout());
Label demoLabel = new Label(currentDemo.getDisplayName());
demoLabel.setIcon(currentDemo.getDemoIcon());
demoLabel.setName("DemoLabel");
demoForm.addComponent(BorderLayout.NORTH, demoLabel);
demoForm.addComponent(BorderLayout.CENTER, wrapInShelves(n));
// ...
demoForm.setBackCommand(backCommand);
demoForm.setTransitionOutAnimator(
    MorphTransition.create(3000).morph(
        currentDemo.getDisplayName(),
        "DemoLabel"));
f.setTransitionOutAnimator(
    MorphTransition.create(3000).
        morph(currentDemo.getDisplayName(),
        "DemoLabel"));
demoForm.show();
Snapshot mode

By default MorphTransition paints both endpoints by re-rendering the live source / destination components every frame at the interpolated bounds. That works well when the source is fully visible — a card in the body of one form morphing to a card in the next.

It runs into edge cases when the source lives inside a scrolling container that has children extending past the source’s bounds, or when the source has dynamic content (a video frame, a BrowserComponent, a custom-painted background) that should be visually frozen for the duration of the animation. The legacy live-paint path can leak off-viewport pixels into the morph because the layered pane that holds the source during the animation doesn’t carry the original parent’s clip.

To opt into the image-snapshot path call snapshotMode(true) on the builder:

MorphTransition morph = MorphTransition.create(300)
        .snapshotMode(true)
        .morph("card");
nextForm.setTransitionInAnimator(morph);
nextForm.show();

snapshotMode(true) captures each (source, dest) pair as a clipped Image at initTransition(), then the tween draws those images at the interpolated bounds rather than re-painting the live components. Off-viewport children of the source are clipped at capture time (the image’s own bounds are the clip), so they can’t leak into the morph.

The default MorphTransition behavior (live paint, no snapshots) is unchanged for back-compat. Use snapshot mode opportunistically when the live-paint output exhibits the off-viewport leak, or when the source’s children produce frame-by-frame visual change you want to freeze.

12.4.6. SwipeBackSupport

iOS7+ allows swiping back one form to the previous form, Codename One has an API to enable back swipe transition:

SwipeBackSupport.bindBack(currentForm, destination);

That one command will enable swiping back from currentForm. LazyValue allows you to pass a value lazily:

/**
 * Useful when passing a value that might not exist to a function, e.g. When we
 * pass a form that we might need to construct dynamically later on.
 */
public interface LazyValue<T> {
    /**
     * Returns the actual value.
     *
     * @param args optional arguments for the creation of the lazy value
     * @return the value
     */
    T get(Object... args);
}

This effectively allows you to pass a form and create it as necessary (for example, for a GUI builder app you don’t have the actual previous form instance), notice that the arguments aren’t used for this case but will be used in other cases.

The code below should work for the transition sample above. Notice that this API was designed to work with "Slide Fade" transition and might have issues with other transition types:

SwipeBackSupport.bindBack(dest, (args) -> hi);

Theming and styling

13. Advanced theming

Before getting into CSS, this section introduces a few advanced theme concepts. Those ideas also apply to CSS because CSS uses features such as theme constants.

13.1. Working with UIIDs

A UIID (User Interface Identifier) uniquely identifies a group of theme definitions for UI components. For example, a Button UIID can be linked to a component, and the theme can then define that component’s appearance.

A major advantage of UIIDs is the ability to change a component’s UIID. For example, to create a multiline label, use code like this:

TextArea t = new TextArea(); // ...
t.setUIID("Label");
t.setEditable(false);
Components such as SpanLabel use this approach internally.

UIIDs can be customized in the GUI builder and support per-component styling.

The component class name often matches the UIID, but the two remain separate entities.

Looking a UIID up isn’t a single lookup. The state, the appearance and any derive chain each get a turn before the default style is reached:

The order UIManager searches to resolve a UIID into a Style
Figure 182. The order UIManager searches when a component asks for its style

13.2. Theme layering

Theme layering helps in two common cases:

  • A platform needs a slightly different theme.

  • A specific use case needs theme customization. For example, a user might select larger fonts.

Theme layering is straightforward and doesn’t require rebuilding the entire theme. A theme can be applied on top of another theme, like CSS cascading. To create a layer, add a new theme with the Add Theme button.

Remove the includeNativeBool constant from the new theme.

In the new theme, define the changes you need. For example, to use a larger default font, define that property for the relevant UIIDs and leave the other properties unchanged.

In a non-GUI-builder app, the theme loading code looks like this by default:

Resources theme = UIManager.initFirstTheme("/theme");

Update it to look like this:

Resources theme = UIManager.initNamedTheme("/theme", "Theme");
This example assumes that the main theme is named Theme, not the layer theme that was added.

The original code relies on the theme being at position 0 in the theme name array. That might not always be true.

To add the theme layer, use:

UIManager.getInstance().addThemeProps(theme.getTheme("NameOfLayerTheme"));

The addThemeProps call places the secondary theme on top of the primary "Theme" and keeps the original UIIDs in "Theme" intact.

To apply theme changes to a running application, call Form’s `refreshTheme(). This updates the UI and provides visual feedback for the theme changes.

13.3. Override resources in platform

When you adapt an application to different OS conventions, one common need is to use different icons. Sometimes you also need to change behavior based on device type, for example to use a different UI structure for a tablet.

Codename One lets you override a resource for a specific platform. You can redefine a resource for that platform and add platform-specific resources.

Override resources for specific platform
Figure 183. Override resources for specific platform

Overridden resources take precedence over embedded resources, which lets you change the look or even behavior for a specific platform or OS.

Overriding the theme is dangerous because a theme has external dependencies, such as image borders. The solution is to use theme layering and override the layer.

To override a resource, select the platform where the override applies.

Override for platform, allows you to override the checked resources and replace them with another resource
Figure 184. Override for platform, allows you to override the checked resources and replace them with another resource

You can then click the green checkbox to mark that resource as specific to this platform. All resources added while that platform is selected apply to that platform. If you change your mind, delete the override in override mode and it will stop applying.

13.4. Theme constants

The Codename One Designer has a tab for creating constants. These constants can add global values and behavior hints to Codename One and its components. Constants are always strings. Some conventions let the UI adapt to input types. For example, a constant that ends with Bool is treated as a boolean value and displays as a checkbox. An Int suffix displays a numeric picker, and an Image suffix shows a combo box for picking an image.

The combo box in the designer for adding a theme constant is editable, so you can type any value you want.

To use a constant, call the appropriate UIManager methods:

  • getThemeConstant

  • isThemeConstant

  • getThemeImageConstant

Internally, Codename One has many built-in constants, and the list keeps growing. As features are added, the list is updated, but theme constants are inherently ad hoc and some may not appear here.

Table 6. Theme Constants
ConstantDescription/Argument

alwaysTensileBool

Enables tensile drag even when there is no scrolling in the container (only for scrollable containers)

backGestureThresholdInt

The threshold for the back gesture in the SwipeBackSupport class, defaults to 5

backUsesTitleBool

Indicates to the GUI builder that the back command should use the title of the previous form and not just the word "Back"

buttonRippleBool

true to activate the material design ripple effect on the buttons. This effect draws a growing circle from the point of touch onwards. This is false by default except for Android where it defaults to true. This is equivalent to setButtonRippleEffectDefault(bool) in the Button class

capsButtonTextBool

true to activate the caps text mode in the buttons. When activated setText on Button and all the constructors will invoke upcase() on all the strings effectively making the application buttons use uppercase exclusively. This is false by default except for Android where it defaults to true. It’s equivalent to Button.setCapsTextDefault(boolean) and can be tuned to an individual Component via Component.setRippleEffect(boolean)

capsButtonUiids

A list of the UIID’s that should be capitalized by default (in supported platforms) other than the Button and RaisedButton which are already capitalized. This list can be separated by spaces or commas for example, capsButtonUiids=UpcaseButton,OtherCustomButton

defaultCommandImage

Image to give a command with no icon

defaultNativeWindowModeBool

true to back every newly created Dialog and InteractionDialog with a real operating system window on desktop platforms. Ignored where there is no windowing system, so it changes nothing on mobile or the web. Equivalent to Dialog.setDefaultNativeWindowMode(boolean), and overridden for one dialog by setNativeWindowMode(boolean)

dialogButtonCommandsBool

Place commands in the dialogs as buttons

dialogBlurRadiusInt

Sets the default Gaussian blur radius for the background of the dialogs. The default value is -1 indicating no blur

dialogPosition

Place the dialog in an arbitrary border layout position (for example, North, South, Center, etc.)

centeredPopupBool

Popup of the combo box will appear in the center of the screen

changeTabOnFocusBool

Useful for feature phones, allows changing the tab when the focus changes, without pressing a key

checkBoxCheckDisImage

CheckBox image to use instead of Codename One drawing it on its own

checkBoxCheckedImage

CheckBox image to use instead of Codename One drawing it on its own

checkBoxOppositeSideBool

Indicates the check box should be drawn on the opposite side to the text and not next to the text

checkBoxUncheckDisImage

CheckBox image to use instead of Codename One drawing it on its own

checkBoxUncheckedImage

CheckBox image to use instead of Codename One drawing it on its own

comboImage

Combo image to use instead of Codename One drawing it on its own

comboPopupMaxRowsInt

The most rows the popup of the combo box shows before it scrolls. A popup with a limit opens below or above the combo box and doesn’t cover it. Defaults to 10 on a desktop and to 0, which means no limit, on other platforms

commandBehavior

Deprecated: don’t use this constant as it conflicts with the Toolbar. Indicates how commands should act, as a touch menu, native menu etc. Possible values: SoftKey, Touch, Bar, Title, Right, Native

ComponentGroupBool

Enables component group, which allows components to be logically grouped together, so the UIID’s of components would be modified based on their group placement. This allows for some unique styling effects where the first/last elements have different styles from the rest of the elements. It’s disabled by default, thus leaving its usage up to the designer

dialogTransitionIn

Default transition for dialog

dialogTransitionInImage

Default transition Image for dialog, causes a Timeline transition effect

dialogTransitionOut

Default transition for dialog

defaultCommandImage

An image to place on a command if none is defined, only applies to touch commands

defaultEmblemImage

The emblem painted on the side of the multibutton, by default this is an arrow on some platforms

emblemUiid

Overrides the UIID applied to emblem labels rendered by composite buttons such as MultiButton and SpanMultiButton.

iconUiid

Allows theming the icon component used by SpanLabel, SpanButton, MultiButton, and SpanMultiButton when they fetch icon styling via theme constants.

iosScrollMotionBool

Enables iOS-style scroll physics (nonlinear rubber-band during drag and critically damped tensile snap-back). When unset it defaults to true on the iOS platform and false elsewhere. Set explicitly to override the platform default. See Section 13.4.1, “Scroll motion tuning”

imageviewerNavigationArrowsBool

Enables side navigation arrows by default for ImageViewer instances using the ImageViewer UIID (or a lowercased custom UIID prefix).

imageviewerThumbnailBarHeightMM

Sets the default thumbnail strip height (in millimeters) for ImageViewer navigation thumbnails.

imageviewerThumbnailsBool

Enables the bottom thumbnail strip by default for ImageViewer instances using the ImageViewer UIID (or a lowercased custom UIID prefix).

textUiid

Overrides the text component UIID for SpanLabel, SpanButton, MultiButton, and SpanMultiButton instances when provided as a theme constant.

useLargerTextScaleBool

When true, UIManager applies the larger text accessibility scale from Display.getLargerTextScale() when Display.isLargerTextEnabled() is enabled.

dialogTransitionOutImage

Default transition Image for dialog, causes a Timeline transition effect

DecayMotionScaleFactorInt

Velocity-to-distance multiplier for the exponential-decay scroll motion (see Section 13.4.1, “Scroll motion tuning”). Default is 950. Larger values make flicks travel farther for the same release velocity

disabledColor

Color to use when disabling entries by default

dlgButtonCommandUIID

The UIID used for dialog button commands

dlgCommandButtonSizeInt

Minimum size to give to command buttons in the dialog

dlgCommandGridBool

Places the dialog commands in a grid for uniform sizes

dlgInvisibleButtons

Includes an RRGGBB color for the line separating dialog buttons, as is the case with Android 4 and iOS 7 buttons in dialogs

dlgSlideDirection

Slide hints

dlgSlideInDirBool

Slide hints

dlgSlideOutDirBool

Slide hints

drawMapPointerBool

Indicates whether a pointer should appear in the center of the map component

fadeScrollBarBool

Boolean indicating if the scrollbar should fade when there is inactivity

setFadeScrollBarSpeed(int) (API)

Sets the per-frame opacity decrement for scrollbar fading (not milliseconds). Approximate fade duration is durationMs ~= (255 / speed) * (1000 / frameRate). At 60 FPS: speed 5 ~= 850ms, 3 ~= 1400ms, 2 ~= 2100ms, 1 ~= 4250ms

fadeScrollEdgeBool

Places a fade effect at the edges of the screen to show that it’s possible to scroll until you reach the edge (common on Android)

fadeScrollEdgeInt

Amount of pixels to fade out at the edge

firstCharRTLBool

Indicates to the GenericListCellRenderer that it should determine RTL status based on the first character in the sentence

noTextModeBool

Indicates that the on/off switch in iOS shouldn’t draw text on top of the switch, which is the case for iOS 7+ but not for prior versions

fixedSelectionInt

Number corresponding to the fixed selection constants in List

formTransitionIn

Default transition for form

formTransitionInImage

Default transition Image for form, causes a Timeline transition effect

formTransitionOut

Default transition for form

formTransitionOutImage

Default transition Image for form, causes a Timeline transition effect

globalToobarBool

Indicates that the Toolbar API should be on/off by default for all forms

hasRaisedButtonBool

Is true in platforms where the theme has the RaisedButton UIID defined. This is only true in the native Android theme to allow some material design guidelines

hideBackCommandBool

Hides the back command from the side menu when possible

hideEmptyTitleBool

Indicates that a title with no content should be hidden even if the border for the title occupies space

hideLeftSideMenuBool

Hides the side menu icon that appears on the left side of the UI

hideRightSideMenuBool

Hides the toolbar menu icon that appears on the right side of the title area

ignorListFocusBool

Hide the focus component of the list when the list doesn’t have focus

infiniteImage

The image used by the infinite progress component, the component will rotate it as needed

infiniteMaterialDesignSize

Size (in millimeters) of the generated material design spinner when InfiniteProgress runs in material mode. Defaults to 6.667mm

infiniteMaterialImageSize

Size (in millimeters) of the generated spinner image when no custom infiniteImage is provided. Defaults to 7mm

infiniteDefaultColor

Hex RGB color used for the autogenerated material spinner when infiniteImage isn’t supplied. Defaults to 777777

interactionDialogSpeedInt

Controls the duration in milliseconds that InteractionDialog uses when animating into and out of the layered pane (including the directional dispose helpers). Defaults to 400 if the constant isn’t defined.

includeNativeBool

True to derive from the platform native theme, false to create a blank theme that only uses the basic defaults

labelGap

Positive floating point value representing the default gap value between the label text and the icon in millimeters

listItemGapInt

Built-in item gap in the list, this defaults to 2, which predated padding/margin in Codename One

listLongPressBool

Indicates whether a list should handle long press events, defaults to true

mapTileLoadingImage

An image to preview while loading the MapComponent tile

mapTileLoadingText

The text of the tiles in the MapComponent during loading, defaults to "Loading…​"

mapZoomButtonsBool

Indicates whether buttons should be drawn on the map component

mediaBackImage

Media icon used by the media player class

mediaFwdImage

Media icon used by the media player class

mediaPauseImage

Media icon used by the media player class

mediaPlayImage

Media icon used by the media player class

menuButtonBottomBool

When set to true this flag aligns the menu button to the bottom portion of the title. Defaults to false

menuButtonTopBool

When set to true this flag aligns the menu button to the top portion of the title. Defaults to false

landscapeTitleUiidBool

When true the toolbar swaps to landscape-specific UIIDs (such as ToolbarLandscape/BackCommandLandscape) for layout and icon styling

menuHeightPercent

Allows positioning and sizing the menu

menuImage

The three dot menu image used in Android and the Toolbar to show more command entries

menuImageSize

The size in millimeters (floating point value) of the generated side menu image, this is only used if you don’t supply a custom image. The default value is 4.5.

menuPrefSizeBool

Allows positioning and sizing the menu

menuSlideDirection

Defines menu entrance effect

menuSlideInDirBool

Defines menu entrance effect

menuSlideOutDirBool

Defines menu entrance effect

menuTransitionIn

Defines menu entrance effect

menuTransitionInImage

Defines menu entrance effect

menuTransitionOut

Defines menu exit effect

menuTransitionOutImage

Defines menu entrance effect

menuWidthPercent

Allows positioning and sizing the menu

iosStyleBackArrowBool

Renders the back command using the iOS-style chevron arrow (with a small icon gap) when the toolbar shows back text

minimizeOnBackBool

Indicates whether the form should minimize the entire application when the physical back button is pressed (if available) and no command is defined as the back command. Defaults to true

onOffIOSModeBool

Indicates whether the on/off switch should use the iOS or Android mode

otherPopupRendererBool

Indicates that a separate renderer UIID/instance should be used to the list within the combo box popup

PackTouchMenuBool

Enables preferred sized packing of the touch menu (true by default), when set to false this allows manually determining the touch menu size using percentages

paintsTitleBarBool

Indicates that the StatusBar UIID should be added to the top of the form to space down the title area, as is the case on iOS 7+ where the status bar is painted on top of the UI

rightSideMenuImage

Overrides the default icon used for the right-side toolbar menu button

rightSideMenuPressImage

Optional pressed-state icon for the right-side toolbar menu button

popupCancelBodyBool

Indicates that a cancel button should appear within the combo box popup

PopupDialogArrowBool

Indicates whether the popup dialog has an arrow, notice that this constant will change if you change UIID of the popup dialog

PopupDialogArrowBottomImage

Image of the popup dialog arrow, notice that this constant will change if you change UIID of the popup dialog

PopupDialogArrowTopImage

Image of the popup dialog arrow, notice that this constant will change if you change UIID of the popup dialog

PopupDialogArrowLeftImage

Image of the popup dialog arrow, notice that this constant will change if you change UIID of the popup dialog

PopupDialogArrowRightImage

Image of the popup dialog arrow, notice that this constant will change if you change UIID of the popup dialog

popupNoTitleAddPaddingInt

Adds padding to a popup when no title is present

popupTitleBool

Indicates that a title should appear within the combo box popup

pullToRefreshImage

The arrow image used to draw the pullToRefresh animation

pureTouchBool

Indicates the pure touch mode

radioOppositeSideBool

Indicates the radio button should be drawn on the opposite side to the text and not next to the text

radioSelectedDisImage

Radio button image

radioSelectedImage

Radio button image

radioUnselectedDisImage

Radio button image

radioUnselectedImage

Radio button image

radioSelectedDisFocusImage

Radio button image

radioSelectedFocusImage

Radio button image

radioUnselectedDisFocusImage

Radio button image

radioUnselectedFocusImage

Radio button image

releaseRadiusInt

Indicates the distance from the button with dragging, in which the button should be released, defaults to 0

rendererShowsNumbersBool

Indicates whether renderers should render the entry number

reverseSoftButtonsBool

Swaps the softbutton positions

rightSideMenuImage

Same as sideMenuImage only for the right side, optional and defaults to sideMenuImage

rightSideMenuPressImage

Same as sideMenuPressImage only for the right side, optional and defaults to sideMenuPressImage

rubberBandCoefficientInt

Resistance coefficient for the iOS-style rubber-band compression used while the finger drags past a scroll edge. Value is interpreted as hundredths, so 55 means 0.55 (the iOS reference value). Larger values let the content be pulled farther for the same finger travel; smaller values make the content feel stiffer. Only active when iosScrollMotionBool is true. See Section 13.4.1, “Scroll motion tuning”

ScrollMotion

Selects the post-release flick model. DECAY (default) uses exponential velocity decay controlled by ScrollMotionTimeConstantInt and DecayMotionScaleFactorInt. Any other value (for example, FRICTION) falls back to the linear-friction model. See Section 13.4.1, “Scroll motion tuning”

ScrollMotionTimeConstantInt

Time constant in milliseconds for the exponential-decay flick model (active when ScrollMotion=DECAY). Default is 500. Smaller values stop the flick sooner

scrollVisibleBool

true/false default is platform dependent. Toggles whether the scroll bar is visible

showBackCommandOnTitleBool

Used by the Toolbar API to show whether the back button should appear on the title

shrinkPopupTitleBool

Indicates the title of the popup should be set to 0 if it’s missing

sideMenuAnimSpeedInt

The speed at which a sidemenu moves defaults to 300 milliseconds

sideMenuFoldedSwipeBool

Indicates the side menu could be opened via swiping

sideMenuImage

The image representing the side menu, three lines (Hamburger menu)

sideMenuPressImage

Optional pressed version of the sideMenuImage

sideMenuScrollVisibleBool

Indicates whether the scroll bar on the side menu should be visible or not, defaults to hidden

sideMenuShadowBool

Indicates whether the shadow for the side menu should be drawn

sideMenuShadowImage

The image used when drawing the shadow (a default is used if this isn’t supplied)

sideMenuSizeTabPortraitInt

The size of the side menu when expanded in a tablet in portrait mode

sideMenuSizePortraitInt

The size of the side menu when expanded in a phone in portrait mode

sideMenuSizeTabLandscapeInt

The size of the side menu when expanded in a tablet in landscape mode

sideMenuSizeLandscapeInt

The size of the side menu when expanded in a phone in landscape mode

sideMenuTensileDragBool

Enables/disables the tensile drag behavior within the opened side menu

sideSwipeActivationInt

Indicates the threshold in the side menu bar at which a swipe should trigger activation, defaults to 15 (percent)

sideSwipeSensitiveInt

Indicates the region of the screen that’s sensitive to side swipe in the side menu bar, defaults to 10 (percent)

sigButtonOKUIID

Defines the UIID applied to the confirmation button in the signature capture dialog (defaults to Button).

sigButtonResetUIID

Defines the UIID applied to the reset/clear button in the signature capture dialog (defaults to Button).

sigButtonCancelUIID

Defines the UIID applied to the cancel button in the signature capture dialog (defaults to Button).

slideDirection

Default slide transition settings

slideInDirBool

Default slide transition settings

slideOutDirBool

Default slide transition settings

sliderThumbImage

The thumb image that can appear on the sliders

snapGridBool

Snap to grid toggle

statusBarScrollsUpBool

Indicates that a tap on the status bar should scroll up the UI, only relevant in OSes where paintsTitleBarBool is true

switchButtonPadInt

Indicates the padding in the on/off switch, defaults to 16

switchMaskImage

Indicates the mask image used in iOS mode to draw on top of the switch

switchOnImage

Indicates the on image used in iOS mode to draw the on/off switch

switchOffImage

Indicates the off image used in iOS mode to draw the on/off switch

TabEnableAutoImageBool

Indicates images should be filled by default for tabs

TabSelectedImage

Default selected image for tabs (if TabEnableAutoImageBool=true)

TabUnselectedImage

Default unselected image for tabs (if TabEnableAutoImageBool=true)

tabPlacementInt

The placement of the tabs in the Tabs component: TOP = 0, LEFT = 1, BOTTOM = 2, RIGHT = 3

tabsSlideSpeedInt

The time of the animation that occurs (in milliseconds) between releasing a swiped tab and reaching the next tab. Defaults to 200

tabsFillRowsBool

Indicates if the tabs should fill the row using flow layout

tabsGridBool

Indicates whether tabs should use a grid layout thus forcing all tabs to have identical sizes

tabsOnTopBool

Indicates the tabs should be drawn on top of their content in a layered UI, this allows a tab to intrude into the content of the tabs

textCmpVAlignInt

The vertical alignment of the text component: TOP = 0, CENTER = 4, BOTTOM = 2

textComponentErrorColor

A hex RGB color which defaults to null in which case this has no effect. When defined this will change the color of the border and label to the given color to match the material design styling. This implements the red border underline in cases of error and the label text color change

textComponentOnTopBool

Toggles the on top mode which makes things look like they do on Android. This defaults to true on Android and false on other OSes. This can also be manipulated via the onTopMode(boolean) method in InputComponent, but the layout will only use the theme constant

textComponentAnimBool

toggles the animation mode which again can be manipulated by a method in InputComponent. If you want to keep the UI static without the floating hint effect set this to false. Notice this defaults to true only on Android

textComponentFieldUIID

sets the UIID of the text field to something other than TextField this is useful for platforms such as iOS where the look of the text field is different within the text component. This allows you to make the background of the text field transparent when it’s within the TextComponent and make it different from the regular text field

textFieldCursorColorInt

The color of the cursor as an integer (not hex)

tickerSpeedInt

The speed of label/button etc. (in milliseconds)

tintColor

The aarrggbb hex color to tint the screen when a dialog is shown

topMenuSizeTabPortraitInt

The size of the side menu when expanded and attached to the top in a tablet in portrait mode

topMenuSizePortraitInt

The size of the side menu when expanded and attached to the top in a phone in portrait mode

topMenuSizeTabLandscapeInt

The size of the side menu when expanded and attached to the top in a tablet in landscape mode

topMenuSizeLandscapeInt

The size of the side menu when expanded and attached to the top in a phone in landscape mode

touchCommandFillBool

Indicates how the touch menu should lay out the commands within

touchCommandFlowBool

Indicates how the touch menu should lay out the commands within

transitionSpeedInt

Indicates the default speed for transitions

treeFolderImage

Picture of a folder for the Tree class

treeFolderOpenImage

Picture of a folder expanded for the Tree class

treeNodeImage

Picture of a file node for the Tree class

tensileDragBool

Indicates that tensile drag should be enabled/disabled. This is set by platform themes

tensileSnapMinDurationInt

Minimum duration in milliseconds for the tensile snap-back animation when the finger is released past a scroll edge. Defaults to 400 when iosScrollMotionBool is true and 300 otherwise. The actual duration scales with the distance being snapped; this is only a floor

tensileSnapMotion

Motion curve used for the tensile snap-back. SPRING (the default when iosScrollMotionBool is true) applies a critically damped spring envelope that settles softly. DECELERATION (the default elsewhere) applies the legacy quadratic ease-out. See Section 13.4.1, “Scroll motion tuning”

13.4.1. Scroll motion tuning

Scroll feel is controlled by three stages, each tunable via theme constants:

  1. While the finger is dragging past an edge--when iosScrollMotionBool is true, the over-edge distance is compressed by the iOS UIScrollView rubber-band function c * d * dim / (c * d + dim), where d is the raw finger displacement past the edge, dim is the viewport dimension, and c is rubberBandCoefficientInt / 100 (default 0.55). The result is that the content feels heavier the farther you pull it, asymptotically approaching dim. When iosScrollMotionBool is false, the legacy behavior is used: a linear 1:1 follow clamped to tensileLength.

  2. After the finger is lifted, while there is still velocity--the ScrollMotion constant selects the model. DECAY (default) uses exponential velocity decay with a time constant of ScrollMotionTimeConstantInt milliseconds and a distance scale of DecayMotionScaleFactorInt. Any other value (for example, FRICTION) falls back to linear friction.

  3. When the scroll comes to rest past an edge--a tensile snap-back animates the content back to the edge. tensileSnapMotion picks the curve: SPRING is a critically damped envelope (iOS-like soft settle) and DECELERATION is the legacy quadratic ease-out. The duration scales with distance but never falls below tensileSnapMinDurationInt milliseconds.

    iosScrollMotionBool is the single switch that flips stage 1 and the default of stage 3 to the iOS-matching behavior. It defaults to true on the iOS platform only. Every individual constant can still be overridden regardless of this switch, so you can, for example, enable the nonlinear rubber-band globally (iosScrollMotionBool=true) while keeping the legacy quadratic snap-back (tensileSnapMotion=DECELERATION).

Tuning suggestions
  • To make scrolling feel stiffer on iOS (less pull), reduce rubberBandCoefficientInt from 55 toward 35.

  • To make flicks stop sooner, reduce ScrollMotionTimeConstantInt (default 500) or DecayMotionScaleFactorInt (default 950).

  • To enable iOS-style physics on Android or desktop for consistency, set iosScrollMotionBool=true explicitly.

  • To disable iOS physics on the simulator while debugging, set iosScrollMotionBool=false in your development theme.

Dynamic Theme Swapping & Theme Constants

Once a theme constant is set by a theme, it isn’t removed on a refresh when replacing the theme.

For example, if one would set the comboImage constant to a specific value in theme A and then switch to theme B, that doesn’t define the comboImage, the original theme A comboImage might remain!

The reason for this is simple: when extracting the constant values, components keep the values in cache locally and just don’t track the change in value. Furthermore, since the components allow manually setting values, it’s impractical for them to track whether a value was set by a constant or explicitly by the user.

The solution for this is to either manually reset undesired values before replacing a theme (for example, for the case, above by calling the default look and feel method for setting the combo image with a null value), or defining a constant value to replace the existing value.

13.5. Native theming

Codename One uses a theme constant called includeNativeBool, when that constant is set to true Codename One starts by loading the native theme first and then applying all the theme settings. This means your theme "derives" the style of the native theme first, like the cascading effect of CSS. Internally this is what the theme layering section covered.

By avoiding this flag you can create themes that look EXACTLY the same on all platforms.

If you avoid the native theming you might be on your own. A few small device oddities such as the iOS status bar are abstracted by native theming. Without it you will need to do everything from scratch

You can simulate different OS platforms by using the native theme menu option

The native theme menu option
Figure 185. The native theme menu option

Developers can pick the platform of their liking and see how the theme will appear in that particular platform by selecting it and having the preview update on the fly.

13.6. Under the hood of the theme engine

To truly understand a theme you need to understand what it is. Internally a theme is a Hashtable key/value pair between UIID based keys and their respective values. For example: the key:

return "Button.fgColor=ffffff";

Will set the foreground color of the Button UIID to white.

When a Codename One Component is instantiated it requests a Style object from the UIManager class. The Style object is based on the settings within the theme and can be modified through code or by using the theme.

You can replace the theme dynamically in runtime and refresh the styles assigned to the various components using the refreshTheme() method.

It’s a common mistake to invoke refreshTheme() without actually changing the theme. You see developers doing it when all they need is a repaint() or revalidate(). Since refreshTheme() is ** expensive recommend that you don’t use it unless you need to…​

A theme Hashtable key comprises:

[UIID.][type#]attribute

The UIID, corresponds to the component’s UIID for example: Button, CheckBox etc. It’s optional and may be omitted to address the global default style.

The type is omitted for the default unselected type, and may be one of sel (selected type), dis (disabled type) or press (pressed type). The attribute should be one of:

  • derive - the value for this attribute should be a string representing the base component.

  • bgColor - represents the background color for the component, if applicable, in a web hex string format RRGGBB for example: ff0000 for red.

  • fgColor - represents the foreground color, if applicable.

  • border - an instance of the border class, used to display the border for the component.

  • bgImage - an Image object used in the background of a component.

  • transparency - a String containing a number between 0-255 representing the alpha value for the background. This applies to the bgColor.

  • margin - the margin of the component as a String containing 4 comma separated numbers for top, bottom, left, right.

  • padding - the padding of the component, it has an identical format to the margin attribute.

  • font - A Font object instance.

  • alignment - an Integer object containing the LEFT/RIGHT/CENTER constant values defined in Component.

  • textDecoration - an Integer value containing one of the TEXT_DECORATION_* constant values defined in Style.

  • backgroundType - a Byte object containing one of the constants for the background type defined in Style under BACKGROUND_*.

  • backgroundGradient - contains an Object array containing 2 integers for the colors of the gradient. If the gradient is radial it contains 3 floating points defining the x, y & size of the gradient.

To set the foreground color of a selected button to red, a theme will define a property like:

Button.sel#fgColor=ff0000

This information is useful for understanding how things work within Codename One, but it can also be useful in runtime.

For example: to increase the size of all fonts in the application, you can do something like:

Hashtable h = new Hashtable();
h.put("font", largeFont);
UIManager.getInstance().addThemeProps(h);
Display.getInstance().getCurrent().refreshTheme();

13.7. Understanding images and Multi-Images

This section provides a high-level overview of images. You dive deeper into the various types of images in the graphics section.

When working with a theme, you often use images for borders or backgrounds. You also use images within the GUI for various purposes and most such images will be extracted from the resource file.

Adding a standard JPEG/PNG image to the resource file is straight forward, and the resulting image can be viewed within the images section. For example, due to the wide difference between device types, an image that would be appropriate in size for an iPhone 3gs would not be appropriate in size for a Nexus device or an iPhone 4 (but perhaps, it will be right for iPad 1 and iPad 2).

The density of the devices varies and Codename One tries to simplify the process by unifying everything into one set of values to show density. For simplicity’s sake, density is sometimes expressed in pixels, but it’s mapped internally to actual screen measurements where possible.

A multi-image is an image that has many varieties for different densities, and thus looks sharp in all the densities. Since scaling on the device can’t interpolate the data (due to performance considerations), significant scaling on the device becomes impractical. For example, a multi-image will provide the "right" resolution image for the given device type.

From the programming perspective this is seamless, a developer accesses one image and has no ability to access the images in the different resolutions. Within the designer, but, you can explicitly define images for many resolutions and perform high quality scaling so the "right" image is available.

You can use two basic methods to add a multi-image: quick add and standard add.

Both methods rely on understanding the source resolution of the image, for example: if you have an icon that you expect to be 128×128 pixels on iPhone 4, 102×102 on nexus one and 64×64 on iPhone 3gs. You can provide the source image as the 128 pixel image and perform a quick add option while picking the # High# density option.

This will show to the algorithm that your source image is designed for the " high" density and it will scale for the rest of the densities accordingly.

This relies on the common use case of asking your designer to design for one high end device (for example: iPhone X) then you can take the resources and add them as "HD" resources. They will automatically adapt to the lower resolutions

Or, you can use the standard add multi-image dialog and set it like this:

Multi-image resolution dialog

Notice that you selected the square image option, essentially eliminating the height option. Setting values to 0 prevents the system from generating a multi-image entry for that resolution, which will mean a device in that category will fall on the closest alternative.

The percentage value will change the entire column, and it means the percentage of the screen. For example: You know the icon is 128 for the high resolution, you can move the percentage until you reach something close to 128 in the " High" row and the other rows will represent a size that should be pretty close in physical size to the 128 figure.

At runtime, you can always find the host device’s approximate pixel density using the Display.getDeviceDensity() method. This will return one of:

Table 7. Densities

Constant

Density

Example Device

Display.DENSITY_VERY_LOW

~ 88 ppi

Display.DENSITY_LOW

~ 120 ppi

Android ldpi devices

Display.DENSITY_MEDIUM

~ 160 ppi

iPhone 3GS, iPad, Android mdpi devices

Display.DENSITY_HIGH

~ 240 ppi

Android hdpi devices

Display.DENSITY_VERY_HIGH

~ 320 ppi

iPhone 4, iPad Air 2, Android xhdpi devices

Display.DENSITY_HD

~ 540 ppi

iPhone 6+, Android xxhdpi devices

Display.DENSITY_560

~ 750 ppi

Android xxxhdpi devices

Density.DENSITY_2HD

~ 1000 ppi

Density.DENSITY_4K

~ 1250ppi

13.8. Use millimeters for Padding/Margin and font sizes

When configuring your styles, you should rarely use "Pixels" as the unit for padding, margins, font size, and border thickness because the results will be inconsistent on different densities. Instead, you should use millimeters for all non-zero units of measurement.

As you now understand the complexities of DPI it should be clear why this is important.

13.8.1. Fractions of millimeters

Sometimes millimeters don’t give you enough precision for what you want to do. The designer allows you to specify integer values for most units. For example, you can achieve more precise results when working directly in Java. The Display.convertToPixels() method will allow you to convert millimeters (or DIPS) to pixels. It also takes an integer input, but you can use it to get a multiplier that you can then use to convert any millimeter value you want into pixels.

For example:

double pixelsPerMM = ((double) Display.getInstance().convertToPixels(10, true)) / 10.0;

And now you can set the padding on an element to 1.5mm. For example:

myButton.getAllStyles().setPaddingUnit(Style.UNIT_TYPE_PIXELS);
int pixels = (int) (1.5 * pixelsPerMM);
myButton.getAllStyles().setPadding(pixels, pixels, pixels, pixels);

13.9. Creating a great looking side menu

Side Menu final result
Figure 186. Side Menu final result

A side menu is a crucial piece of an elegant application. You will explain how one creates a simple side menu that’s elegant, portable and easy to build. This is a good "starting point" side menu from which you can build more elaborate designs.

To get this result you will start from a native theme and a bare-bones application to keep things simple.

The code for the side menu is this:

Form hi = new Form("Hi World");

Toolbar tb = hi.getToolbar();
Image icon = theme.getImage("icon.png"); (1)
Container topBar = BorderLayout.east(new Label(icon));
topBar.add(BorderLayout.SOUTH, new Label("Cool App Tagline...", "SidemenuTagline")); (2)
topBar.setUIID("SideCommand");
tb.addComponentToSideMenu(topBar);

tb.addMaterialCommandToSideMenu("Home", FontImage.MATERIAL_HOME, e -> {}); (3)
tb.addMaterialCommandToSideMenu("Website", FontImage.MATERIAL_WEB, e -> {});
tb.addMaterialCommandToSideMenu("Settings", FontImage.MATERIAL_SETTINGS, e -> {});
tb.addMaterialCommandToSideMenu("About", FontImage.MATERIAL_INFO, e -> {});

hi.addComponent(new Label("Hi World"));
hi.show();
1This is the icon which was used instead of a logo it appears in the top right of the side menu
2This is the top bar containing the tagline and the icon it’s styled as if it’s a command but you can put anything here for example: an image etc.
3The commands are added as usual to the side menu with no styling or functionality, the entire look is determined by the theme

Next you will open the designer tool to style the UI

Open the side menu so you will get the right values in the combo box on add
Figure 187. Open the side menu so you will get the right values in the combo box on add

Now when you press Add the side menu entries will appear in the combo box (you can type them but this is more convenient). You will start with the SideNavigationPanel style:

The SideNavigationPanel has an opaque white background
Figure 188. The SideNavigationPanel has an opaque white background

The SideCommand style is a bit more elaborate, you start with a white foreground and an opaque bluish/purple color:

The SideCommand has a white foreground and opaque bluish background
Figure 189. The SideCommand has a white foreground and opaque bluish background

You will set padding to 3 millimeters which provides everything a good feel and spacing. This is important for finger touch sensitivity.

Padding is 3mm so it will feel spacious and touch friendly
Figure 190. Padding is 3mm so it will feel spacious and touch friendly

You will set margin to 0 except for the bottom one pixel which will leave a nice white line by showing off the background. This means the commands will have a space between them and the white style you gave to the SideNavigationPanel will appear through that space.

Margin is 0 except for a thin line below each command
Figure 191. Margin is 0 except for a thin line below each command

Setting the border to empty is crucial!

The iOS version of the side command inherits a border style so you must "remove" it by defining a different border in this case an empty border. Since borders take precedence over color this would have prevented the color changes you made from appearing.

Border must be defined as Empty
Figure 192. Border must be defined as Empty

Next you need to pick a good looking font and make sure it’s large enough. You use millimeters size it for all OS’s and override the derived text decoration which has a value in the iOS native theme so it can impact the final look.

Pick a good looking font for the side command
Figure 193. Pick a good looking font for the side command

Next you need to move to the selected tab and add a new side command entry that derives from the unselected version. You will pick a new color that’s slightly deeper and will make the selected style appear selected. You will also copy and paste this selected style to the pressed style.

Selected & Pressed SideCommand
Figure 194. Selected & Pressed SideCommand
Color for the Selected/Pressed SideCommand
Figure 195. Color for the Selected/Pressed SideCommand

The SidemenuTagline is a SideCommand style that was slightly adapted. You will remove the padding and margin because the whole section is wrapped in a side command and you don’t want double padding. You will leave 1mm padding at the top for a bit of spacing from the logo.

Padding of the SidemenuTagline
Figure 196. Padding of the SidemenuTagline

You will also update the font to a smaller size and italic styling so it will feel like a tagline.

Font for the SideMenuTagline is slightly smaller and italic
Figure 197. Font for the SideMenuTagline is slightly smaller and italic

The last change for the theme is for the StatusBarSideMenu UIID which is a spacing on the top of the sidemenu. This spacing is there for iOS devices which render the clock/battery/reception symbols on top of the app. You will set the padding to 0.

StatusBarSideMenu padding for the top of the side menu
Figure 198. StatusBarSideMenu padding for the top of the side menu

Finally, you will add the icon image (or a logo if you have it) into the theme as a multi image so you can use it within the side menu as a good looking logo. A large icon image works as a 2HD multi-image but you can use many strategies to get a fitting image for this spot.

Rounded images work well here, you can round images dynamically using masking

These steps produce the UI above as a side menu, they might seem like a long set of steps but each step is pretty simple as you walk through each one. This does show off the versatility and power of Codename One as a change to one step can create a radically different UI design.

13.10. From a design to a theme

A design usually arrives as a mock-up from someone who doesn’t write apps, and the work is the same whichever tool it came out of: decide which components and layout managers reproduce the structure, export the images you need at the densities you need, and then style it.

Sign up form design
Figure 199. Sign up form design

The structure is the part worth doing on paper first. Nesting containers to match the design, rather than positioning things absolutely, is what keeps it working across screen sizes and platforms:

Component hierarchy and layouts
Figure 200. Component hierarchy and layouts

Export the artwork the design needs before writing the code. This one needs three pieces: the header background, and the camera icon with the round button it sits on.

The header background
Figure 201. The header background
The camera icon
Figure 202. The camera icon
The button behind it
Figure 203. The button behind it

Only images a stylesheet names reach the compiled theme, and the camera pieces are fetched by name at runtime rather than used as a background, so the theme below carries a selector that exists purely to import them. Each is declared at its source density so the compiler produces a multi-image and every screen gets an appropriately sized file, which is what theme.getImage then returns.

That hierarchy is ordinary component code. The code below builds the form, starting with a separator the design uses between fields:

private Label createSeparator() {
    Label sep = new Label();
    sep.setUIID("Separator");
    // the separator line  is implemented in the theme using padding and background color, by default labels
    // are hidden when they have no content, this method disables that behavior
    sep.setShowEvenIfBlank(true);
    return sep;
}
if (current != null) {
    current.show();
    return;
}
// The toolbar uses the layered mode so it resides on top of the background image, the theme makes
// it transparent so we will see the image below it, we use border layout to place the background image on
// top and the "Get started" button in the south
Form psdTutorial = new Form("Signup", new BorderLayout());
Toolbar tb = new Toolbar(true);
psdTutorial.setToolbar(tb);

// we create 4mm material arrow images for the back button and the Get started button
Style iconStyle = psdTutorial.getUIManager().getComponentStyle("Title");
FontImage leftArrow = FontImage.createMaterial(FontImage.MATERIAL_ARROW_BACK, iconStyle, 4);
FontImage rightArrow = FontImage.createMaterial(FontImage.MATERIAL_ARROW_FORWARD, iconStyle, 4);

// we place the back and done commands in the toolbar, we need to change UIID of the "Done" command
// so we can color it in Red
tb.addCommandToLeftBar("", leftArrow, (e) -> Log.p("Back pressed"));
Command doneCommand = tb.addCommandToRightBar("Done", null, (e) -> Log.p("Done pressed"));
tb.findCommandComponent(doneCommand).setUIID("RedCommand");

// The camera button is comprised of 3 pieces. A label containing the image and the transparent button
// with the camera icon on top. This is all wrapped in the title container where the title background image
// is placed using the theme. We chose to use a Label rather than a background using the cameraLayer so
// the label will preserve the original size of the image without scaling it and take up the space it needs
Button cameraButton = new Button(theme.getImage("camera.png"));
Container cameraLayer = LayeredLayout.encloseIn(
        new Label(theme.getImage("camera-button.png")),
        cameraButton);
cameraButton.setUIID("CameraButton");
Container titleContainer = Container.encloseIn(
        new BorderLayout(BorderLayout.CENTER_BEHAVIOR_CENTER),
        cameraLayer, BorderLayout.CENTER);
titleContainer.setUIID("TitleContainer");

TextField firstName = new TextField("", "First Name");
TextField lastName = new TextField("", "Last Name");
TextField email = new TextField("", "Email Address", 20, TextField.EMAILADDR);
TextField password = new TextField("", "Choose a Password", 20, TextField.PASSWORD);
TextField phone = new TextField("", "Phone Number", 20, TextField.PHONENUMBER);
Label phonePrefix = new Label("+1");
phonePrefix.setUIID("TextField");

// The phone and full name have vertical separators, we use two table layouts to arrange them correctly
// so the vertical separator will be in the right place
TableLayout fullNameLayout = new TableLayout(1, 3);
Container fullName = new Container(fullNameLayout);
fullName.add(fullNameLayout.createConstraint().widthPercentage(49), firstName).
        add(fullNameLayout.createConstraint().widthPercentage(1), createSeparator()).
        add(fullNameLayout.createConstraint().widthPercentage(50), lastName);
Container fullPhone = TableLayout.encloseIn(3, phonePrefix, createSeparator(), phone);

// The button in the south portion needs the arrow icon to be on the right side so we place the text on the left
Button southButton = new Button("Get started", rightArrow);
southButton.setTextPosition(Component.LEFT);
southButton.setUIID("SouthButton");

// we add the components and the separators the center portion contains all of the elements in a box
// Y container which we allow to scroll. BorderLayout Containers implicitly disable scrolling
Container by = BoxLayout.encloseY(
        fullName,
        createSeparator(),
        email,
        createSeparator(),
        password,
        createSeparator(),
        fullPhone,
        createSeparator()
);
by.setScrollableY(true);
psdTutorial.add(BorderLayout.NORTH, titleContainer).
        add(BorderLayout.SOUTH, southButton).
        add(BorderLayout.CENTER, by);

psdTutorial.show();

Style it with Chapter 15, CSS. Ten UIIDs cover this design, and every value in it maps to an ordinary CSS property: the scaled header image is cn1-background-type, a UIID that only varies a color inherits the rest with cn1-derive, and the pressed and selected states are the .pressed and .selected classes rather than separate definitions. Sizes are in millimetres so they hold their physical size across densities.

TitleContainer {
    background-image: url(images/background.jpg);
    cn1-background-type: cn1-image-scaled-fill;
    cn1-source-dpi: 320;
    padding: 8mm 3mm 2mm 3mm;
    margin: 0;
}

/* The camera artwork is fetched by name at runtime rather than set as a
   background, so it needs a selector to get it into the theme at all. This one
   is never applied to anything; naming the images here is what bundles them. */
PsdImages {
    background-image: url(images/camera.png),
        url(images/camera-button.png);
    cn1-source-dpi: 320;
}

Title {
    background-color: transparent;
    color: #ffffff;
    font-family: "native:MainThin";
    font-size: 3.5mm;
    padding: 1mm;
    margin: 0;
    border: none;
}

TitleCommand {
    cn1-derive: Title;
}

RedCommand, RedCommand.pressed, RedCommand.selected {
    cn1-derive: Title;
    color: #f73267;
    font-family: "native:MainLight";
    font-size: 3mm;
}

TitleArea {
    background-color: transparent;
    padding: 0;
    margin: 0;
    border: none;
}

TextField, TextField.selected {
    background-color: #ffffff;
    font-family: "native:MainLight";
    font-size: 2mm;
    padding: 2mm;
    margin: 0;
    border: none;
}

TextHint {
    cn1-derive: TextField;
    color: #4d606f;
}

SouthButton, SouthButton.pressed, SouthButton.selected {
    background-color: #f73267;
    color: #ffffff;
    text-align: center;
    font-family: "native:MainThin";
    font-size: 3mm;
    padding: 2mm 1mm 2mm 1mm;
    margin: 0;
}

CameraButton, CameraButton.pressed, CameraButton.selected {
    background-color: transparent;
    text-align: center;
    padding: 3mm 1mm 1mm 1mm;
    margin: 1mm;
}

/* The separator is an empty Label, so the line is the style: a background
   colour and just enough padding to give it height. */
Separator {
    background-color: #f5f5f5;
    padding: 0.2mm 0 0 0;
    margin: 1mm 0 1mm 0;
    border: none;
}

That’s the whole theme. With it in place the same code produces the design:

The result in the simulator
Figure 204. The result in the simulator

14. Native modern themes

Codename One ships an iOS Modern (liquid-glass) theme and an Android Material 3 theme that you can opt your app into with a single build hint. Both are fully overridable - their color palettes, type ramps, and state-specific styles are all reachable from your own theme.css and from runtime API.

The legacy iOS 7 (iOS) and Holo Light (Android) themes remain the default so existing apps see no behavior change.

14.1. Inheriting OS colors and fonts

Modern native themes can optionally follow the user’s operating-system settings. Colors and fonts are independent opt-ins; both are off by default. Enable them in an application theme that includes the native theme:

#Constants {
    includeNativeBool: true;
    useNativeColorsBool: true;
    useNativeFontsBool: true;
    useLargerTextScaleBool: true;
}

Alternatively, configure the UIManager before loading the application theme:

UIManager ui = UIManager.getInstance();
ui.setUseNativeColors(true);
ui.setUseNativeFonts(true);
ui.setUseLargerTextScale(true);

An explicit theme constant takes precedence over its Java setter when the theme is built. After changing a setter on an already loaded theme, call UIManager.refreshTheme() and refresh/revalidate the visible form. A theme constant set to false must also be changed or removed before a setter can enable that option.

Color inheritance feeds the theme’s semantic palette bindings. Font inheritance uses the normal OS UI font family and size while retaining the native theme’s relative heading sizes and styles. Explicit application style properties and palette constants override these inherited defaults. Bundled application fonts and icon fonts aren’t replaced. Legacy hand-authored native themes don’t carry the inheritance metadata and retain their existing appearance.

The existing larger-text accessibility option remains independent. It scales eligible fonts after OS font inheritance, so enabling both doesn’t apply the OS text-size multiplier twice. Existing dark-mode selection remains independent too.

Settings changes and application activation trigger a coalesced theme refresh. The framework preserves application overrides, refreshes visible styles and layout, and restores bundled defaults when settings become unavailable or an inheritance option is disabled. Unsupported settings fall back individually.

PortSettings source

Windows native

Windows UISettings accent/selection palette, high-contrast system colors, and the nonclient message font. Normal Fluent surfaces retain their bundled colors where no corresponding OS value is exposed.

macOS native

AppKit semantic colors and normal system UI typography.

Linux native

The active GTK palette and GTK font setting. Only available named colors are inherited; the opposite appearance retains its bundled palette.

Android

Platform normal text appearance and, on Android 12 or newer, public dynamic-color resources. Older versions retain the bundled palette.

iOS

UIKit semantic colors on iOS 13 or newer and normal system UI typography.

JavaSE

Available AWT desktop properties; the simulator uses explicit simulated settings rather than the host’s palette.

In the simulator, use Simulate > OS Theme Settings to choose an accent and UI font or reset the simulated settings. These controls exercise the app’s opt-ins; they don’t enable inheritance for the app. Tests can supply a deterministic snapshot with JavaSEPort.setSimulatorNativeThemeSettings(…​).

14.2. Selecting a theme

Three build hints control the platform native theme. None of them are required; with all three unset every app continues to load the legacy theme it always did.

HintValuesDescription

ios.themeMode

auto (default)
modern / liquid
ios7 / flat
legacy / iphone

auto and ios7 both load the iOS 7 flat theme. modern / liquid opts in to the modern theme generated from native-themes/ios-modern/theme.css. legacy / iphone loads the pre-iOS 7 theme. The auto → modern flip is planned for a future release.

and.themeMode

auto / modern / material
hololight (legacy default)
legacy

auto and modern / material opt in to the modern theme generated from native-themes/android-material/theme.css. hololight is Android Holo Light (the pre-modern default for existing apps). legacy is the pre-Holo theme. The legacy alias cn1.androidTheme is still honored for back-compat.

ios.themeGeneration

26 (default)
27

Which iOS design generation the modern theme targets. Consulted only when ios.themeMode resolves to modern; the iOS 7 and pre-flat looks have one generation each and ignore it. Unset is 26, so an existing project keeps the theme it has. 27 is a real design change rather than a version bump — 31 of the 68 native reference tiles differ, concentrated in the Liquid Glass surfaces and the bar and button chrome built on them, while the classic form controls are identical.

nativeTheme

modern / legacy / custom

Cross-platform shortcut that sets both ios.themeMode and and.themeMode together. modern = liquid glass + Material 3, legacy = iOS 7 + Holo Light, custom disables the framework theme entirely so your own theme.css owns the base layer. The legacy alias cn1.nativeTheme is still honored for back-compat.

The legacy and.hololight=true hint still works and maps to and.themeMode=hololight.

14.3. Desktop themes

Windows, macOS and GNOME have their own native themes, selected with desktop.themeMode on the JavaSE desktop build and with macos.themeMode on the native macOS port.

HintValuesDescription

desktop.themeMode

legacy (default)
auto / native
fluent / aqua / adwaita
custom

Unset is legacy: an existing desktop project keeps the theme it has always loaded, so upgrading the framework doesn’t restyle an application nobody asked to restyle. auto and native opt in and both mean "whatever this machine is" — Windows 11 Fluent, macOS Aqua or GNOME Adwaita — which is the only sensible reading on desktop, where one binary runs on all three. Naming a theme outright is what a build that wants one look everywhere asks for. custom installs no framework theme so your own theme.css is the only one.

macos.themeMode

aqua (default) / native
modern / liquid
ios7 / flat

The native macOS port. When neither this hint nor the shared nativeTheme hint is set, the default is Aqua. aqua and native select the macOS theme; modern / liquid select the iOS Liquid Glass theme. An explicit shared hint still applies when macos.themeMode is unset: nativeTheme=modern selects the modern theme, while nativeTheme=legacy selects ios7.

The three desktop themes are generated from native-themes/windows-fluent, native-themes/macos-aqua and native-themes/gnome-adwaita. They’re separate files rather than one file with per-platform blocks, and they’re held to the same surface by DesktopNativeThemeParityTest: the same UIIDs, the same #Constants, and a $Dark counterpart for everything that paints a color. That matters to you and not only to the themes — an application retunes a parent theme by redeclaring #Constants, so one vocabulary means the same CSS retunes all three platforms rather than only the one it was written against.

14.3.1. One application on all three

The Codename One Settings tool is built this way. Its main class declares @DesktopBuild(themeMode = "native"), so it opens in Fluent on Windows, Aqua on macOS and Adwaita on Linux, and its own theme.css never names a color the platform owns:

  • Each control derives from the native UIID it’s a variant of — cn1-derive: TextField for a field, RaisedButton for the primary action, GroupBox for a card — so borders, fills and focus rings are the platform’s.

  • Surfaces and text use the palette variables every desktop theme declares, such as var(--window-bg-color) and var(--text-secondary-color). At runtime the installed theme’s values replace the ones the compiler baked in.

  • Only the brand is fixed: the tool redeclares --accent-color in its #Constants, and the Save button keeps its own green.

The Settings tool under Windows 11 Fluent

Settings under Fluent in light mode Settings under Fluent in dark mode

The Settings tool under macOS Aqua

Settings under Aqua in light mode Settings under Aqua in dark mode

The Settings tool under GNOME Adwaita

Settings under Adwaita in light mode Settings under Adwaita in dark mode

All six images were captured on a Mac, not on Windows or Linux. Colors, borders and spacing come from the theme and are the same on every host, but each theme draws text in its platform’s own typeface — Segoe UI Variable, SF or Cantarell — and the Fluent and Adwaita images fall back to the Mac’s system font. On a real Windows or Linux desktop the text looks different.

In a web browser, nativeTheme=native selects the desktop theme of the browser’s operating system, and the javascript.titleBar build hint decides whether the title and the commands stay in the Toolbar or move to an HTML title bar and menu bar. See Changing the Native Theme.

To preview a desktop theme in the simulator, pick the Desktop skin and choose the theme from the Native Theme menu. With Auto selected the Desktop skin follows desktop.themeMode, which is what the packaged application does.

14.3.2. Hover

Desktop themes carry a state mobile ones have no use for. A .hover rule styles a component while the pointer is over it:

Button.hover {
    background-color: #f6f6f6;
}

It compiles to hover# entries the same way .pressed compiles to press#, and Component.getHoverStyle() returns null when the theme declares none — so a component with no hover rule keeps its normal style rather than falling back to a blank one.

Hover has no meaning on a touch device and isn’t delivered there. On desktop it’s driven by real pointer motion: the JavaSE, Windows and Linux ports all report motion with no button held, which is what Form.pointerHover resolves against.

macOS is the exception, and the reason belongs to AppKit rather than to Codename One. AppKit draws no rollover state for buttons, fields, sliders, switches or popup buttons, so the Aqua theme leaves hover equal to normal. The captured native reference says the same, and the fidelity gate holds it there.

14.4. Light and dark mode

Both modern themes ship a dark variant via a @media (prefers-color-scheme: dark) block in their CSS. The CSS compiler rewrites each rule inside that block into a $Dark<UIID> style entry; UIManager picks them up whenever CN.isDarkMode() == true.

One form under Android Material, rendered in each appearance

Light appearance Dark appearance

Nothing in that form is styled by hand, so the difference between the two pictures is entirely what the theme’s dark entries supply.

Display.getInstance().setDarkMode(Boolean) controls the active appearance:

  • null (the default) - follow the device. iOS reads UITraitCollection, Android reads Configuration.uiMode. When the user toggles light / dark in system settings the app reflects the change. A JavaSE desktop application reads the system appearance once, at launch: AppsUseLightTheme on Windows, AppleInterfaceStyle on macOS and the GNOME color-scheme setting on Linux. In the simulator the Dark/Light Mode menu decides instead.

  • true / false - force the app into one mode regardless of system setting (useful for theme-preview screens or accessibility toggles).

14.5. Material 3 color palette (Android)

The Android Material 3 theme is built around the Material Design 3 "baseline" palette. Each color is referenced from one or more UIIDs; if you change a color the change ripples to every UIID that inherits from it.

RoleLightDarkUsed by

primary

#6750a4

#d0bcff

Default Button fill, BackCommand / TitleCommand text, SelectedTab text color.

on-primary

#ffffff

#381e72

Text printed on top of the primary fill.

primary-container

#eaddff

#4f378b

RaisedButton (the elevated tone), Button.pressed and MultiButton.pressed highlight, FloatingActionButton.

surface

#fef7ff

#141218

Form, ContentPane, Toolbar, TitleArea, List, Tabs, SideNavigationPanel. The "page" color.

on-surface

#1d1b20

#e6e0e9

Body text on surfaces (Label, Title, MultiLine1).

surface-variant

#e7e0ec

#49454f

Track of the off-state Switch.

on-surface-variant

#49454f

#cac4d0

Secondary text (SecondaryLabel, MultiLine2, UnselectedTab text).

surface-container

#f3edf7

#211f26

TextField / TextArea filled background.

surface-container-highest

#e6e0e9

#211f26

Dialog, PopupContent. Sits one elevation step above surface so dialogs read as raised cards.

outline / outline-variant

#79747e / #cac4d0

#938f99 / #49454f

Separator, TertiaryLabel, disabled-text muting.

state-pressed

#d0bcff

#4f378b

All .pressed overrides on Button-family UIIDs.

state-disabled / on-disabled

#e0dce4 / #a5a0ab

#2b2930 / #5c5967

All .disabled overrides.

To rebrand the app, override the color at the role level rather than touching every UIID. The example below layers a teal palette on top from your app’s own theme.css; if you want the same rebrand to apply at runtime (for in-app accent toggles, branded flavours, A/B tests) without recompiling the theme, see Runtime accent palette override further down - a single addThemeProps({"@accent-color": …​}) call retunes every accent-bearing UIID at once:

#Constants {
    includeNativeBool: true;
    darkModeBool: true;
}

/* Touch the four UIIDs that paint with primary / primary-container.
   The role-as-rule pattern keeps brand changes localised. */
Button { background-color: #00796b; }
Button.pressed { background-color: #4db6ac; color: #00251a; }
RaisedButton { background-color: #b2dfdb; color: #00251a; }
RaisedButton.pressed { background-color: #80cbc4; }
SelectedTab { color: #00796b; }
BackCommand { color: #00796b; }
TitleCommand { color: #00796b; }

14.6. iOS modern color palette

The iOS modern theme follows Apple’s system palette.

RoleLightDarkUsed by

accent

#007aff

#0a84ff

Button text, RaisedButton fill, SelectedTab text, BackCommand / TitleCommand, FloatingActionButton.

accent-pressed

#0064d1

#64b1ff

All .pressed accent overrides.

accent-disabled

#b3d4ff

#004a99

All .disabled accent overrides.

surface

#ffffff

#000000

Pure surface used by Toolbar, TitleArea, Title, List.

surface-grouped

#f2f2f7

#1c1c1e

Form / ContentPane (the iOS "grouped" form bg). Dialog / Tabs use this color at reduced opacity for the liquid-glass look.

surface-tertiary

#e5e5ea

#2c2c2e

Button.pressed highlight, elevated dark Dialog surface.

text-primary

#000000

#ffffff

Label, MultiLine1, Title, primary body text.

text-secondary

#3c3c43

#ebebf5

SecondaryLabel, MultiLine2, unselected tabs.

text-tertiary / text-disabled

#8e8e93 / #c7c7cc

#8e8e93 / #48484a

TertiaryLabel, MultiLine3-4, disabled-state text.

separator

#c6c6c8

#38383a

Separator.

success

#34c759

#30d158

Switch.selected, OnOffSwitch.selected.

To layer a brand color on top, override RaisedButton and accent-driven UIIDs the same way as Android above. The color names match Apple’s UIColor.systemBlue etc. So you can mirror the SF Symbols semantics if you want.

14.7. Accent palette override

Both shipped native themes expose their accent palette as named constants you can retune from your app’s own theme.css (or, for dynamic theming, at runtime). The CSS source uses var(--accent-color, fallback) references so the fallback ships as the baked-in default (the .res file loads fine with no override) and the compiler additionally emits a @cn1-bind:<UIID>.<key>=accent-color constant alongside each affected style key. When the resolved theme constants pick up a new @accent-color value (whether from your CSS or via runtime UIManager.addThemeProps), the framework fans the override out to every bound UIID at once - no per-UIID rule duplication, no theme recompile.

Table 8. iOS modern (native-themes/ios-modern/theme.css)
ConstantLight defaultDark defaultDrives

@accent-color

#007aff

(see @accent-color-dark)

Button.fgColor, RaisedButton.bgColor, CheckBox.selected, RadioButton.selected, OnOffSwitch.fgColor, BackCommand, TitleCommand, FloatingActionButton.bgColor.

@accent-color-dark

n/a

#0a84ff

$Dark<UIID> counterparts of the above.

@accent-pressed-color / @accent-pressed-color-dark

#0064d1

#64b1ff

All .press#fg/bgColor accent overrides.

@accent-disabled-color / @accent-disabled-color-dark

#b3d4ff

#004a99

All .dis#fg/bgColor accent overrides.

@accent-on-color

#ffffff

(same)

Text color painted on top of the accent fill.

Table 9. Android Material 3 (native-themes/android-material/theme.css)
ConstantLight defaultDark defaultMaterial 3 token

@accent-color / @accent-color-dark

#6750a4

#d0bcff

primary

@accent-on-color / @accent-on-color-dark

#ffffff

#381e72

on-primary

@accent-container-color / @accent-container-color-dark

#eaddff

#4f378b

primary-container

@accent-on-container-color / @accent-on-container-color-dark

#21005d

#eaddff

on-primary-container

@accent-pressed-color / @accent-pressed-color-dark

#d0bcff

#4f378b

state-pressed

Redeclare the accent variable inside the #Constants block of your app’s theme.css. The framework’s CSS compiler exports any --name declaration in #Constants as a @name theme constant, so the value flows through the same binding pass that handles runtime overrides:

#Constants {
    includeNativeBool: true;
    darkModeBool: true;

    /* Override the native theme's accent palette. The compiler picks
       up these declarations from #Constants and exports them as
       @accent-color / @accent-color-dark theme constants so every
       UIID bound to var(--accent-color) in the parent native theme
       picks them up at app launch - no per-UIID rule edit needed. */
    --accent-color: #ff2d95;
    --accent-color-dark: #ff2d95;
    --accent-pressed-color: #c71a75;
    --accent-pressed-color-dark: #c71a75;
    --accent-on-color: #ffffff;

    /* Material 3 RaisedButton uses a separate "container" tonal
       pair; iOS ignores these (no bindings reference them) so it's
       safe to set them unconditionally. */
    --accent-container-color: #ff2d95;
    --accent-container-color-dark: #ff2d95;
    --accent-on-container-color: #ffffff;
    --accent-on-container-color-dark: #ffffff;
}

Bindings that reference a constant you didn’t override stay at their baked-in default, so a partial override (for example, just --accent-color) is fine.

14.7.2. Runtime override

For dynamic theming - in-app accent toggles, branded flavours, A/B tests - push the same constants through UIManager.addThemeProps after the theme has been installed:

Hashtable override = new Hashtable();
override.put("@accent-color", "ff2d95");
override.put("@accent-color-dark", "ff2d95");
override.put("@accent-pressed-color", "c71a75");
override.put("@accent-pressed-color-dark", "c71a75");
override.put("@accent-on-color", "ffffff");
// every colour that has a -dark twin needs both, or dark mode keeps the
// theme's original value for the half you left out
override.put("@accent-on-color-dark", "ffffff");
override.put("@accent-disabled-color", "f9a8d0");
override.put("@accent-disabled-color-dark", "7a1547");
override.put("@accent-container-color", "ff2d95");
override.put("@accent-container-color-dark", "ff2d95");
override.put("@accent-on-container-color", "ffffff");
override.put("@accent-on-container-color-dark", "ffffff");
UIManager.getInstance().addThemeProps(override);
// null before the first form is shown, which is exactly when a branded
// flavour applies its overrides; forms built afterwards pick the new
// props up on their own
Form current = CN.getCurrentForm();
if (current != null) {
    current.refreshTheme();
}

Values can be passed with or without the leading # and in any case; the runtime accepts "ff2d95", "#FF2D95", and the 3-digit shorthand "#f0a" interchangeably.

PaletteOverrideThemeScreenshotTest in the hellocodenameone test suite exercises this path against both native themes, light + dark.

14.7.3. When the override path doesn’t apply

The binding mechanism handles every accent UIID the shipped themes expose. For other widgets - or when you want to override a color the native CSS hard-codes (for example, the iOS success green on Switch.selected) - either:

  • Layer a per-UIID redeclaration in your app’s theme.css (see Customizing in your own theme below). Right when you want to tweak a UIID the binding vocabulary doesn’t already cover.

  • Or pass the specific UIID/state key directly into UIManager.addThemeProps (Switch.sel#bgColor etc.). Runtime, bypasses the binding system. Right when you need a one-off color tweak you can’t anchor in CSS.

14.8. Platform-specific UIIDs

A handful of UIIDs exist only because one platform draws them differently from the other. They’re still safe to override; you just want to know which platform’s screen the override is going to land on.

iOS-only behavior:

  • Toolbar, TitleArea, Title paint over the status-bar area. iOS reserves room above for the notch / status bar; in your capture this reads as a colored strip at the top of the Form. In production the device fills it with system content (signal, battery, time).

  • MultiButton is styled as an iOS Settings row (multi-line text ramp + chevron). Compare against Material 3’s denser list-item pattern.

Android-only behavior:

  • Toolbar doesn’t paint over the system status bar; the native Android status bar handles that.

  • Tabs use Material 3 top tabs (flat, underline-by-color). iOS modern renders Tabs as a bottom-anchored pill group via the tabPlacementInt constant - that constant is intentionally only set in the iOS theme so behavior stays consistent on each platform.

14.9. Switching CheckBox / RadioButton glyphs

The default check / radio glyphs are Material icons drawn by DefaultLookAndFeel. The theme can swap them via four optional constants (Material codepoints):

ConstantDefaultNotes

@checkBoxCheckedIconInt

MATERIAL_CHECK_BOX (E834)

Override to for example, MATERIAL_CHECK_CIRCLE (E86C / 59500) for an iOS-style filled circle. The iOS modern theme does this.

@checkBoxUncheckedIconInt

MATERIAL_CHECK_BOX_OUTLINE_BLANK (E835)

Match the empty version of whatever you chose above.

@radioCheckedIconInt

MATERIAL_RADIO_BUTTON_CHECKED (E837)

Filled circle with dot.

@radioUncheckedIconInt

MATERIAL_RADIO_BUTTON_UNCHECKED (E836)

Empty circle.

Set these in your #Constants { …​ } block; the icons rebuild on the next style refresh.

14.10. Component-specific tuning constants

ConstantEffect

@switchTrackScaleX, @switchTrackScaleY

Stretches the Switch track. Larger X = longer pill, larger Y = thicker. iOS uses 2.5 / 1.5; Material uses 3.0 / 0.9.

@switchThumbScaleY

Scales the Switch thumb relative to the track. iOS 1.4, Material 1.5.

@switchThumbPaddingInt, @switchThumbInsetMM

Pixels of breathing room between thumb and track.

@switchTrackOffOutlineWidthMM, @switchTrackOffOutlineColor

iOS draws a faint ring around the off-state track; Material does not.

@tabPlacementInt

Component.TOP (0), Component.BOTTOM (2), Component.LEFT (1), Component.RIGHT (3). Where the Tabs widget anchors its tab bar. Set in iOS modern theme to 2 for the iOS 26 bottom-bar look; unset on Android (Tabs at top).

@tabsFillRowsBool, @tabsGridBool

Distribute tabs evenly across the bar.

@tabsAnimatedIndicatorBool

true paints a thin colored underline below the currently selected tab and tweens its x / width between tabs on selection change. Both modern themes set this to true. Off in the framework default; opt-in for legacy themes by setting it explicitly.

@tabsAnimatedIndicatorDurationInt

Duration of the indicator tween in milliseconds (default 200, matching Material 3’s NavigationBar spec).

@tabsAnimatedIndicatorThicknessMm

Indicator underline thickness in millimetres (default 1).

@pullToRefreshModernBool

true switches the pull-to-refresh visual from the legacy rotating-arrow + text Label stack to a thin circular arc spinner painted directly via Graphics.drawArc. The arc sweep grows from 0° to ~330° proportional to the user’s pull, then spins continuously once the refresh task fires. Both modern themes set this to true. Color comes from the TabIndicator UIID’s fg (consistent with the animated tab indicator), falling back to the Title fg if unset.

@pullToRefreshIndicatorDiameterMm

Outer diameter of the modern arc spinner in millimetres (default 8). Drives the gesture threshold too — the user must pull this distance plus a small margin to fire the refresh task.

@pullToRefreshIndicatorStrokeMm

Stroke thickness of the modern arc spinner in millimetres (default 0.6).

@darkModeBool

true enables $DarkUIID resolution when the app is in dark mode. Both modern themes set this; user themes that want dark mode also need to set it.

14.11. iOS 26 Liquid Glass tab selection morph

When the iOS modern theme renders Tabs as a bottom bar (tabPlacementInt: 2) the selected tab is marked by a Liquid Glass drop — a frosted, magnifying glass capsule painted over the (dark) icons rather than a flat highlight. On a selection change the drop springs across to the new tab, elongating while it travels and settling with a small overshoot. The selected blue is supplied by the drop itself (a luminance-keyed dark→accent tint of the glyph beneath it), so the color travels with the drop instead of snapping between tabs.

iOS 26 Liquid Glass tab selection morph

On iOS the drop is rendered live by a Metal fragment shader that samples the bar beneath it on the GPU, so the morph runs at frame rate with no screen read-back; other platforms and the simulator use the equivalent CPU lens. The effect is opt-in: the iOS modern theme sets tabsSelectionCapsuleBool: true and glassMaterialBool: true. Without the glass flag the capsule degrades to a plain translucent pill.

The morph is developed against the real OS control: the frame-by-frame comparison below shows the native iOS 26 tab bar (left) and the Codename One render (right) at matching moments of the selection travel.

Native iOS 26 tab bar vs the Codename One morph, frame by frame

The animation is controlled by a named motion preset plus a handful of high-level knobs. The detailed envelopes (stretch, squash, lift, lens magnification, aberration, tint timing) live inside the preset in the motion model (TabSelectionMorph), where they’re pinned by unit test and validated frame-by-frame by the fidelity suite — a theme picks a preset and scales it rather than tuning a dozen loose constants:

ConstantiOS modernEffect

@tabsSelectionCapsuleBool

true

Master switch for the selection drop. Off falls back to the legacy colored underline indicator (tabsAnimatedIndicatorBool).

@tabsMorphPreset

ios26

The named motion preset: ios26 (the measured Liquid Glass morph) or subtle (half the deformation and optics, for a calmer selection change).

@tabsAnimatedIndicatorDurationInt

480

Morph duration in milliseconds. Lower is snappier.

@tabsMorphLensIntensityPct

100

Scales the drop’s optics (magnification, chromatic aberration, accent tint) around the preset: 0 is an optically flat drop, 200 doubles the lens strength. Geometry is unaffected.

@tabsMorphSpringPct

100

Scales the settle overshoot: 0 stops dead on a plain ease-out, 200 doubles the bounce.

@tabSelLensTintColorInt

0x0a84ff

The accent the dark glyph is tinted to inside the drop.

The iOS 27 theme uses a third preset, ios27, which is time based rather than a fixed-duration morph. Its curves are measured from a real UITabBarController on the iOS 27 simulator, frame by frame, and played back by TabGlassMotion:

  • on a tap the selection lens lifts: it grows, its platter fades so it becomes clear glass, and the tab content seen through it magnifies;

  • it travels on a spring, stretching while it accelerates and squashing on arrival in proportion to the distance, then settles with a second, smaller wobble;

  • the whole bar — glass, content and lens — pulses in scale, and a soft glow spreads from where the finger touched.

The motion follows the gesture, not just the tap, the way UIKit’s does:

  • holding a press keeps the lens lifted and the bar grown until the finger lifts;

  • pressing the selected tab lifts and pulses the lens in place;

  • dragging along the bar pulls the lens with the finger (a scrub), and letting go selects the tab under the finger, with the lens settling there;

  • every release ends in a small wobble about a second after the finger lifts.

The accent color lives in a second copy of the tab content, visible only through the lens, so the color travels with the glass. Where the port supports Graphics.colorMatrixRegion (iOS, macOS, the JavaScript port and the simulator), the tab content is vibrant like UIKit’s: each glyph pixel is a color matrix of the glass behind it rather than flat paint, so labels and the accent pick up the colors under the bar. The selection platter is likewise the bar’s own glass seen through a color matrix, not a translucent fill. With this preset the tabs are painted with their normal style outside the lens and with their pressed style inside it: the theme’s Tab/TabIcon colors are the unselected ones and Tab.pressed/TabIcon.pressed the selected ones. Tab backgrounds should stay transparent.

The motion reaches past the bar’s visible pill, so the bar reserves room for it inside its own bounds: the theme widens the TabsContainer padding by the slack, narrows its margin by the same amount so the pill stays where it was, and names the slack in constants. Everything the motion paints then stays inside the bar’s own bounds and repaint region.

ConstantiOS 27Effect

@tabsMorphPreset

ios27

Selects the measured time-based motion described above.

@tabsGlassSlackXMm / @tabsGlassSlackYMm

2 / 1

How much of the TabsContainer padding is motion slack rather than pill.

@tabSelInsetMm

0.66

Inset of the resting lens inside the pill.

@tabSelPillColorInt / @tabSelPillAlphaInt

0 / 35

Color and alpha of the resting selection platter on ports without colorMatrixRegion.

@tabSelPillColorDarkInt / @tabSelPillAlphaDarkInt

0 / 67

The same platter in the dark appearance; defaults to the light values.

@tabGlassLensLightAlphaInt

28

White wash of the lifted lens, which reads brighter than the bar.

@tabGlassRimAlphaInt / @tabGlassEdgeAlphaInt

150 / 110

Alpha of the lifted lens’s bright inner rim and dark edge ring, scaled by the lift.

@tabGlassGlowPct

40

Strength of the touch glow; 0 turns it off.

@tabGlassSpecularAlphaInt / @tabGlassSpecularDarkAlphaInt

145 / 90

Peak alpha of the bright rim along the bar’s top and bottom edges; 0 (the default) draws none.

Similarly, the Liquid Glass backdrop materials themselves are typed, named recipes (GlassRecipe): a theme assigns chrome (edge-anchored bars), pill (the floating tab bar) or panel (buttons, dialogs, panels — the default) per UIID with <UIID>GlassRecipe constants, e.g. ToolbarGlassRecipe: "chrome". Each recipe bundles the measured saturation/scale/offset color transform and edge optics of one native material, so similar glass surfaces can’t drift apart one constant at a time.

The drop’s glass cues (rim shrink, refraction, glare, edge shadow) fade out as it settles, so a resting selection reads as a calm frosted pill rather than a distorting lens. Every motion preset is validated deterministically: the fidelity suite freezes the morph at the fixed progress points 0, 10, 25, 50, 75, 90 and 100 percent, regression-compares each frame, and pins the same points numerically against the motion model in unit tests. The Switch thumb uses the same discipline for its liquid droplet morph (switchLiquidGlassBool, stretch/squash while sliding, frame-validated):
iOS 26 liquid-glass switch droplet

14.12. Customizing in your own theme

Your app’s theme.css inherits from the installed native theme:

#Constants {
    includeNativeBool: true;
    darkModeBool: true;
}

/* Tweak only what's different. Everything you do not redeclare
   keeps coming from the native theme. */
RaisedButton { background-color: #d81b60; }
RaisedButton.pressed { background-color: #b71c5c; }
RaisedButton.disabled { background-color: #ffd6e2; color: #ffffff; }

@media (prefers-color-scheme: dark) {
    RaisedButton { background-color: #ff80ab; color: #4a0026; }
    RaisedButton.pressed { background-color: #f06292; }
}

The user’s CSS is layered on top of the native theme at app launch, so refresh / restart picks the override up.

For a wholesale accent rebrand prefer redeclaring the --accent-color (etc.) variables in your #Constants block - see Override from your app’s theme.css above. That single declaration fans out through every UIID bound to the variable in the native theme, no per-UIID rules required. Per-UIID redeclaration here remains the right choice for tweaking non-accent properties (typography, spacing, surface fills) the binding vocabulary doesn’t cover.

14.13. Inheriting from a native UIID

cn1-derive lets a custom UIID start from one of the native theme’s UIIDs and refine it:

DangerButton {
    cn1-derive: RaisedButton;
    background-color: #d32f2f;
}
DangerButton.pressed {
    cn1-derive: RaisedButton;
    background-color: #b71c1c;
}

cn1-derive works best when the relationship is child refines parent. Avoid deriving across unrelated UIIDs (for example, a TitleArea that derives from Toolbar) - inline the properties instead.

14.14. Translucency, glass effects, and the test harness

The iOS modern Dialog and Tabs use translucent surfaces (rgba with alpha < 1) so any backdrop reads through the widget. To exercise this in screenshot tests, the hellocodenameone fidelity tests opt-in to a diagonal-stripe textured backdrop on the form (useTexturedBackdrop() in DualAppearanceBaseTest). Translucent widgets show their see-through tint against the stripes; opaque widgets cover the stripes entirely.

CSS backdrop-filter: blur(<length>) and filter: blur(<length>) are now recognized by the compiler and persisted in the theme as the backdropFilterBlur and filterBlur Style properties (also reachable programmatically via Style#getBackdropFilterBlurRadius() / Style#getFilterBlurRadius()). Image-level blur is hardware-accelerated (CIGaussianBlur on iOS, RenderScript / RenderEffect on Android, JHLabs GaussianFilter in the simulator). Painting the blur into the component framebuffer is still being wired up; until that lands, the rgba approximation above remains useful for translucent surfaces.

15. CSS

In this chapter this guide covers theming with CSS in Codename One.

CSS Changes don’t Require a Recompile
You can change the CSS values while the simulator is running and the changes will reflect in the simulator within a few seconds

15.1. Activating CSS

Codename One applications always use the resource file. The CSS support compiles a file in CSS syntax to a Codename One resource file and adds it to the application. In runtime the CSS no longer exists and the file acts like a regular theme file.

The CSS compiler is part of the build. It runs without a window or a display, so the same build works on a desktop machine, over SSH, in a container, and on a continuous integration server.

New Maven projects enable CSS by default with codename1.cssTheme=true in common/codenameone_settings.properties. Add that property manually if you are migrating an older project where CSS support is disabled.

Once enabled your theme.res file will regenerate from a CSS file that resides under the css directory. Changes you make to the CSS file will instantly update the simulator as you save. But, there are some limits to this live update so sometimes a simulator restart would be necessary.

15.2. Splitting a stylesheet with @import

A stylesheet can pull in other local stylesheets with @import. Both spellings work: @import "buttons.css"; and @import url(buttons.css);. The path is relative to the file that contains the rule.

The compiler places the imported rules at the point where the @import appears, as if you had pasted the file there. An imported file can import other files in turn.

Every @import goes at the top of its file, before any rule. The build fails on an @import that follows a rule and names it.

A relative url() inside an imported file stays relative to that file, not to the file that imported it. An image that sits beside widgets/buttons.css is referenced the same way whether theme.css imports that file directly or through another stylesheet.

The build fails when an imported file doesn’t exist, and when files import each other in a circle. Only local files can be imported: the compiler refuses an @import that names a remote URL.

15.3. Layering one theme over another

Compiling CSS in a Maven project rewrites the build’s theme.res in place. The compiler reads src/main/css, merges in whatever CSS the project’s dependencies contribute, and writes the result as the theme the app loads. What it doesn’t do is keep an older Designer resource underneath: there’s no second file and no overlay involved.

Something does sit beneath the compiled styles, though. The theme.css a new project starts with sets includeNativeBool: true, and UIManager installs the platform’s native theme before it applies the compiled one, so a property you leave out of CSS can still arrive from there.

Layering is a separate mechanism that you ask for explicitly. A theme constant named OverlayThemes holds a comma-separated list of resource names, each without the .res extension.

Write that name bare wherever you author it. The Designer’s constant editor and a CSS #Constants block both add the @ that theme constants are stored with, exactly as they do for includeNativeBool or commandBehavior, so typing @OverlayThemes in either place produces @@OverlayThemes and nothing ever reads it. The stored key is @OverlayThemes, which is what you see in the resource and what code setting the property directly has to use.

In a CSS #Constants block, quote the value whenever you name more than one overlay. The compiler keeps only the first value it parses out of the declaration, so OverlayThemes: base,extra; loses extra without a word while OverlayThemes: "base,extra"; keeps both.

When UIManager finishes building a theme it reads that constant, opens each name in turn from the resource root and applies its properties over the ones already loaded, so a later overlay beats an earlier one and every overlay beats the theme that named them.

Reach for it when you want to override a theme you don’t own — one shipped inside a cn1lib, for instance — without editing the original.

An overlay is loaded by name from the resource root. A name the build doesn’t produce is skipped with a message on the error stream and the app carries on with the theme it already has, so a typo shows up as styling that never applies rather than as a build failure.

15.4. Supported CSS selectors

Since Codename One stylesheets are meant to be used with Codename One component hierarchies instead of XML/HTML documents, selectors work a little differently.

  1. All selectors (with some specific exceptions discussed below) are interpreted as UIIDs.

  2. Only 4 predefined CSS classes are supported:

    • .pressed: Targets the component when in "Pressed" state.

    • .selected: Targets the component when in "Selected" state.

    • .unselected: Targets the component when in "Unselected" state.

    • .disabled: Targets the component when in "Disabled" state.

      If no class is specified, then the selector targets "all" states of the given component.

The following are a few possible selectors you can include in your stylesheet.

  1. Button: Defines styles for the "Button" UIID.

  2. Button.pressed: Defines styles for the "Button" UIID’s "pressed" state.

  3. Button, TextField, Form: Defines styles for the Button, TextField, and "Form" UIIDs.

The following example creates a simple button with a border, and text aligned center. By default the button will have a transparent background, but when it’s pressed, it will have a gray background:

Button {
    text-align: center;
    border: 1pt solid gray;
    background-color: transparent;
}

Button.pressed {
    background-color: gray;
}

15.4.1. Inheriting properties using cn1-derive

The following example defines a custom Button style named "MyButton" that inherits all the styles of Button but changes the background color to blue:

MyButton {
   cn1-derive: Button;
   background-color: blue;
}

15.5. Special selectors

15.5.1. #device

The #Device selector allows you to define which device resolutions this CSS file should target. Mutli-images generated from this style-sheet will be included variants for device resolutions in the range (min-resolution, max-resolution) as defined in this section. By default all resolutions are generated:

#Device {
    min-resolution: 120dpi;
    max-resolution: 480dpi;
    resolution: 480dpi;
}

15.5.2. #constants

The #Constants selector allows you to specify theme constants.

For example:

#Constants {
    includeNativeBool: true;
    commandBehavior: "Side";
    defaultFontSizeInt: 18;
    defaultDesktopFontSizeInt: 14;
    defaultSourceDPIInt: "0";
    menuImage: "menu.png";
}

MenuIcon {
    background-image: url(images/menu.png);
}

In the above example, the constants referring to an image name as a string requires that the image exists in one of the following locations:

  • res/<cssfilename>/<imageName>

  • ../res/<cssfilename>/<imageName>

  • ../../res/<cssfilename>/<imageName>

It must also have been defined as a background image in some selector in this CSS file.

15.5.3. Default

The Default selector is special in that it will set properties on the theme’s "default" element. The default element is a special UIID in Codename One from which all other UIIDs in the same theme are derived. This is a good place to set things like default fonts or background-colors.

A UIID takes a property from Default only when no rule sets that property for the UIID itself. That includes the rules of the native theme the app builds on, so Default doesn’t override a native Button or TextField. It fills in the UIIDs that nothing else styles, which are mostly the ones you create.

Backgrounds follow the same rule, and the native theme decides what an unstyled UIID looks like. Container is always transparent with no padding or margin, but a UIID of your own that sets no background can paint an opaque one under some themes. If such a UIID shows a band of color over its parent, give it background-color: transparent, or set that on Default to cover every UIID you leave unstyled.

The universal selector * isn’t supported. The compiler ignores its declarations and prints a warning. Use Default instead.

15.6. Standard CSS properties

  • padding (and variants)

  • margin (and variants)

  • border (and variants)

  • border-radius

  • background (Usage below)

  • background-color

  • background-repeat

  • background-image

  • border-image

  • border-image-slice

  • font (Usage is covered in the following font section)

  • font-family (Usage is covered in the following font section)

  • font-style (Usage is covered in the following font section)

  • font-size (Usage is covered in the following font section)

  • @font-face (Usage is covered in the following font section)

  • color

  • text-align

  • text-decoration(Usage below)

  • opacity

  • box-shadow

  • width ( used for generating background-images and borders)

  • height ( used for generating background-images and borders)

15.7. Custom properties

cn1-source-dpi

Used to specify source DPI for multi-image generation of background images. Accepted values: 0 (Not multi-image), 120 (Low res), 160 (Medium Res), 320 (Very High Res), 480 (HD), Higher than 480 (2HD). If not specified, the default value will be the value of the defaultSourceDPIInt theme constant, if specified, or 480, if not specified.

cn1-background-type

Used to explicitly specify the background-type that should be used for the class.

cn1-9patch

Used to explicitly specify the slices used when generating 9-piece borders. Deprecated - Use border-image and border-image-slice for 9-piece borders.

cn1-derive

Used to specify that this UIID should derive from an existing UIID.

15.8. CSS variables

As of CodenameOne 7.0, you can use variables in your CSS file via the var() CSS function. For example:

#Constants {
    --header-color: blue;
}

Header {
    color: var(--header-color, blue);
}

The var() function can be used inside property values. That is, You can’t use it in property names or selectors.

The var() grammar follows the browser CSS form:

#Constants {
    --custom-property-name: #0066cc;
}

ExampleSelector {
    color: var(--custom-property-name, #0066cc);
}

The <custom-property-name> must begin with two dashes (--).

The <declaration-value> is the fallback value that will be used if the variable hasn’t been defined in the CSS file. The fallback value may include commas.

Examples

Listing 11. Example defining and using a CSS variable
#Constants {
    --main-bg-color: red;
}

MyContainer {
    background-color: var(--main-bg-color);
}
Listing 12. Example using a fallback value
#Constants {
    --main-bg-color: red;
}

MyContainer {
    background-color: var(--main-bg-color, blue);
}

See the MDN docs for more details about the CSS variable spec.

15.9. Auditing a theme

A theme drifts as it grows. A color gets typed as #3366ff in a new rule when --brand already holds it, a variable outlives the last rule that read it, and a UIID stays styled long after its last screen was removed. The css-audit goal finds these without compiling anything:

mvn compile cn1:css-audit

It reports, with the file and line of each:

  • literal-matches-variable: a color literal whose value a variable already names, with the var() to use instead.

  • undefined-variable: a var(--name) with no definition and no fallback. This is the one error, and it fails the goal.

  • unused-variable: a variable that no rule reads.

  • repeated-literal: a color written in three or more rules that no variable names.

  • low-contrast: a rule whose color and background color fall below the 4.5:1 contrast ratio WCAG AA asks for body text. Variables are resolved first; translucent colors are skipped, because their contrast depends on what lies under them.

  • unused-uiid: a styled UIID that neither the framework nor the project names. Running compile first lets the audit search the compiled classes as well as the sources. A name built at run time, such as "Tab" + state in Java or "Tab$state" in Kotlin, counts as a use of every UIID starting with Tab, and a UIID another rule names in cn1-derive counts as used.

Variables a media query redefines, such as dark mode colors, are resolved within that query, and a literal is never told to use a variable whose value changes with the mode. The stylesheets of installed cn1libs are read for the variables they define, so a theme that uses one isn’t reported, but the audit reports nothing inside them.

The audit reads the stylesheet as written, so it runs in well under a second. -Dcn1.cssAudit.strict=true fails the goal on any warning, which suits a continuous integration step, and -Dcn1.cssAudit.format=json prints the findings as JSON for other tools.

15.10. CSS properties

This section isn’t as comprehensive as it should be due to the breadth of CSS.

15.10.1. Text-decoration

underline

Underlines text. For example, text-decoration: underline;

overline

Overlines text. For example, text-decoration: overline;

line-through

Strikes through text. For example, text-decoration: line-through;

none

No text decoration. For example, text-decoration: none;

cn1-3d

3D text. For example, text-decoraton: cn1-3d; cn1-3d screenshot

cn1-3d-lowered

3D lowered text. For example, text-decoration: cn1-3d-lowered; cn1-3d-lowered screenshot

cn1-3d-shadow-north

3D text with north shadow. For example, text-decoration: cn1-3d-shadow-north; cn1-3d-shadow-north screenshot

For other CSS font settings see the Fonts section

15.10.2. Border

This library supports the border property and most of its variants (for example, border-width, border-style, and border-color. It will try to use native Codename One styles for generating borders if possible. If the border definition has no native equivalent, the CSS compiler paints the styled box itself at build time and stores the result in the theme as a 9-piece image border, or as a stretched background image. This has the effect of making the resulting resource file larger, but will produce good runtime performance, and a look that’s faithful to the provided CSS.

The algorithm used to determine whether to use a native border or to generate a 9-piece image, is complex, but the following guidelines may help you if you wish to design borders that can be rendered natively in CN1:

  • Non-pixel units border-width. (Except with the cn1-round-border and cn1-pill-border styles)

  • Using the border-radius directive.

  • Using box-shadow (Unless using cn1-round-border or cn1-pill-border styles)

  • Using a background gradient in combination with a border or any kind

  • Using a different border-width, border-style, or border-color for different sides of the border

  • Using a filter

To see whether an image was generated for a style, open the compiled theme.res in the resource editor (mvn cn1:designer) and inspect that style’s border. The editor is only a way to look at the result. Compiling the CSS doesn’t use it.

A generated image has a fixed resolution and is stretched to fit the component. The native forms — cn1-round-border, cn1-pill-border, a plain border-radius, and the cn1-box-shadow-* properties — are drawn by the platform at the device’s own density. Generating the image also makes CSS compilation slower and the binary larger, so tune the CSS so it avoids this fallback where the design allows.

Round borders

Rounded borders can be achieved in a few different ways. The easiest methods are:

  • The cn1-round-border style. This will render a circular round border in the background natively. That is, this doesn’t require generation of an image border

  • The cn1-pill-border style. This will render a pill-shaped border in the background natively. This also doesn’t require generation of an image border

  • The border-radius property. This will round the corners of the border. If the style can be achieved using the RoundRectBorder in CodenameOne, then it will use that border. If not, this will cause the style to be generated as an image border

A border generated from border-radius follows the CSS box model, so the radius rounds the component without changing its size. A radius larger than the component scales down to fit it. This differs from a RoundRectBorder you create in Java, which grows the component to twice the radius so the corners are always drawn in full. Use cn1-pill-border when a shape has to stay a pill at any height.

Examples using cn1-round-border

RoundBorder {
    border: 1px #3399ff cn1-round-border;
    text-align: center;
    margin: 2mm;
    padding: 3mm;
}

RoundBorderFilled {
    background: cn1-round-border;
    background-color: #cccccc;
    text-align: center;
    margin: 2mm;
    padding: 3mm;
}

Examples using cn1-pill-border

PillBorder {
    border: 1pt #3399ff cn1-pill-border;
    text-align: center;
}

PillBorderFilled {
    background: cn1-pill-border;
    background-color: #3399ff;
    color: white;
    text-align: center;
}

Examples using border-radius

RoundRectLabel {
    background-color: red;
    border-radius: 2mm;
}

cn1-pill-border and cn1-round-border don’t support the standard CSS box-shadow property. This is because the box-shadow property parameters don’t map onto the shadow parameters for the Codename One RoundBorder class. To get shadows on the cn1-pill-border, you should use one or more of the following CSS properties:

  • cn1-box-shadow-spread: Accepts values in any scalar unit (for example, px, mm, cm, etc.). This maps directly to the border’s shadowSpread property.

  • cn1-box-shadow-h: Accepts values in real values or integers (not a scalar unit). This maps directly to the border’s shadowX property.

  • cn1-box-shadow-v: Accepts values in real values or integers (not a scalar unit). This maps directly to the border’s shadowY property.

  • cn1-box-shadow-blur: Scalar value. Maps to the border’s shadowBlur property.

  • cn1-box-shadow-color: The shadow color

  • cn1-box-shadow-inset: Set to inset to render an inner shadow instead of the default outer shadow spread.

Using the regular CSS box-shadow in conjunction with border-radius will cause a 9-piece border to be generated rather than mapping to the RoundRectBorder. If, but, you use the cn1-box-* properties for the shadow instead, it will use the RoundRectBorder—assuming that no other styles are specified that trigger an image border to be generated.

Codename One also exposes per-corner elliptical radius controls that map to the RoundBorder’s X/Y radii. You can set them directly with `cn1-border-top-left-radius-x / cn1-border-top-left-radius-y (and the equivalent top-right, bottom-left, and bottom-right pairs) to fine tune horizontal and vertical curvature independently. The CSS parser automatically populates these properties when you use standard border-radius syntax, including the longhand declarations and the border-radius: <x-radii> / <y-radii> shorthand:

EllipticalBorder {
    border-radius: 2mm 4mm 6mm 1mm / 1mm 3mm 5mm 7mm;
    cn1-box-shadow-spread: 1.5mm;
    cn1-box-shadow-inset: inset;
}

In the example above, the four horizontal radii (2mm 4mm 6mm 1mm) populate the cn1-border--radius-x properties clockwise from the top-left corner. The four values after the slash fill the matching cn1-border--radius-y entries. Setting cn1-box-shadow-inset: inset; converts the shadow into an inset glow that follows the same elliptical curvature.

15.10.3. Background

The background property supports most standard CSS values for setting the background color, or background image.

9-piece Image borders always take precedence over background settings in Codename One. If your background directive seems to have no effect, it’s likely because the theme has specified a 9-piece image border for the UIID. You can disable the image border using a directive like border: none
Background images

See Images

Gradients

The full CSS gradient range is natively supported: linear-gradient, radial-gradient, conic-gradient, repeating-linear-gradient, and repeating-radial-gradient — all with arbitrary angles, unlimited multi-stop colors (with optional position hints), and full radial shape/extent control. The compiled theme resource file carries a compact descriptor and the gradient is rendered at runtime by the platform-native graphics API (Java2D on JavaSE, LinearGradient/RadialGradient/SweepGradient on Android, Core Graphics / Core Image on iOS).

CSS gradient examples
Figure 205. CSS gradient functions rendered side-by-side from the framework’s screenshot test (top to bottom: linear at an arbitrary angle, linear to <side>, linear with mismatched alphas, radial farthest-corner, radial ellipse, conic, repeating-linear, repeating-radial).

linear-gradient

Any angle in degrees, radians, or turn, or the canonical to <side> / to <side1> <side2> directions. Two or more stops, each with optional position percentage; positions left blank between fixed anchors are autodistributed:

LinearGradientA { background: linear-gradient(0deg, #cccccc, #666666); }
LinearGradientB { background: linear-gradient(to top, #cccccc, #666666); }
LinearGradientC { background: linear-gradient(45deg, #eaeaea, #666666); }
LinearGradientD { background: linear-gradient(135deg, #ff0080 0%, #ff8c00 50%, #40e0d0 100%); }
LinearGradientE { background: linear-gradient(to bottom right, #ff0066, #000033); }
LinearGradientF { background: linear-gradient(90deg, rgba(255, 0, 0, 0.6), blue); }

radial-gradient

Full CSS radial syntax: circle or ellipse, any of the four extent keywords (closest-side / closest-corner / farthest-side / farthest-corner, defaulting to farthest-corner), explicit radii as percentages, an optional at <position> clause with side keywords or percentages, and two or more multi-stop colors:

RadialGradientA { background: radial-gradient(circle, gray, white); }
RadialGradientB { background: radial-gradient(ellipse closest-side at 25% 75%, #ffffff, #000000); }
RadialGradientC { background: radial-gradient(circle farthest-corner at right, #ffffee, #006666 60%, #000011 100%); }

conic-gradient

Sweep / pie-style gradient. Optional from <angle> (CSS convention: 0° points up, sweep is clockwise) and at <position> prefix, followed by the stop list:

ConicGradientA { background: conic-gradient(red, yellow, green, blue, red); }
ConicGradientB { background: conic-gradient(from 45deg at 50% 50%, #ff0066 0%, #ffcc00 25%, #00cc66 50%, #0066ff 75%, #ff0066 100%); }

repeating-linear-gradient / repeating-radial-gradient

Identical syntax to their non-repeating counterparts. The stop pattern tiles outward to fill the bounding box, ideal for stripes and rings:

MyStripe { background: repeating-linear-gradient(45deg, #eeeeee 0%, #eeeeee 10%, #cccccc 10%, #cccccc 20%); }
MyTarget { background: repeating-radial-gradient(circle at center, #ffffff 0%, #ffffff 20%, #cc3333 20%, #cc3333 40%); }
filter and backdrop-filter

CSS filter and backdrop-filter accept a chain of functions. Two storage forms land on the corresponding Style:

  • blur(<length>) → filterBlurRadius / backdropFilterBlurRadius (a single pixel value).

  • brightness, contrast, grayscale, hue-rotate, invert, opacity, saturate, sepia → filterColorMatrix / backdropFilterColorMatrix (a 4×5 color matrix; a multi-function chain composes into a single matrix in CSS order):

MyOverlay {
    background: rgba(0, 0, 0, 0.4);
    backdrop-filter: blur(12px);
}

MyBlurredImage {
    filter: blur(4px);
}

MyFaded {
    filter: brightness(0.7) contrast(1.15);
}

MyGrayscale {
    filter: grayscale(1);
}

MySepia {
    filter: sepia(0.8) saturate(1.1);
}
CSS filter blur visual
Figure 206. filter: blur() applied at a graphics primitive level — the framework’s screenshot test renders RGB stripes and a gradient, then blurs both via Graphics.gaussianBlur(…​). Component-level paint-time integration of filter: declarations is in progress; until it lands, set the radius / matrix on a Style and consume them via the corresponding Graphics primitives manually.

filter applies to the component’s own painted content; backdrop-filter applies to whatever is painted behind. The radii / matrices are also exposed on Style (getFilterBlurRadius(), getFilterColorMatrix(), getBackdropFilterBlurRadius(), getBackdropFilterColorMatrix()) so they can be set programmatically. Hardware blur is used where available (Core Image on iOS, RenderScript/RenderEffect on Android, JHLabs GaussianFilter on JavaSE simulator); ports without a fast path fall back to a software Gaussian.

15.10.4. cn1-background-type

It also supports some special Codename One values, which are identifiers with a "cn1-" prefix. The following special values are available. They map to the standard Codename One values you discussed in the theming chapter:

  • cn1-image-scaled

  • cn1-image-scaled-fill

  • cn1-image-scaled-fit

  • cn1-image-tile-both

  • cn1-image-tile-valign-left

  • cn1-image-tile-valign-center

  • cn1-image-tile-valign-right

  • cn1-image-tile-halign-top

  • cn1-image-tile-halign-center

  • cn1-image-tile-halign-bottom

  • cn1-image-align-bottom

  • cn1-image-align-left

  • cn1-image-align-right

  • cn1-image-align-center

  • cn1-image-align-top-left

  • cn1-image-align-top-right

  • cn1-image-align-bottom-left

  • cn1-image-align-bottom-right

  • cn1-image-border

  • cn1-none

  • cn1-round-border

  • cn1-pill-border

15.11. Images

Images are supported as both "inputs" of the stylesheet, and as outputs to the compiled resource file. "Input" images are specified via the background-image property in a selector. "Output" images are always saved as multi-images inside the resource file.

15.11.1. Image DPI and device densities

To appropriately size the image, the CSS compiler needs to know what the source density of the image is. For example, if an image is 160×160 pixels with a source density of 160dpi (that is, medium density - or the same as an iPhone 3G), then the resulting multi-image will be sized at 160×160 for medium density devices and 320×320 on high density devices (for example, iPhone 4S Retina) - which will result in the same perceived size to the user of 1×1 inch.

However, if the image has a source density of 320dpi, then the resulting multi-image would be 80×80 pixels on medium density devices and 160×160 pixels on high density devices.

Some images have this density information embedded in the image itself so that the CSS processor will know how to resize the image. But, it’s better to explicitly document your intentions by including the cn1-source-dpi property as follows:

SomeStyle {
    background-image: url(images/my-image.png);
    cn1-source-dpi: 160;
}
cn1-source-dpi values are meant to fall into threshold ranges. Values less than or equal to 120, are interpreted as low density. 121 - 160 are medium density (iPhone 3GS). 161 - 320, high density (iPhone 4S). 321 - 480 == HD. 481 and higher == 2HD. In general, you should try to use images that are one of these DPIs exactly: 160, 320, or 480, then images will be scaled up or down to the other densities accordingly.

15.11.2. Multi-Images vs regular images

By default all images are imported as multi-images (unless you define the defaultSourceDPIInt theme constant). If you want to import an image as a "regular" image, you can set cn1-source-dpi to 0. For example:

SomeStyle {
    background-image: url(images/my-image.png);
    cn1-source-dpi: 0;
}

You can change the default source DPI for the whole stylesheet by adding defaultSourceDPIInt: 0 to the theme constants. For example:

#Constants {
  defaultSourceDPIInt: 0;
}

Most application templates in Codename One Initializr include this constant by default.

15.11.3. Multi-Images as inputs

If you’ve already generated images in all the appropriate sizes for all densities, you can provide them in the same file structure used by the Codename One XML resource files: The image path is a directory that contains images named after the density that they’re intended to be used for. The possible names include:

  • verylow.png

  • low.png

  • medium.png

  • high.png

  • veryhigh.png

  • 560.png

  • hd.png

  • 2hd.png

  • 4k.png

For example, Given the CSS directives:

MyStyle {
    background-image: url(images/mymultiimage.png);
}

The files would look like:

css/
 +--- mycssfile.css
 +--- images/
       +--- mymultiimage.png/
             +--- verylow.png
             +--- low.png
             +--- medium.png
              ... etc.
Multi-image inputs are supported for local URLs. You can’t use remote (for example, http://) urls with multi-image inputs

15.11.4. Image constants

Theme constants can be images. The convention is to suffix the constant name with "Image" so that it will be treated as an image. Also to the standard url() notation for specifying a constant image, you can provide a simple string name of the image, and the CSS processor will try to find an image by that name specified as a background image for one of the styles. If it can’t find one, it will look inside a special directory named "res" (located in the same directory as the CSS stylesheet), inside which it will look for a directory named the same as the stylesheet, inside which it will look for a directory with the specified multi-image. This directory structure is the same as used for Codename One’s XML resources directory.

For example, In the CSS file "mycssfile.css":

radioSelectedFocusImage: "Radio_btn_Press.png";

Will look for a directory located at res/mycssfile.css/Radio_btn_Press.png/ with the following images:

  • verylow.png

  • low.png

  • medium.png

  • high.png

  • veryhigh.png

  • 560.png

  • hd.png

  • 2hd.png

  • 4k.png

It will then create a multi-image from these images and include them in the resource file.

15.12. Image recipes

15.12.1. Import multiple images in single selector

It’s quite useful to be able to embed images inside the resource file that’s generated from the CSS stylesheet so that you can access the images using the Resources.getImage() method in your app and set it as an icon on a button or label. In this case, it’s easier to create a dummy style that you don’t intend to use and include multiple images in the background-image property like so:

Images {
    background-image: url(images/NowLogo.png),
        url(images/Username-icon.png),
        url(images/Password-icon.png),
        url(images/Name-icon.png),
        url(images/Email-icon.png),
        url(images/SeaIce.png),
        url(images/Back-icon.png),
        url(images/Source-icon.png),
        url(images/Date-icon.png),
        url(images/Arrow-right.png),
        url(images/Share-icon.png),
        url(images/Text-icon.png),
        url(images/Comments-icon.png),
        url(images/RedPlanet.png),
        url(images/News-icon.png),
        url(images/Channels-icon.png),
        url(images/Bookmarks-icon.png),
        url(images/Overview-icon.png),
        url(images/Calendar-icon.png),
        url(images/Timeline-icon.png),
        url(images/Profile-icon.png),
        url(images/Widgets-icon.png),
        url(images/Settings-icon.png),
        url(images/Bookmark-icon.png);
}

Then in Java, you might do something like:

Resources theme = Resources.openLayered("/theme");

Label bookmark = new Label(theme.getImage("Bookmark-icon.png"));

15.12.2. Loading images from URLs

You can also load images from remote URLs. The compiled guide fixture uses a local asset so the build is deterministic and doesn’t depend on network access; application CSS can use the same url(…​) syntax with an HTTPS URL:

ImagesRemote {
    background-image: url(images/remote-logo.png);
}

15.12.3. Generating 9-Piece Image borders

css nine piece border

9-Piece image borders can be created using the image-border and image-border-slice properties.

For example:

NinePiece {
    border-image: url(images/dashbg_landscape.png);
}

In the above example you omitted the border-image-slice property, so it defaults to "40%," which means that the image is sliced 40% from the top, 40% from the bottom, 40% from the left, and 40% from the right.

If you want more specific "slice" points, you can add the border-image-slice property. For example:

NinePiece {
    border-image: url(images/dashbg_landscape.png);
    border-image-slice: 10% 49%;
}

NinePiece2 {
    border-image: url(images/dashbg_landscape.png);
    border-image-slice: 10% 49% 20%;
}

NinePiece3 {
    border-image: url(images/dashbg_landscape.png);
    border-image-slice: 10% 30% 40% 20%;
}

NinePiece4 {
    border-image: url(images/dashbg_landscape.png);
    border-image-slice: 10%;
}

The compiler also produces 9-piece borders on its own, for styles that have no native equivalent. See Border for which styles those are. It paints these images itself during the build, so they need no image file from you and no extra tool. A background image is painted into the generated image, whether it’s a PNG, a JPEG, an SVG or a Lottie file. An animated SVG or Lottie file is painted as it looks before its animation starts.

15.12.4. Image backgrounds

Component backgrounds in Codename One are a common source of confusion for newcomers because there are 3 different properties that can be used to define what a component’s background looks like, and they have priorities:

  1. Background Color - You can specify an RGB color to be used as the background for a component.

  2. Background Image - You can specify an image to be used as the background for a component. Codename One includes settings to define how the image is treated, for example, scale/fill, tile, etc. If a background image is specified, it will override the background color setting - unless the image has transparent regions.

  3. Image Border - You can define a 9-piece image border which will effectively cover the entire background of the component. If an image border is specified, it will override the background image of the component.

A common scenario you may run into is trying to set the background color of a component and seeing no change when you preview the form, because the style had an image background defined - which overrides the background color change.

The potential for confusion is mitigated somewhat, but still exists when using CSS. You can make your intentions explicit by adding the cn1-background-type property to your style. Possible values include:

  • cn1-image-scaled

  • cn1-image-scaled-fill

  • cn1-image-scaled-fit

  • cn1-image-tile-both

  • cn1-image-tile-valign-left

  • cn1-image-tile-valign-center

  • cn1-image-tile-valign-right

  • cn1-image-tile-halign-top

  • cn1-image-tile-halign-center

  • cn1-image-tile-halign-bottom

  • cn1-image-align-bottom

  • cn1-image-align-left

  • cn1-image-align-right

  • cn1-image-align-center

  • cn1-image-align-top-left

  • cn1-image-align-top-right

  • cn1-image-align-bottom-left

  • cn1-image-align-bottom-right

  • cn1-image-border

  • cn1-none

  • none

Example setting background Image to scale fill
MyContainer {
    background-image: url(images/myimage.png);
    cn1-background-type: cn1-image-scaled-fill;
}

15.13. Image compression

CN1 resource files support both PNG and JPEG images, but PNG is the default. Multi-images that are generated by the CSS compiler will be PNG if they include alpha transparency, and JPEG otherwise. This is to try to reduce the file size as much as possible while not sacrificing quality.

15.14. Fonts

This library supports the font, font-size, font-family, font-style, font-weight, and text-decoration properties, as well as the @font-face CSS "at" rule for including TrueType and OpenType fonts.

15.14.1. font-family

By default, CN1’s native fonts are used. The appropriate native font is selected for the provided font-weight and font-style properties. You can also explicitly specify the native font you wish to use in the font-family property. For example:

SideCommand {
    font-family:  "native:MainThin";
}

If you omit the font-family directive altogether, it will use native:MainRegular. The following native fonts are available:

  1. native:MainThin

  2. native:MainLight

  3. native:MainRegular

  4. native:MainBold

  5. native:MainBlack

  6. native:ItalicThin

  7. native:ItalicLight

  8. native:ItalicRegular

  9. native:ItalicBold

  10. native:ItalicBlack

Using bundled fonts

If you want to use a font other than the built-in fonts, you’ll need to define the font using the @font-face rule. For example:

@font-face {
    font-family: "GuideDemoFont";
    src: url(res/GuideDemoFont-Regular.ttf);
}

Both TrueType (.ttf) and OpenType (.otf) files work, upper-case or lower-case. Every platform loads both formats through its own font API, so an OpenType font needs no conversion before you bundle it. Web-only formats such as .woff aren’t supported, and the CSS compiler fails the build on one rather than letting it reach the device.

The compiler reads each font at build time, so a file it can’t parse, or one with no PostScript name, fails the build. That second case is worth knowing about: iOS resolves fonts by their PostScript name, so a font without one renders everywhere except on an iOS device.

Then you’ll be able to reference the font using the specified font-family in any CSS element. For example:

MyLabel {
    font-family: "GuideDemoFont";
}
Where to put the font file

A relative src URL is resolved against the directory that holds the CSS file. You can keep font files directly beside theme.css, or in any subdirectory of it, whichever you prefer:

@font-face {
    font-family: "GuideRootFont";
    src: url(GuideRootFont.ttf);
}

@font-face {
    font-family: "GuideDemoFont Bold";
    src: url(res/GuideDemoFont-Bold.ttf);
}

The font does have to live somewhere under that directory, because only that directory is copied into the build. A font reached through ../, or one that doesn’t exist, fails the build rather than producing an app whose text falls back to the system font. Two @font-face rules naming different files that share a file name also fail, since fonts are deployed by file name alone and one would overwrite the other. Pointing two families at the same file is fine.

Family names, weights and styles

A font-family name that contains spaces must be quoted, both in the @font-face rule and wherever you reference it. An unquoted name is parsed as a list of separate identifiers, so font-family: GuideDemoFont Bold registers the family as GuideDemoFont and collides with your regular weight.

font-weight and font-style select between the built-in native: fonts, but they have no effect once font-family resolves to a @font-face rule. Declare one @font-face per weight and style you need, each with its own family name, as in the example above, then reference the right family from each UIID.

To change the base font of an entire theme, set font-family on the special Default selector, then override the UIIDs that need a bold or italic face:

Default {
    font-family: "GuideRootFont";
}

Title {
    font-family: "GuideDemoFont Bold";
}
Remote and GitHub-hosted fonts

The @font-face directive’s src property will accept both local and remote URLs. The guide fixture below uses a local font so the demo build remains offline and repeatable; application CSS can replace the URL with an HTTPS font URL:

@font-face {
    font-family: "GuideDownloadedFont";
    src: url(res/GuideDemoFont-Regular.ttf);
}

In this case, it will download the myfont.ttf file into the build directory alongside the merged CSS file, and reuse that copy on later builds so that it doesn’t have to make a network request every time. A mvn clean discards the cache and the next build downloads the font again.

Fonts are automatically copied next to the compiled theme.res when the CSS file is compiled, so that they’re distributed with the app and available at runtime. The copy uses the font’s file name only, which means two @font-face rules that point at identically named files in different directories will collide. The copy is also skipped when a file of that name is already there, so run mvn clean after you replace a font file with a different one of the same name.

GitHub URLs

Fonts hosted on GitHub are accessible using a special github: protocol to make it easier to reference such fonts. The compiled guide fixture uses a bundled icon font for offline validation; application CSS can use the same rule shape with a github: URL.

@font-face {
    font-family: "GuideIconFont";
    src: url(res/GuideIconFont.ttf);
}
If a third-party font repository moves or changes licensing, vendor the font into your project and reference it locally so builds stay reproducible.
Fonts loaded at runtime

A font that isn’t known at build time, such as one the app downloads or a user picks, can’t go through @font-face. Font.createTrueTypeFontFromData creates a font from the bytes of a .ttf or .otf file, given either as an InputStream or as a byte[]. The result works like a bundled font: derive it to the size and weight you need and set it on a style.

Label label = new Label("Handlee");
Font base = null;
if (Font.isTrueTypeStreamSupported()) {
    try {
        InputStream in = Storage.getInstance().createInputStream("Handlee-Regular.ttf");
        base = Font.createTrueTypeFontFromData("Handlee", in);
    } catch (IOException err) {
        Log.e(err);
    }
}
if (base == null) {
    base = Font.createTrueTypeFont("native:MainRegular");
}
label.getAllStyles().setFont(base.derive(CN.convertToPixels(4), Font.STYLE_PLAIN));

The name you pass identifies the font in the font cache, so a second call with the same name returns the first font without reading the data again. Give each distinct font its own name.

Font.isTrueTypeStreamSupported() reports whether the platform can do this. The simulator, Android, iOS, macOS, the JavaScript port and the native Windows and Linux ports all can. Elsewhere createTrueTypeFontFromData returns null, so keep a fallback font as the example does.

15.14.2. font-size

It’s best practice to size your fonts using millimetres (rem) (or another "real-world" measurement unit such as inches (in), centimetres (cm), millimetres (mm). This will allow the font to be sized appropriate for all display densities. If you specify size in pixels (px), it will treat it the same as if you sized it in points (pt), where 1pt == 1/72 inches (one seventy-second of an inch).

If you size your font in percentage units (for example, 150%) it will set the font size relative to the medium font size of the platform. This is different than the standard behaviour of a web browser, which would size it relative to the parent element’s font size.

font-size: 150% is the same as font-size: 1.5rem.

You can use system fonts, true type fonts, and native fonts in your CSS stylesheet. True Type fonts need to be defined in a @font-face directive before they can be referenced. True-type fonts and native fonts have the advantage that you can specify their sizes in generic terms (for example, small, medium, large) and in more specific units such as millimeters (mm) or pixels (px).

Normalizing Default Font Size

When trying to make a design look "good" across multiple platforms it can be difficult to deal with the differing default font sizes on different platforms. You may spend hours tweaking your UI to look perfect on iPhone X, only to find out that the fonts are too small when viewed on an android device. You’ve now added theme constants to explicitly set the default font size in "screen-independent-pixels."

Note In this case, 1 screen-independent-pixel is defined as 1/160th of an inch on a device, and 1/96th of an inch on desktop. These values correspond to Android’s definition on device, and Windows' definition on the desktop.

If you add the following to your stylesheet, it will set the default font size to 18 screen-independent pixels (or 18/160th of an inch), which corresponds to the Android native default "medium" font size:

#Constants {
 defaultFontSizeInt: 18;
}
A value of 18 here gives best results across devices.

On the desktop, you may find that 18 is too big. You can define a default font size for tablet and desktop using defaultDesktopFontSizeInt and defaultTabletFontSizeInt respectively. A defaultDesktopFontSizeInt value gives results that match the macOS default font size:

#Constants {
 defaultFontSizeInt: 18;
 defaultDesktopFontSizeInt: 14;
}
How density is determined per platform

The conversion from "screen-independent pixels" or mm to physical pixels uses the device’s PPI. The two mobile ports compute it differently, which is worth keeping in mind when chasing per-platform sizing differences:

  • Android: uses density × 160 from DisplayMetrics, where density is the bucketed scale factor reported by Android (typically 1.0, 1.5, 2.0, 3.0, 3.5, 4.0). Because the buckets are coarse, a phone whose physical density falls between two buckets will report the lower one, so mm-based measurements may render slightly smaller than their nominal physical size.

  • iOS: uses an explicit per-device PPI lookup keyed on the screen’s pixel dimensions (for example, 460ppi for iPhone 12 / 13 / 14 / 15 / 16, 458ppi for the Plus and Pro Max models, 326ppi for older 2× devices). This is exact for catalogued devices. Any iPhone whose resolution isn’t in the table falls through to a default fallback (now 460ppi, since Apple has held that density steady for every non-Plus iPhone since the iPhone 12).

Net result: the same defaultFontSizeInt: 18 may render at slightly different absolute physical sizes on an iPhone vs. An Android device of similar physical size—typically the iOS rendering is the larger of the two when both are at the platform’s default text size. If you need cross-platform pixel-perfect sizing, use platform overrides (@iOS-platform-font-size, etc., via media queries) rather than relying on the conversion math alone.

When a new iPhone model ships with a resolution that isn’t yet in the iOS PPI table, mm-based measurements will use the fallback 460ppi, which is correct to within 1-2% for every modern iPhone. If you discover a model that should use a different value (for example a future Plus/Max device that returns to 458ppi), file an issue so the table can be updated.

15.14.3. text-decoration

15.14.4. Some sample CSS directives

@font-face {
    font-family: "GuideDemoFont";
    src: url(res/GuideDemoFont-Regular.ttf);
}

@font-face {
    font-family: "GuideDemoFont-Bold";
    src: url(res/GuideDemoFont-Bold.ttf);
}

PlainText0p5mm { font-size: 0.5mm; }
PlainText1mm { font-size: 1mm; }
PlainText2mm { font-size: 2mm; }
PlainText5mm { font-size: 5mm; }
PlainText10mm { font-size: 10mm; }
PlainText50mm { font-size: 50mm; }
PlainTextSmall { font-size: small; }
PlainTextMedium { font-size: medium; }
PlainTextLarge { font-size: large; }
PlainText3pt { font-size: 3pt; }
PlainText6pt { font-size: 6pt; }
PlainText12pt { font-size: 12pt; }
PlainText20pt { font-size: 20pt; }
PlainText36pt { font-size: 36pt; }

BoldText { font-weight: bold; }
BoldText1mm { font-weight: bold; font-size: 1mm; }
BoldText2mm { font-weight: bold; font-size: 2mm; }
BoldText3mm { font-weight: bold; font-size: 3mm; }
BoldText5mm { font-weight: bold; font-size: 5mm; }

ItalicText { font-style: italic; }
ItalicText3mm { font-style: italic; font-size: 3mm; }
ItalicBoldText { font-style: italic; font-weight: bold; }

PlainTextUnderline { text-decoration: underline; }
BoldTextUnderline { text-decoration: underline; font-weight: bold; }
ItalicTextUnderline { text-decoration: underline; font-style: italic; }

PlainText3d {
    text-decoration: cn1-3d;
    color: white;
    background-color: #3399ff;
}

BoldText3d {
    text-decoration: cn1-3d;
    font-weight: bold;
    color: white;
    background-color: #3399ff;
}

ItalicText3d {
    text-decoration: cn1-3d;
    font-style: italic;
    color: white;
    background-color: #3399ff;
}

PlainText3dLowered {
    text-decoration: cn1-3d-lowered;
    color: black;
    background-color: #3399ff;
}

BoldText3dLowered {
    text-decoration: cn1-3d-lowered;
    font-weight: bold;
    color: black;
    background-color: #3399ff;
}

ItalicText3dLowered {
    text-decoration: cn1-3d-lowered;
    font-style: italic;
    color: black;
    background-color: #3399ff;
}

PlainText3dShadow {
    text-decoration: cn1-3d-shadow-north;
    color: white;
    background-color: #3399ff;
}

BoldText3dShadow {
    text-decoration: cn1-3d-shadow-north;
    font-weight: bold;
    color: white;
    background-color: #3399ff;
}

ItalicText3dShadow {
    text-decoration: cn1-3d-shadow-north;
    font-style: italic;
    color: white;
    background-color: #3399ff;
}

MainThin {
    font-size: 200%;
    background: radial-gradient(circle at top left, yellow, blue 100%);
}

MainRegular0001 {
    font-family: "native:MainRegular";
    color: blue;
    border: 1px cn1-pill-border blue;
    padding: 2mm;
}

MainRegular0001.pressed {
    font-family: "native:MainRegular";
    background: cn1-pill-border blue;
    color: white;
    border: 1px solid white;
    padding: 2mm;
}

Heading {
    font-size: 4mm;
    font-family: "GuideDemoFont-Bold";
    color: black;
    padding: 2mm;
    text-align: center;
}

15.15. Media queries

You can use media queries to target styles to specific platforms, devices, and device densities. The following media queries are supported:

  1. platform-xxx - Target a specific platform. For example, platform-and, platform-ios, platform-mac, platform-win.

  2. density-xxx - Target a specific device density. For example, density—​low, density-low, density-medium, density-high, density—​high, density-hd, density-2hd, and density-560.

  3. device-xxx - Target a specific device type. For example, device-desktop, device-tablet, device-phone, device-tv (Apple TV / Android TV), and device-watch (Apple Watch / Wear OS). The device-tv and device-watch variants are selected at runtime when Display.isTV() / Display.isWatch() returns true, letting you adapt styling for the 10-foot TV UI or the small wearable screen.

Also to the Codename One specific media tokens above, the CSS compilers also recognize standard dark-mode media queries using prefers-color-scheme: dark. Rules inside these blocks are compiled into $Dark UIIDs automatically (for example, Button becomes $DarkButton, Button.selected becomes $DarkButton.selected).

Listing 13. Example: Dark-mode overrides with standard CSS media query syntax
Button {
    color: #222222;
}

@media (prefers-color-scheme: dark) {
    Button {
        color: #f0f0f0;
        background-color: #000000;
    }

    Button.selected {
        color: #ff0000;
    }
}
Listing 14. Example: Different font colors on Android and iOS. On Android, labels will appear green. On iOS, they will appear red. On all other platforms, they will appear black:
Label {
    color: black;
}

@media platform-and {
    Label {
        color: green;
    }
}

@media platform-ios {
    Label {
        color: red;
    }
}
Listing 15. Example: Different font colors based on device density. On lower densities, labels will be green. On higher densities, labels will be red.
Label {
    color: black;
}

@media density-very-low, density-low, density-medium, density-high {
    Label {
        color: green;
    }
}

@media density-very-high, density-h2, density-2hd, density-560 {
    Label {
        color: red;
    }
}
Listing 16. Example: Different label colors based on device type.
Label {
    color: black;
}

@media device-desktop {
    Label {
        color: green;
    }
}

@media device-tablet, device-phone {
    Label {
        color: red;
    }
}
When deploying your app using the JavaScript port, it will use a platform name derived from the "UserAgent" string in the browser, rather than the result of Display.getPlatformName(), which is used for other ports. When running on Android, then, the platform will be "and." When running on iOS, the platform will be "ios." Etc.

15.15.1. Compound media queries

You can combine multiple media queries together, separated by a comma. Queries of the same type are "OR"ed together. Queries of different types are "AND"ed together. For example if you have a media query that specifies two different device densities (for example, density-low and density-high) the query will match both devices with low density and high density. But, if the query specifies a device density and a platform (for example, density-low and platform-and), then it will match a device if it matches the platform and the density.

Listing 17. Example: Targeting styles to Android devices with high density
@media platform-and, density-high {
    Label {
        color: green;
    }
}
Listing 18. Example: Targeting styles to iOS devices with high or low density
@media platform-ios, density-high, density-low {
    Label {
        color: red;
    }
}
Listing 19. Example: Targeting Mac Desktop:
@media device-desktop, platform-mac {
    Label {
        color: blue;
    }
}

15.15.2. Order or precedence

The order of precedence when applying styles differs slightly from the way styles would be applied in standard CSS. The order of precedence is as follows:

  1. Styles defined inside @media blocks will always take precedence over styles defined outside of @media blocks.

  2. @media blocks with more query matches will take precedence over blocks with fewer query matches. For example, A media block matching density, platform, and device will take precedence over a block that only matches the density and platform.

  3. If the same style is defined in two media blocks which contain the same number of query matches, then the order precedence is platform, device, density in decreasing order. That is, the block that matches on platform will take precedence over the block that matches on density.

  4. If the same style is defined in two media blocks with identical query matches, then the order of precedence is undefined.

15.15.3. Font scaling constants

Sometimes you may find that fonts are coming out too large or too small across the board on certain types of devices. You can use standard media queries to customize font sizes, but you can also use font-scaling constants to scale font sizes for the entire stylesheet based on platform, device, and/or density. Sometimes you may find this approach easier.

For example, consider the following simple stylesheet that defines a font size of 2mm on labels:

Label {
 font-size: 3mm;
}

During testing, perhaps you find that, on desktop, the fonts are a little bit too small. In this case, you can apply a font-scale constant that only applies to the desktop:

#Constants {
 device-desktop-font-scale: "1.5";
}

Label {
 font-size: 3mm;
}

Now, on most devices the Label style will have 3mm fonts. However, on desktop, it will have 4.5mm fonts.

The above would be equivalent to:

Label {
 font-size: 3mm;
}

@media device-desktop {
 Label {
 font-size: 4.5mm;
 }
}
Listing 20. Example: Font-scaling based on device, platform, and density
#Constants {
 device-phone-font-scale: "1.5";
 device-tablet-font-scale: "1.2";
 device-desktop-font-scale: "1.4";
 platform-ios-font-scale: "0.9";
 density-low-font-scale: "1.2";
 platform-ios-density-low-font-scale: "1.3";
}
All matching font-scale constants will be applied to the styles. If you define 3 font-scale constants that all match the current runtime environment, they will all be applied. For example, If there are 3 matching font-scale constants with 2.0, 3.0, and 4.0, then fonts will be scaled by 2*3*4=24!

Graphics and games

16. Graphics, drawing, images, and fonts

Drawing is considered a low-level API that might introduce some platform fragmentation.

16.1. Basics - where and how to draw manually

The Graphics class handles drawing basics, shapes, images, and text. Developers never instantiate it directly; the Codename One API passes it in.

You can gain access to a Graphics object using one of the following methods:

  • Derive Component or a subclass of Component - Component includes many methods that let developers change drawing behavior. Override them to change how the component is drawn:

    • paint(Graphics) - invoked to draw the component, this can be overridden to draw the component from scratch.

    • paintBackground(Graphics) / paintBackgrounds(Graphics) - these allow overriding the way the component background is painted although you would probably be better off implementing a painter (see below).

    • paintBorder(Graphics) - allows overriding the process of drawing a border, notice that border drawing might differ based on the style of the component.

    • paintComponent(Graphics) - allows painting the components contents while leaving the default paint behavior to the style.

    • paintScrollbars(Graphics), paintScrollbarX(Graphics), paintScrollbarY(Graphics) allows overriding the behavior of scrollbar painting.

  • Implement the painter interface; this interface can be used as a GlassPane or a background painter.

    The painter interface is simple and includes one paint method. It lets developers perform custom painting without subclassing Component. Painters can be chained together to create elaborate paint behavior with the PainterChain class.

    • Glass pane - a glass pane allows developers to paint on top of the form painting. This allows an overlay effect on top of a form.

      At first, a glass pane may seem like overriding the Form’s paint method and drawing after super.paint(g) completes. It isn’t the same. When a component repaints by invoking repaint(), that component is drawn, and Form’s paint() method isn’t invoked. The glass pane painter is invoked in those cases and behaves as expected.

      Container has a glass-pane method called paintGlass(Graphics), which you can override to provide a similar effect at the Container level. This is useful for complex containers such as Table, which draws its lines using this approach.

    • Background painter - the background painter is installed through the style. By default, Codename One installs its own custom background painter. Installing a custom painter lets a developer define how the component background is drawn.
      Many background-style behaviors can also be achieved using styles alone.

A common mistake is overriding the paint(Graphics) method of Form. The problem is that a form has child components that may request a repaint. To avoid that, place a paintable component in the center of the Form, or override the glass pane or background painter.

A paint method can be implemented as such:

// hide the title
Form hi = new Form("", new BorderLayout());
hi.add(BorderLayout.CENTER, new Component() {
@Override
public void paint(Graphics g) {
// red color
g.setColor(0xff0000);

// paint the screen in red
g.fillRect(getX(), getY(), getWidth(), getHeight());

// draw hi world in white text in the top left corner of the screen
g.setColor(0xffffff);
g.drawString("Hi World", getX(), getY());
}
});
hi.show();
Hi world demo code under the iOS theme
Figure 207. Hi world demo code under the iOS theme; the paint fills the form and the status bar strip above it belongs to the platform

16.1.1. Painting with gradients

Solid colors are the starting point. Graphics also understands "paint" objects that describe gradients and other patterns. You can pass an instance of Paint to setColor(Paint) in place of an integer color value to activate a gradient for later fill and draw operations. The LinearGradientPaint class is the most common option and accepts a list of color stops along a line:

LinearGradientPaint gradient = new LinearGradientPaint(
        getX(), getY(), getX() + getWidth(), getY(),  // horizontal gradient
        new float[] {0f, 0.5f, 1f},
        new int[] {0xff4285f4, 0xff34a853, 0xfffbbc05},
        MultipleGradientPaint.CycleMethod.NO_CYCLE,
        MultipleGradientPaint.ColorSpaceType.SRGB,
        null
);
g.setColor(gradient);
// a Paint is consulted by fillShape; fillRect still uses the integer colour
g.fillShape(new Rectangle(getX(), getY(), getWidth(), getHeight()));

The fillLinearGradient() convenience methods (with optional repeat flag) provide a shorthand when you need a two-color gradient without constructing your own Paint object.

Radial gradients are equally straightforward using fillRadialGradient() or fillRectRadialGradient(), which can render circular and rectangular radial transitions respectively. These APIs accept the inner/outer colors, focal point, and spread so you can combine them with linear gradients to build sophisticated backgrounds and lighting effects.

For the full CSS gradient range, Graphics exposes a single fillGradient method that consumes a Gradient value object. Gradient is a Paint subclass with three concrete forms - LinearGradient, RadialGradient, ConicGradient - following the same pattern as the Shape hierarchy:

int[] colors  = { 0xffff0080, 0xffff8c00, 0xff40e0d0 };
float[] stops = { 0f, 0.5f, 1f };

// one band each, so all three are visible at once
int band = getHeight() / 3;
g.fillGradient(new LinearGradient(45f, colors, stops),
        getX(), getY(), getWidth(), band);

RadialGradient circle = new RadialGradient(colors, stops);
circle.setShape(RadialGradient.SHAPE_CIRCLE)
      .setExtent(RadialGradient.EXTENT_FARTHEST_CORNER);
g.fillGradient(circle, getX(), getY() + band, getWidth(), band);

g.fillGradient(new ConicGradient(colors, stops),
        getX(), getY() + band * 2, getWidth(), band);

Gradient carries the cycle method (CYCLE_NONE / CYCLE_REPEAT / CYCLE_REFLECT) for repeating / reflected fills. Each port implements fillGradient via the fastest native shader available - Java2D LinearGradientPaint / RadialGradientPaint on the simulator, LinearGradient / RadialGradient / SweepGradient shaders on Android - and falls back to a software rasterizer that calls Gradient#sampleArgb per pixel where no native shader exists.

16.1.2. Image blur

Graphics.gaussianBlur(Image, float radius) returns a blurred copy of an image using the platform’s fastest path (Core Image on iOS, RenderScript / RenderEffect on Android, JHLabs GaussianFilter in the simulator). The same blur is reachable from CSS via the filter: blur(<length>) and backdrop-filter: blur(<length>) properties, which are stored on the component’s Style as filterBlurRadius and backdropFilterBlurRadius.

16.2. Glass pane

The GlassPane `in Codename One is inspired by the Swing `GlassPane & LayeredPane with a few twists. You tried to imagine how Swing developers would have implemented the glass pane knowing what they do now about painters and Swings learning curve. But first: what’s the glass pane?

A typical Codename One application is essentially composed of 3 layers (this is a gross simplification though), the background painters are responsible for drawing the background of all components including the main form. The component draws its own content (which might overrule the painter) and the glass pane paints last…​

Form layout graphic
Figure 208. Form layout graphic

Essentially the glass pane is a painter that allows you to draw an overlay on top of the Codename One application.

Overriding the paint method of a form isn’t a substitute for glasspane as it would appear to work initially, when you enter a Form. For example, when modifying an element within the form that element gets repainted not the entire Form!

If you have a form with a Button and text drawn on top using the Form’s paint method it would get erased whenever the button gets focus.

The glass pane is called whenever a component gets painted, it paints within the clipping region of the component hence it won’t break the rest of the components on the Form which weren’t modified.

You can set a painter on a form using code like this:

hi.setGlassPane(new Painter() {
    @Override
    public void paint(Graphics g, Rectangle rect) {
    }
});

Or you can use Java 8 lambdas to tighten the code a bit:

hi.setGlassPane((g, rect) -> {
});

PainterChain allows you to chain many painters together to perform different logical tasks such as a validation painter coupled with a fade out painter. The sample below shows a crude validation panel that allows you to draw error icons next to components while exceeding their physical bounds as is common in many user interfaces

Form hi = new Form("Glass Pane", new BoxLayout(BoxLayout.Y_AXIS));
Style s = UIManager.getInstance().getComponentStyle("Label");
s.setFgColor(0xff0000);
s.setBgTransparency(0);
Image warningImage = FontImage.createMaterial(FontImage.MATERIAL_WARNING, s).toImage();
TextField tf1 = new TextField("My Field");
tf1.getAllStyles().setMarginUnit(Style.UNIT_TYPE_DIPS);
tf1.getAllStyles().setMargin(5, 5, 5, 5);
hi.add(tf1);
hi.setGlassPane((g, rect) -> {
int x = tf1.getAbsoluteX() + tf1.getWidth();
int y = tf1.getAbsoluteY();
x -= warningImage.getWidth() / 2;
y += (tf1.getHeight() / 2 - warningImage.getHeight() / 2);
g.drawImage(warningImage, x, y);
});
hi.show();
The glass pane draws the warning sign on the border of the component peeking out
Figure 209. The glass pane draws the warning sign on the border of the component peeking out

16.3. Shapes & transforms

The graphics API provides a high performance shape API that allows drawing arbitrary shapes by defining paths and curves and caching the shape drawn in the GPU.

16.4. Device support

Shapes and transforms ship with all Codename One’s actively maintained ports (Android, iOS, JavaScript, and desktop/Simulator). Older platforms that have reached end of life may lack these APIs, so keep the guard code shown below if you still target them with legacy builds.

Notice that perspective transform is missing from the desktop/simulator port. No real equivalent to perspective transform in Java SE that you could use.

16.5. A 2D drawing app

You can show shape drawing with a simple example of a drawing app, that allows the user to tap the screen to draw a contour picture.

The app works by keeping a GeneralPath in memory, and adding points as Bézier curves. Whenever a point is added, the path is redrawn to the screen.

The center of the app is the DrawingCanvas class, which extends Component:

public class DrawingCanvas extends Component {
    GeneralPath p = new GeneralPath();
    int strokeColor = 0x0000ff;
    int strokeWidth = 10;

    public void addPoint(float x, float y){
        // To be written
    }

    @Override
    protected void paintBackground(Graphics g) {
        super.paintBackground(g);
            Stroke stroke = new Stroke(
                strokeWidth,
                Stroke.CAP_BUTT,
                Stroke.JOIN_ROUND, 1f
            );
            g.setColor(strokeColor);

            // Draw the shape
            g.drawShape(p, stroke);

    }

    @Override
    public void pointerPressed(int x, int y) {
        addPoint(x-getParent().getAbsoluteX(), y-getParent().getAbsoluteY());
    }
}

Conceptually this is basic component. You will be overriding the paintBackground() method to draw the path. You keep a reference to a GeneralPath object (which is the concrete implementation of the Shape interface in Codename One) to store each successive point in the drawing. You also parametrize the stroke width and color.

The implementation of the paintBackground() method (shown above) should be straight forward. It creates a stroke of the appropriate width, and sets the color on the graphics context. Then it calls drawShape() to render the path of points.

16.5.1. Implementing addpoint()

The addPoint method is designed to allow you to add points to the drawing. A simple implementation that uses straight lines rather than curves might look like this:

private float lastX = -1;
private float lastY = -1;

public void addPoint(float x, float y) {
    if (lastX == -1) {
        // this is the first point... Don't draw a line yet
        p.moveTo(x, y);
    } else {
        p.lineTo(x, y);
    }
    lastX = x;
    lastY = y;

    repaint();
}

The sample introduces a couple of house-keeping member vars (lastX and lastY) to store the last point that was added that you know whether this is the first tap or a later tap. The first tap triggers a moveTo() call, whereas later taps trigger lineTo() calls, which draw lines from the last point to the current point.

A drawing might look like this:

lineTo example
Figure 210. lineTo example

16.5.2. Using Bézier curves

Your previous implementation of addPoint() used lines for each segment of the drawing. Now make a change to allow for smoother edges by using quadratic curves instead of lines.

Codename One’s GeneralPath class includes two methods for drawing curves:

  1. quadTo() : Appends a quadratic Bézier curve. It takes 2 points: a control point, and an end point.

  2. curveTo() : Appends a cubic Bézier curve, taking 3 points: 2 control points, and an end point.

See the General Path javadocs for the full API.

You will make use of the quadTo() method to append curves to the drawing as follows:

private boolean odd=true;
public void addPoint(float x, float y){
    if ( lastX == -1 ){
        p.moveTo(x, y);

    } else {
        float controlX = odd ? lastX : x;
        float controlY = odd ? y : lastY;
        p.quadTo(controlX, controlY, x, y);
    }
    odd = !odd;
    lastX = x;
    lastY = y;
    repaint();
}

This change should be straight forward except, perhaps, the business with the odd variable. Since quadratic curves require two points (also to the implied starting point), you can’t take the last tap point and the current tap point. You need a point between them to act as a control point. This is where you get the curve from. The control point works by exerting a sort of "gravity" on the line segment, to pull the line towards it. This results in the line being curved. The example uses the odd marker to alternate the control point between positions above the line and below the line.

A drawing from the resulting app looks like:

Result of quadTo example
Figure 211. Result of quadTo example

16.5.3. Detecting platform support

The DrawingCanvas example is a bit naive in that it assumes that the device supports the shape API. Running this code on a device that doesn’t support the Shape API would draw a blank canvas where the shape was expected to be drawn. You can fall back gracefully if you make use of the Graphics.isShapeSupported() method. For example:

@Override
protected void paintBackground(Graphics g) {
    super.paintBackground(g);
    if ( g.isShapeSupported() ){
       // do my shape drawing code here
    } else {
        // draw an alternate representation for device
        // that doesn't support shapes.
        // E.g. You could defer to the Pisces
        // library in this case
    }

}

16.6. Transforms

The Graphics class has included limited support for 2D transformations for some time now including scaling, rotation, and translation:

  • scale(x,y) : Scales drawing operations by a factor in each direction.

  • translate(x,y) : Translates drawing operations by an offset in each direction.

  • rotate(angle) : Rotates about the origin.

  • rotate(angle, px, py) : Rotates about a pivot point.

scale() and rotate() methods are available on platforms that support Affine transforms. See table X for a compatibility list.

16.6.1. Device support

All current Codename One ports expose affine transforms (that’s: scale() and rotate()). Use the following table as a quick reference when deciding whether you need a fallback path.

Table 10. Transforms Device Support

Platform

Affine Supported

Simulator/Desktop

Yes

iOS

Yes

Android

Yes

JavaScript

Yes

You can check if a particular Graphics context supports rotation and scaling using the isAffineSupported() method.

For example:

public void paint(Graphics g){
    if ( g.isAffineSupported() ){
        // Do something that requires rotation and scaling

    } else {
        // Fallback behavior here
    }
}

16.7. Example: Drawing an analog clock

The following sections implement an analog clock component. This will show three key concepts in Codename One’s graphics:

  1. Using the GeneralPath class for drawing arbitrary shapes.

  2. Using Graphics.translate() to translate your drawing position by an offset.

  3. Using Graphics.rotate() to rotate your drawing position.

There are three separate things that need to be drawn in a clock:

  1. The tick marks. For example: most clocks will have a tick mark for each second, larger tick marks for each hour, and sometimes even larger tick marks for each quarter-hour.

  2. The numbers. You will draw the clock numbers (1 through 12) in the appropriate positions.

  3. The hands. You will draw the clock hands to point at the appropriate points to display the current time.

16.7.1. The AnalogClock Component

Your clock will extend the Component class, and override the paintBackground() method to draw the clock as follows:

public class AnalogClock extends Component {
    Date currentTime = new Date();

    @Override
    public void paintBackground(Graphics g) {
        // Draw the clock in this method
    }
}

16.7.2. Setting up the parameters

Before you actually draw anything, take a moment to figure out what values you need to know to draw an effective clock. Minimally, you need two values:

  1. The center point of the clock.

  2. The radius of the clock.

The clock also exposes the following parameters to help customize how it’s rendered:

  1. The padding (that’s: the space between the edge of the component and the edge of the clock circle.

  2. The tick lengths. The example uses 3 different lengths of tick marks on this clock. The longest ticks will be displayed at quarter points (that’s: 12, 3, 6, and 9). Slightly shorter ticks will be displayed at the five-minute marks (that’s: where the numbers appear), and the remaining marks (corresponding with seconds) will be short:

// Hard code the padding at 10 pixels for now
double padding = 10;

// Clock radius
double r = Math.min(getWidth(), getHeight())/2-padding;

// Center point.
double cX = getX()+getWidth()/2;
double cY = getY()+getHeight()/2;

//Tick Styles
int tickLen = 10;  // short tick
int medTickLen = 30;  // at 5-minute intervals
int longTickLen = 50; // at the quarters
int tickColor = 0xCCCCCC;
Stroke tickStroke = new Stroke(2f, Stroke.CAP_BUTT, Stroke.JOIN_ROUND, 1f);

16.7.3. Drawing the tick marks

For the tick marks, you will use a single GeneralPath object, making use of the moveTo() and lineTo() methods to draw each individual tick:

// a fresh path each repaint, otherwise the segments accumulate
GeneralPath ticksPath = new GeneralPath();
        // Draw a tick for each "second" (1 through 60)
for ( int i=1; i<= 60; i++){
    // default tick length is short
    int len = tickLen;
    if ( i % 15 == 0 ){
        // Longest tick on quarters (every 15 ticks)
        len = longTickLen;
    } else if ( i % 5 == 0 ){
        // Medium ticks on the '5's (every 5 ticks)
        len = medTickLen;
    }

    double di = (double)i; // tick num as double for easier math

    // Get the angle from 12 O'Clock to this tick (radians)
    double angleFrom12 = di/60.0*2.0*Math.PI;

    // Get the angle from 3 O'Clock to this tick
        // Note: 3 O'Clock corresponds with zero angle in unit circle
        // Makes it easier to do the math.
    double angleFrom3 = Math.PI/2.0-angleFrom12;

    // Move to the outer edge of the circle at correct position
    // for this tick.
    ticksPath.moveTo(
            (float)(cX+Math.cos(angleFrom3)*r),
            (float)(cY-Math.sin(angleFrom3)*r)
    );

    // Draw line inward along radius for length of tick mark
    ticksPath.lineTo(
            (float)(cX+Math.cos(angleFrom3)*(r-len)),
            (float)(cY-Math.sin(angleFrom3)*(r-len))
    );
}

// Draw the full shape onto the graphics context.
g.setColor(tickColor);
g.drawShape(ticksPath, tickStroke);
This example uses a little bit of trigonometry to calculate the (x,y) coordinates of the tick marks based on the angle and the radius. If math isn’t your thing, don’t worry. This example makes use of the identities: x=r*cosθ and y=r*sinθ.

At this point your clock should include a series of tick marks orbiting a blank center as shown below:

Drawing tick marks on the watch face
Figure 212. Drawing tick marks on the watch face

16.7.4. Drawing the numbers

The Graphics.drawString(str, x, y) method allows you to draw text at any point of a component. The tricky part here is calculating the correct x and y values for each string so that the number appears in the correct location.

For the purposes of this tutorial, you will use the following strategy. For each number (1 through 12):

  1. Use the Graphics.translate(x,y) method to apply a translation from the clock’s center point to the point where the number should appear.

  2. Draw number (using drawString()) at the clock’s center. It should be rendered at the correct point due to your translation.

  3. Invert the translation performed in step 1:

for ( int i=1; i<=12; i++){
    // Calculate the string width and height so we can center it properly
    String numStr = ""+i;
    int charWidth = g.getFont().stringWidth(numStr);
    int charHeight = g.getFont().getHeight();

    double di = (double)i;  // number as double for easier math

    // Calculate the position along the edge of the clock where the number should
    // be drawn
     // Get the angle from 12 O'Clock to this tick (radians)
    double angleFrom12 = di/12.0*2.0*Math.PI;

    // Get the angle from 3 O'Clock to this tick
        // Note: 3 O'Clock corresponds with zero angle in unit circle
        // Makes it easier to do the math.
    double angleFrom3 = Math.PI/2.0-angleFrom12;

    // Get diff between number position and clock center
    int tx = (int)(Math.cos(angleFrom3)*(r-longTickLen));
    int ty = (int)(-Math.sin(angleFrom3)*(r-longTickLen));

    // For 6 and 12 we will shift number slightly so they're more even
    if ( i == 6 ){
        ty -= charHeight/2;
    } else if ( i == 12 ){
        ty += charHeight/2;
    }

    // Translate the graphics context by delta between clock center and
    // number position
    g.translate(
            tx,
            ty
    );


    // Draw number at clock center.
    g.drawString(numStr, (int)cX-charWidth/2, (int)cY-charHeight/2);

    // Undo translation
    g.translate(-tx, -ty);

}
This example is, admittedly, a little contrived to allow for a demonstration of the Graphics.translate() method. You could have as passed the exact location of the number to drawString() rather than draw at the clock center and translate to the correct location.

Now, you should have a clock with tick marks and numbers as shown below:

Drawing the numbers on the watch face
Figure 213. Drawing the numbers on the watch face

16.7.5. Drawing the hands

The clock will include three hands: Hour, Minute, and Second. You will use a separate GeneralPath object for each hand. For the positioning/angle of each, use the following strategy:

  1. Draw the hand at the clock center pointing toward 12 (straight up).

  2. Translate the hand slightly down so that it overlaps the center.

  3. Rotate the hand at the appropriate angle for the current time, using the clock center as a pivot point.

Drawing the Second Hand:

For the "second" hand, you will use a simple line from the clock center to the inside edge of the medium tick mark at the 12 o’clock position:

GeneralPath secondHand = new GeneralPath();
secondHand.moveTo((float)cX, (float)cY);
secondHand.lineTo((float)cX, (float)(cY-(r-medTickLen)));

And you will translate it down slightly so that it overlaps the center. This translation will be performed on the GeneralPath object directly rather than through the Graphics context:

Shape translatedSecondHand = secondHand.createTransformedShape(
    Transform.makeTranslation(0f, 5)
);

Rotating the Second Hand::

The rotation of the second hand will be performed in the Graphics context through the rotate(angle, px, py) method. This requires you to calculate the angle. The px and py arguments constitute the pivot point of the rotation, which, in your case will be the clock center.

The rotation pivot point is expected to be in absolute screen coordinates rather than relative coordinates of the component. You therefore need to get the absolute clock center position to perform the rotation:
// Calculate the angle of the second hand
Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
double second = (double)(calendar.get(Calendar.SECOND));
double secondAngle = second/60.0*2.0*Math.PI;

// Get absolute center position of the clock
double absCX = getAbsoluteX()+cX-getX();
double absCY = getAbsoluteY()+cY-getY();

// keep whatever transform the caller had, rather than resetting to none
Transform originalTransform = g.getTransform();
g.rotate((float)secondAngle, (int)absCX, (int)absCY);
g.setColor(0xff0000);
g.drawShape(
        translatedSecondHand,
        new Stroke(2f, Stroke.CAP_BUTT, Stroke.JOIN_BEVEL, 1f)
);
g.setTransform(originalTransform);
Put the transform back when you’re done with the rotation, or the drawing that follows uses your rotated coordinate system. Save it with getTransform() first and restore it with setTransform(), as the sample above does. resetAffine() looks like the way to do this and isn’t: it clears the transform entirely, including one a parent set before your component was painted.

Drawing the Minute And Hour Hands:

The mechanism for drawing the hour and minute hands is largely the same as for the minute hand, with a couple of added complexities though:

  1. You will make these hands trapezoidal, and almost triangular rather than using a simple line, which means the GeneralPath construction will be slightly more complex.

  2. Calculation of the angles will be slightly more complex because they need to consider many parameters. For example: The hour hand angle is informed by both the hour of the day and the minute of the hour.

The remaining drawing code is as follows:

// Draw the minute hand
GeneralPath minuteHand = new GeneralPath();
minuteHand.moveTo((float)cX, (float)cY);
minuteHand.lineTo((float)cX+6, (float)cY);
minuteHand.lineTo((float)cX+2, (float)(cY-(r-tickLen)));
minuteHand.lineTo((float)cX-2, (float)(cY-(r-tickLen)));
minuteHand.lineTo((float)cX-6, (float)cY);
minuteHand.closePath();

// Translate the minute hand slightly down so it overlaps the center
Shape translatedMinuteHand = minuteHand.createTransformedShape(
    Transform.makeTranslation(0f, 5)
);

double minute = (double)(calendar.get(Calendar.MINUTE)) +
        (double)(calendar.get(Calendar.SECOND))/60.0;

double minuteAngle = minute/60.0*2.0*Math.PI;

// Rotate and draw the minute hand, keeping the caller's transform
Transform beforeMinuteHand = g.getTransform();
g.rotate((float)minuteAngle, (int)absCX, (int)absCY);
g.setColor(0x000000);
g.fillShape(translatedMinuteHand);
g.setTransform(beforeMinuteHand);


// Draw the hour hand
GeneralPath hourHand = new GeneralPath();
hourHand.moveTo((float)cX, (float)cY);
hourHand.lineTo((float)cX+4, (float)cY);
hourHand.lineTo((float)cX+1, (float)(cY-(r-longTickLen)*0.75));
hourHand.lineTo((float)cX-1, (float)(cY-(r-longTickLen)*0.75));
hourHand.lineTo((float)cX-4, (float)cY);
hourHand.closePath();

Shape translatedHourHand = hourHand.createTransformedShape(
    Transform.makeTranslation(0f, 5)
);

//Calendar cal = Calendar.getInstance().get
double hour = (double)(calendar.get(Calendar.HOUR_OF_DAY)%12) +
        (double)(calendar.get(Calendar.MINUTE))/60.0;

double angle = hour/12.0*2.0*Math.PI;
Transform beforeHourHand = g.getTransform();
g.rotate((float)angle, (int)absCX, (int)absCY);
g.setColor(0x000000);
g.fillShape(translatedHourHand);
g.setTransform(beforeHourHand);

16.7.6. The final result

At this point, you have a complete clock as shown below:

The final result - fully rendered watch face
Figure 214. The final result - fully rendered watch face

16.7.7. Animating the clock

The current clock component is cool, but it’s static. It displays the time at the point the clock was created. You discussed low-level animations in the animation section of the guide, here you will show a somewhat more elaborate example.

To animate your clock so that it updates once per second, you need to do two things:

  1. Implement the animate() method to show when the clock needs to be updated/re-drawn.

  2. Register the component with the form so that it will receive animation "pulses."

The animate() method in the AnalogClock class:

long lastRenderedTime = 0;

@Override
public boolean animate() {
    long now = System.currentTimeMillis();
    if ( now/1000 != lastRenderedTime/1000){
        currentTime.setTime(now);
        lastRenderedTime = now;
        return true;
    }
    return false;
}

This method will be invoked on each "pulse" of the EDT. It checks the last time the clock was rendered and returns true if the clock hasn’t been rendered in the current "time second" interval. Otherwise it returns false. This ensures that the clock will be redrawn when the time changes.

16.8. Starting and stopping the animation

Animations can be started and stopped through the Form.registerAnimated(component) and Form.deregisterAnimated(component) methods. The sample encapsulates these calls in start() and stop() methods in the component as follows:

public void start(){
    getComponentForm().registerAnimated(this);
}

public void stop(){
    getComponentForm().deregisterAnimated(this);
}

The code to instantiate the clock, and start the animation would be something like:

AnalogClock clock = new AnalogClock();
// the clock draws to its own bounds and declares no preferred size, so it
// needs a region that stretches -- in a flow or box layout it would be 0x0
Form hi = new Form("Clock", new BorderLayout());
hi.add(BorderLayout.CENTER, clock);
hi.show();
clock.start();

16.9. Shape clipping

Clipping is one of the core tenants of graphics programming, you define the boundaries for drawing and when you exceed said boundaries things aren’t drawn. Shape clipping allows you to clip based on any arbitrary Shape and not a rectangle, this allows some unique effects generated in runtime.

For example: this code allows you to draw a rather complex image of duke:

Image duke = null;
try {
    // duke.png is just the default Codename One icon copied into place
    duke = Image.createImage("/duke.png");
} catch(IOException err) {
    Log.e(err);
}
final Image finalDuke = duke;

Form hi = new Form("Shape Clip");

// We create a 50 x 100 shape, this is arbitrary since we can scale it easily
GeneralPath path = new GeneralPath();
path.moveTo(20,0);
path.lineTo(30, 0);
path.lineTo(30, 100);
path.lineTo(20, 100);
path.lineTo(20, 15);
path.lineTo(5, 40);
path.lineTo(5, 25);
path.lineTo(20,0);

Stroke stroke = new Stroke(0.5f, Stroke.CAP_ROUND, Stroke.JOIN_ROUND, 4);
hi.getContentPane().getUnselectedStyle().setBgPainter((Graphics g, Rectangle rect) -> {
    g.setColor(0xff);
    float widthRatio = ((float)rect.getWidth()) / 50f;
    float heightRatio = ((float)rect.getHeight()) / 100f;
    g.scale(widthRatio, heightRatio);
    g.translate((int)(((float)rect.getX()) / widthRatio), (int)(((float)rect.getY()) / heightRatio));
    g.setClip(path);
    g.setAntiAliased(true);
    g.drawImage(finalDuke, 0, 0, 50, 100);
    g.setClip(path.getBounds());
    g.drawShape(path, stroke);
    g.translate(-(int)(((float)rect.getX()) / widthRatio), -(int)(((float)rect.getY()) / heightRatio));
    g.resetAffine();
});

hi.show();
Shape Clipping used to clip the image of duke within the given shape
Figure 215. Shape Clipping used to clip the image of duke within the given shape
Notice that this functionality isn’t available on all platforms so you need to test if shaped clipping is supported using isShapeClipSupported().

16.10. The coordinate system

The Codename One coordinate system follows the example of Swing (and many other - but not all-graphics libraries) and places the origin in the upper left corner of the screen. X-values grow to the right, and Y-values grow downward as illustrated below:

The Codename One graphics coordinate space
Figure 216. The Codename One graphics coordinate space

The screen origin is in the top left corner of the screen. Given this information, consider the method call on the Graphics context g:

g.drawRect(10,10, 100, 100);

Where would this rectangle be drawn on the screen?

If you answered something like "10 pixels from the top, and 10 pixels from the left of the screen," you might be right. It depends on whether the graphics has a translation or transform applied to it. If there is currently a translation of (20,20) (that’s: 20 pixels to the right, and 20 pixels down), then the rectangle would be rendered at (30, 30).

You can always find out the current translation of the graphics context using the Graphics.getTranslateX() and Graphics.getTranslateY() methods:

// Find out the current translation
int currX = g.getTranslateX();
int currY = g.getTranslateY();

// Reset the translation to zeroes
g.translate(-currX, -currY);

// Now we are working in absolute screen coordinates
g.drawRect(10, 10, 100, 100);

// This rectangle should now be drawn at the exact screen
// coordinates (10,10).

//Restore the translation
g.translate(currX, currY);
This example glosses over issues such as clipping and transforms which may cause it to not work as you expect. For example: When painting a component inside its paint() method, there is a clip applied to the context so that the content you draw within the bounds of the component will be seen.

If, also, there is a transform applied that rotates the context 45 degrees clockwise, then the rectangle will be drawn at a 45-degree angle with its top left corner somewhere on the left edge of the screen.

You don’t have to worry about the exact screen coordinates for the things you paint. Most of the time, you will be concerned with relative coordinates.

16.10.1. Relative coordinates

Usually, when you’re drawing onto a Graphics context, you’re doing so within the context of a Component’s paint() method (or one of its variants). In this case, you don’t care what the exact screen coordinates are of your drawing. You’re concerned with their relative location within the coordinate. You can leave the positioning (and even sizing) of the coordinate up to Codename One. Thank you for reading.

To show this, create a simple component called Rectangle component, that draws a rectangle on the screen. You will use the component’s position and size to dictate the size of the rectangle to be drawn. And you will keep a 5 pixel padding between the edge of the component and the edge of your rectangle:

class RectangleComponent extends Component {
    public void paint(Graphics g){
        g.setColor(0x0000ff);
        g.drawRect(getX()+5, getY()+5, getWidth()-10, getHeight()-10);
    }
}

The result is as follows:

The rectangle component
Figure 217. The rectangle component
The x and y coordinates that are passed to the drawRect(x,y,w,h) method are relative to the component’s parent’s origin — not the component itself.. Its parent. This is why you the x position is getX()+5 and not 5.

16.10.2. Transforms and rotations

Unlike the Graphics drawXXX primitives, methods for setting transformations, including scale(x,y) and rotate(angle), are always applied in screen coordinates. This can be confusing at first, because you may be unsure whether to provide a relative coordinate or an absolute coordinate for a given method.

The general rule is:

  1. All coordinates passed to the drawXXX() and fillXXX() methods will be subject to the graphics context’s transform and translation settings.

  2. All coordinates passed to the context’s transformation settings are considered to be screen coordinates, and aren’t subject to current transform and translation settings.

Take your RectangleComponent as an example. Suppose you want to rotate the rectangle by 45 degrees, your first try might look something like:

class RectangleComponent extends Component {

        @Override
        protected Dimension calcPreferredSize() {
            return new Dimension(250,250);
        }

        public void paint(Graphics g) {
            g.setColor(0x0000ff);
            g.rotate((float) (Math.PI / 4.0));
            g.drawRect(getX() + 5, getY() + 5, getWidth() - 10, getHeight() - 10);
            g.rotate(-(float) (Math.PI / 4.0));
        }
    }
When performing rotations and transformations inside a paint() method, always remember to revert your transformations at the end of the method so that it doesn’t pollute the rendering pipeline for later components.

The behavior of this rotation will vary based on where the component is rendered on the screen. To show this, try to place five of these components on a form inside a BorderLayout and see how it looks:

class MyForm extends Form {

    public MyForm() {
        super("Rectangle Rotations", new BorderLayout());
        // one per position, so the rotation can be compared across the screen
        add(BorderLayout.NORTH, new RectangleComponent());
        add(BorderLayout.SOUTH, new RectangleComponent());
        add(BorderLayout.EAST, new RectangleComponent());
        add(BorderLayout.WEST, new RectangleComponent());
        add(BorderLayout.CENTER, new RectangleComponent());
    }
}
new MyForm().show();

The result is as follows:

Rotating the rectangle
Figure 218. Rotating the rectangle

This may not be an intuitive outcome since you drew five rectangle components, but you see a portion of one rectangle. The reason is that the rotate(angle) method uses the screen origin as the pivot point for the rotation. Components nearer to this pivot point will experience a less dramatic effect than components farther from it. In your case, the rotation has caused all rectangles except the first one to be rotated outside the bounds of their containing component, and are therefore being clipped. A more sensible solution for your component would be to place the rotation pivot point somewhere inside the component. That way all the components would look the same. Some possibilities would be:

Top Left Corner:

public void paint(Graphics g) {
    g.setColor(0x0000ff);
    g.rotate((float)(Math.PI/4.0), getAbsoluteX(), getAbsoluteY());
    g.drawRect(getX() + 5, getY() + 5, getWidth() - 10, getHeight() - 10);
    g.rotate(-(float) (Math.PI / 4.0), getAbsoluteX(), getAbsoluteY());
}
Rotating the rectangle with wrong pivot point
Figure 219. Rotating the rectangle with wrong pivot point

Center:

public void paint(Graphics g) {
    g.setColor(0x0000ff);
    g.rotate(
        (float)(Math.PI/4.0),
        getAbsoluteX()+getWidth()/2,
        getAbsoluteY()+getHeight()/2
    );
    g.drawRect(getX() + 5, getY() + 5, getWidth() - 10, getHeight() - 10);
    g.rotate(
        -(float)(Math.PI/4.0),
        getAbsoluteX()+getWidth()/2,
        getAbsoluteY()+getHeight()/2
    );
}
Rotating the rectangle with the center pivot point
Figure 220. Rotating the rectangle with the center pivot point

You could also use the Graphics.setTransform() class to apply rotations and other complex transformations (including 3D perspective transforms), but that belongs to its own topic as it’s a little bit more complex.

16.10.3. Global alpha & Anti-Aliasing

Up to this point you’ve relied on the per-pixel alpha stored in images and gradients. Graphics also lets you apply a global alpha multiplier to every draw call by using setAlpha(int) or concatenateAlpha(int) after checking isAlphaSupported(). Both methods accept values from 0 (fully transparent) to 255 (fully opaque) and remain active until you change them again. concatenateAlpha() is especially handy when you need to temporarily fade a component because it returns the previous alpha so you can restore it later.

Anti-aliasing can likewise be toggled at runtime. Call isAntiAliasingSupported() and isAntiAliasedTextSupported() to discover which hints the current port exposes, then use setAntiAliased(boolean) and setAntiAliasedText(boolean) to opt into smoother edges for shapes and glyphs respectively. These switches make it easy to balance rendering quality versus speed depending on the type of content you draw.

16.10.4. Event coordinates

The coordinate system and event handling are tied. You can listen for touch events on a component by overriding the pointerPressed(x,y) method. The coordinates received in this method will be absolute screen coordinates, so you may need to do some conversions on these coordinates before using them in your drawXXX() methods.

For example: a pointerPressed() callback method can look like this:

public void pointerPressed(int x, int y) {
    addPoint(x-getParent().getAbsoluteX(), y-getParent().getAbsoluteY());
}

In this case you translated these points so that they would be relative to the origin of the parent component. This is because the drawXXX() methods for this component take coordinates relative to the parent component.

16.11. Images

Codename One has a few image types: loaded, RGB (built-in), RGB (Codename One), Mutable, EncodedImage, SVG, MultiImage, FontImage & Timeline. URLImage, FileEncodedImage, FileEncodedImageAsync, and StorageEncodedImage/Async also exist, and are covered in the IO section.

All image types are seamless to use and will work with drawImage and various image related image APIs for the most part with caveats on performance etc.

For animation images the code must invoke the animate() method on the image (this is done automatically by Codename One when placing the image as a background or as an icon!
You need to do it if you invoke drawImage in code rather than use a built-in component).

Performance and memory wise you should read the section below and be aware of the image types you use. The Codename One designer tries to conserve memory and be "clever" by using EncodedImage. While these are great for low memory you need to understand the complexities of image locking and be aware that you might pay a penalty if you don’t.

Here are the pros/cons and logic behind every image type. This covers the logic of how it’s created:

16.11.1. Loaded Image

This is the basic image you get when loading an image from the jar or network using Image.createImage(String), Image.createImage(InputStream) & Image.createImage(byte array, int, int),…​

Some other APIs might return this image type but those APIs do so explicitly!

In some platforms calling getGraphics() on an image like this will throw an exception as it’s immutable). This is true for most other images as well.

This restriction might not apply for all platforms.

The image is stored in RAM based on device logic and should be reasonably efficient in drawing speed. For example, it takes up a lot of RAM.

To calculate the amount of RAM taken by a loaded image you use the following formula:

Image Width * Image Height * 4 = Size In RAM in Bytes

For example: a 50×100 image will take up 20,000 bytes of RAM.

The logic behind this is simple, every pixel contains 3 color channels and an alpha component hence 3 bytes for color and one for alpha.

This isn’t the case for all images but it’s common and you prefer calculating for the worst case scenario. Even with JPEGs that don’t include an alpha channel some OSes might require that more byte.

16.11.2. The RGB image’s

There are two types of RGB constructed images that are different from one another but since they’re both technically "RGB image’s" you’re bundling them under the same subsection.

Internal

This is a close cousin of the loaded image. This image is created using the method Image.createImage(int array, int, int) and receives the AARRGGBB data to form the image. It’s more efficient than the Codename One RGB image but can’t be modified, at least not on the pixel level.

The goal of this image type is to provide an easy way to render RGB data that isn’t modified efficiently at platform native speeds. It’s technically a standard "Loaded Image" internally.

RGBImage class

RGBImage is effectively an AARRGGBB array that can be drawn by Codename One.

On most platforms this is inefficient but for some pixel level manipulations there is no other way.

An RGBImage is constructed with an int array (int[]) that includes width*height elements. You can then change the colors and alpha channel directly within the array and draw the image to any source using standard image drawing APIs.

This is inefficient in rendering speed and memory overhead. Only use this technique if there is absolutely no other way!

16.11.3. EncodedImage

EncodedImage is the workhorse of Codename One. Images returned from resource files are EncodedImage and many APIs expect it.

The EncodedImage is effectively a loaded image that’s "hidden" and extracted as needed to remove the memory overhead associated with loaded image. When creating an EncodedImage the PNG (or JPEG etc.) is loaded to an array in RAM. Such images are small (relatively) so they can be kept in memory without much overhead.

When image information is needed (pixels) the image is decoded into RAM and kept in a weak/sort reference. This allows the image to be cached for performance and allows the garbage collector to reclaim it when the memory becomes scarce.

Since the fully decoded image can be pretty big (width X height X 4) the ability to store the encoded image can be pretty stark. For example: taking your example above a 50×100 image will take up 20,000 bytes of RAM for a loaded image but an EncodedImage can reduce that to 1kb-2kb of RAM.

An EncodedImage might be more expensive than a loaded image as it will take up both the encoded size and the loaded size. The cost might be slightly bigger sometimes. It’s main value is its ability to shrink.

When drawing an EncodedImage it checks the weak reference cache and if the image is cached then it’s shown otherwise the image is loaded the encoded image cache it then drawn.

EncodedImage isn’t final and can be derived to produce complex image fetching strategies for example: the URLImage class that can dynamically download its content from the web.

EncodedImage can be instantiated through the create methods in the EncodedImage class. Pretty much any image can be converted into an EncodedImage through the createFromImage(Image, boolean) method.

EncodedImage Locking

Loading the image is more expensive so you want the images that are on the current form to remain in cache (otherwise GC will thrash a lot). That’s where lock() kicks in, when lock() is active you keep a hard reference to the actual native image so it won’t get GC’d. This significantly improves performance!

Internally this is invoked automatically for background images, icons etc. which results in a huge performance boost. This makes sense since these images are showing and they will be in RAM anyway. But, if you use a complex renderer or custom drawing UI you should lock() your images where possible!

To verify that locking might be a problem you can launch the performance monitor tool (accessible from the simulator menu), if you get log messages that show that an unlocked image was drawn you might have a problem.

16.11.4. MultiImage

Multi images don’t physically exist as a concept within the Codename One API so there is no way to actually create them and they’re in no way distinguishable from EncodedImage.

The built-in support for multi images is in the resource file loading logic where a MultiImage is decoded and the version that matches the current DPI is physically loaded. From that point on user code can treat it like any other EncodedImage.

The 9-image borders use multi images by default to keep their appearance more refined on the different DPI’s.

16.11.5. FontImage & Material design icons

FontImage allows using an icon font as if it was an image. You can specify the character, color and size and then treat the FontImage as if its a regular image. The huge benefits are that the font image can adapt to platform conventions in color and scale to adapt to DPI.

You can generate icon fonts using free tools on the internet such as this. Icon fonts are a simple and powerful technique to create a small, modern applications.

Icon fonts can be created in 2 basic ways the first is explicitly by defining all the elements within the font:

Form hi = new Form("Icon Font");
Font materialFont = FontImage.getMaterialDesignFont();
int w = Display.getInstance().getDisplayWidth();
FontImage fntImage = FontImage.createFixed("\uE161", materialFont, 0xff0000, w, w);
hi.add(fntImage);
hi.show();
Icon font from material design icons created with the fixed size of display width
Figure 221. Icon font from material design icons created with the fixed size of display width
The samples use the built-in material design icon font. This is for convenience so the sample will work out of the box, for everyone. For example you should be able to do this with any arbitrary icon font off the internet as long as its a valid TTF file.

A more common and arguably "correct" way to construct such an icon would be through the Style object. The Style object can provide the color, size and background information needed by FontImage.

There are two versions of this method: the first one expects the Style object to have the correct icon font set to its font attribute. The second accepts a Font object as an argument. The latter is useful for a case where you want to reuse the same Style object that you defined for a general UI element for example: you can set an icon for a Button like this and it will take up the style of the Button:

Form hi = new Form("Icon Font");
Font materialFont = FontImage.getMaterialDesignFont();
int size = Display.getInstance().convertToPixels(6, true);
materialFont = materialFont.derive(size, Font.STYLE_PLAIN);
Button myButton = new Button("Save");
myButton.setIcon(FontImage.create("\uE161", myButton.getUnselectedStyle(), materialFont));
hi.add(myButton);
hi.show();
An image created from the Style object
Figure 222. An image created from the Style object
Notice that for this specific version of the method the size of the font is used to determine the icon size. In the other methods for FontImage creation the size of the font is ignored!
Material design icons

There are many icon fonts on the web, but the field is rather volatile and constantly changing. For example, you wanted to have built-in icons that would allow you to create better looking demos and built-in components.

That’s why you picked the material design icon font for inclusion in the Codename One distribution. It features a stable core set of icons, that aren’t IP encumbered.

You can use the built-in font directly as demonstrated above but there are far better ways to create a material design icon. To find the icon you want you can check out the material design icon gallery. For example: you used the save icon in the samples above.

To recreate the save icon from above you can do something like:

Form hi = new Form("Icon Font");
Button myButton = new Button("Save");
myButton.setIcon(FontImage.createMaterial(FontImage.MATERIAL_SAVE, myButton.getUnselectedStyle()));
hi.add(myButton);
Material save icon
Figure 223. Material save icon
Notice that the icon is smaller now as it’s calculated based on the font size of the Button UIID.

You can even write the code in a more terse style using:

Form hi = new Form("Icon Font");
Button myButton = new Button("Save");
FontImage.setMaterialIcon(myButton, FontImage.MATERIAL_SAVE);
hi.add(myButton);

This will produce the same result for slightly shorter syntax.

FontImage can conflict with some complex APIs that expect a "real" image underneath. Some odd issues can often be resolved by using the toImage() or toEncodedImage() methods to convert the scaled FontImage to a loaded image.

16.11.6. Timeline

Timelines allow rudimentary animation and enable GIF importing using the Codename One Designer. Effectively a timeline is a set of images that can be moved rotated, scaled & blended to provide interesting animation effects. It can be created manually using the Timeline class.

16.11.7. Image masking

Image masking allows you to manipulate images by changing the opacity of an image according to a mask image. The mask image can be hardcoded or generated dynamically, it’s then converted to a Mask object that can be applied to any image. Notice that the masking process is computationally intensive, it should be done once and cached/saved.

The code below can convert an image to a rounded image:

Toolbar.setGlobalToolbar(true);
Form hi = new Form("Rounder", new BorderLayout());
Label picture = new Label("", "Container");
hi.add(BorderLayout.CENTER, picture);
hi.getUnselectedStyle().setBgColor(0xff0000);
hi.getUnselectedStyle().setBgTransparency(255);
Style s = UIManager.getInstance().getComponentStyle("TitleCommand");
Image camera = FontImage.createMaterial(FontImage.MATERIAL_CAMERA, s);
hi.getToolbar().addCommandToRightBar("", camera, (ev) -> {
    try {
        int width = Display.getInstance().getDisplayWidth();
        Image capturedImage = Image.createImage(Capture.capturePhoto(width, -1));
        Image roundMask = Image.createImage(width, capturedImage.getHeight(), 0xff000000);
        Graphics gr = roundMask.getGraphics();
        gr.setColor(0xffffff);
        gr.fillArc(0, 0, width, width, 0, 360);
        Object mask = roundMask.createMask();
        capturedImage = capturedImage.applyMask(mask);
        picture.setIcon(capturedImage);
        hi.revalidate();
    } catch(IOException err) {
        Log.e(err);
    }
});
Picture after the capture was complete and the resulted image was rounded. The background was set to red so the rounding effect will be more noticeable
Figure 224. Picture after the capture was complete and the resulted image was rounded. The background was set to red so the rounding effect will be more noticeable

Notice that this example is simplistic to be self contained. You often recommend that developers ship "ready made" mask images with their application which can allow complex effects on the images.

16.11.8. URLImage

URLImage is an image created with a URL, it implicitly downloads and adapts the image in the given URL while caching it locally. The typical adapt process scales the image or crops it to fit into the same size which is a hard restriction because of the way URLImage is implemented.

How Does URLImage Work?

The reason for the size restriction lies in the implementation of URLImage. URLImage is physically an animated image and so the UI thread tries to invoke its animate() method to refresh. The URLImage uses that call to check if the image was fetched and if not fetches it asynchronously.

Once the image was fetched the animate() method returns true to refresh the UI. During the loading process the placeholder is shown, the reason for the restriction in size is that image animations can’t "grow" the image. They’re assumed to be fixed so the placeholder must match the dimensions of the resulting image.

The simple use case is pretty trivial:

Image i = URLImage.createToStorage(placeholder, "fileNameInStorage", "https://xxx/myurl.jpg", URLImage.RESIZE_SCALE);

Or you can use the similar URLImage.createToFileSystem method instead of the Storage version.

This image can now be used anywhere a regular image will appear, it will initially show the placeholder image and then seamlessly replace it with the file after it was downloaded and stored. Notice that if you make changes to the image itself (for example: the scaled method) it will generate a new image which won’t be able to fetch the actual image.

Since ImageIO is used to perform the operations of the adapter interface its required that ImageIO will work. it’s working in Java SE, Android, iOS & Windows Phone.

If the file in the URL contains an image that’s too big it will scale it to match the size of the placeholder precisely!
An option also exists to fail if the sizes don’t match. Notice that the image that will be saved is the scaled image, this means you will have little overhead in downloading images that are the wrong size although you will get some artifacts.

The last argument is powerful, its an interface called URLImage.ImageAdapter and you can implement it to adapt the downloaded image in any way you like. For example: you can use an image mask to automatically create a rounded version of the downloaded image.

To do this you can override:

public EncodedImage adaptImage(EncodedImage downloadedImage, EncodedImage placeholderImage);

In the adapter interface and return the processed encoded image. If you do heavy processing (for example: rounded edge images) you would need to convert the processed image back to an encoded image so it can be saved. You would then also want to show that this operation should run asynchronously through the appropriate method in the class.

If you need to download the file instantly and not wait for the image to appear before download initiates you can explicitly invoke the fetch() method which will asynchronously fetch the image from the network. Notice that the downloading will still take time so the placeholder is still required.

Authenticated image URLs — RequestDecorator

The standard createToStorage path doesn’t expose the underlying ConnectionRequest, so attaching an Authorization header (or any other custom header / cookie / timeout) requires the RequestDecorator hook. Two ways to install one:

// Global default for createToStorage images from this point on.
// createToFileSystem downloads do not consult it.
// The most common case is "all our images sit behind the same bearer
// token", which has its own shorthand:
URLImage.setDefaultBearerToken(Preferences.get("auth.token", null));

// Or the explicit form, which can attach any header / cookie / timeout:
URLImage.setDefaultRequestDecorator(req ->
        req.addRequestHeader("Authorization", "Bearer " + token));

For per-image overrides (for example one endpoint needs an extra API-version header on top of the global bearer token), use the createToStorage(placeholder, key, url, adapter, RequestDecorator) overload. Per-instance decorators run after the global default so they can override or augment whatever the default set:

URLImage profilePic = URLImage.createToStorage(
        placeholder,
        "profile-" + userId,
        baseUrl + "/users/" + userId + "/picture",
        URLImage.RESIZE_SCALE_TO_FILL,
        req -> req.addRequestHeader("X-API-Version", "2"));
Decorators reach the storage-backed images only. URLImage.fetch() downloads a file-system-backed image through Util.downloadImageToFileSystem, which takes neither the global default nor a per-image decorator, so an image created with createToFileSystem is fetched without your Authorization header. Use createToStorage when the endpoint needs one.

When a decorator is installed (global or per-call), URLImage skips the default Util.downloadImageToStorage path and builds a ConnectionRequest inline so the decorator can inspect / mutate it before it’s queued. The legacy path remains the default for back-compat when no decorator is set.

Mask adapter

A URLImage can be created with a mask adapter to apply an effect to an image. This allows you to round downloaded images or apply any sort of masking for example: you can adapt the round mask code above as such:

Image roundMask = Image.createImage(placeholder.getWidth(), placeholder.getHeight(), 0xff000000);
Graphics gr = roundMask.getGraphics();
gr.setColor(0xffffff);
gr.fillArc(0, 0, placeholder.getWidth(), placeholder.getHeight(), 0, 360);

URLImage.ImageAdapter ada = URLImage.createMaskAdapter(roundMask);
Image i = URLImage.createToStorage(placeholder, "fileNameInStorage", "https://xxx/myurl.jpg", ada);
The adapter masks the image while resizing it to the placeholder, so a download that already matches the placeholder’s dimensions is stored unmasked. Give the placeholder a size the source images don’t already have when every image has to come out rounded.
URLImage in lists

The biggest problem with image download service is with lists. Codename One attacks this issue at the core by integrating URLImage support directly into GenericListCellRenderer which means it will work with MultiList, List & ContainerList. To use this support define the name of the component (name not UIID) to end with _URLImage and give it an icon to use as the placeholder. This is easy to do in the multilist by changing the name of icon to icon_URLImage then using this in the data:

map.put("icon_URLImage", urlToActualImage);

Make sure you also set a "real" icon to the entry in the GUI builder or in handcoded applications. This is important since the icon will be implicitly extracted and used as the placeholder value. Everything else should be handled automatically. You can use setDefaultAdapter & setAdapter on the generic list cell renderer to install adapters for the images. The default is a scale adapter although you might change that to scale fill in the future:

Style s = UIManager.getInstance().getComponentStyle("Button");
FontImage p = FontImage.createMaterial(FontImage.MATERIAL_PORTRAIT, s);
EncodedImage placeholder = EncodedImage.createFromImage(p.scaled(p.getWidth() * 3, p.getHeight() * 4), false);

Form hi = new Form("MultiList", new BorderLayout());

ArrayList<Map<String, Object>> data = new ArrayList<>();

data.add(createListEntry("A Game of Thrones", "1996", "https://www.georgerrmartin.com/wp-content/uploads/2013/03/GOTMTI2.jpg"));
data.add(createListEntry("A Clash Of Kings", "1998", "https://www.georgerrmartin.com/wp-content/uploads/2012/08/clashofkings.jpg"));
data.add(createListEntry("A Storm Of Swords", "2000", "https://www.georgerrmartin.com/wp-content/uploads/2013/03/stormswordsMTI.jpg"));
data.add(createListEntry("A Feast For Crows", "2005", "https://www.georgerrmartin.com/wp-content/uploads/2012/08/feastforcrows.jpg"));
data.add(createListEntry("A Dance With Dragons", "2011", "https://georgerrmartin.com/gallery/art/dragons05.jpg"));
data.add(createListEntry("The Winds of Winter", "2016 (please, please, please)", "https://www.georgerrmartin.com/wp-content/uploads/2013/03/GOTMTI2.jpg"));
data.add(createListEntry("A Dream of Spring", "Ugh", "https://www.georgerrmartin.com/wp-content/uploads/2013/03/GOTMTI2.jpg"));

DefaultListModel<Map<String, Object>> model = new DefaultListModel<>(data);
MultiList ml = new MultiList(model);
ml.getUnselectedButton().setIconName("icon_URLImage");
ml.getSelectedButton().setIconName("icon_URLImage");
ml.getUnselectedButton().setIcon(placeholder);
ml.getSelectedButton().setIcon(placeholder);
hi.add(BorderLayout.CENTER, ml);
hi.show();

The createListEntry method then looks like this:

private Map<String, Object> createListEntry(String name, String date, String coverURL) {
    Map<String, Object> entry = new HashMap<>();
    entry.put("Line1", name);
    entry.put("Line2", date);
    entry.put("icon_URLImage", coverURL);
    entry.put("icon_URLImageName", name);
    return entry;
}
A URL image fetched dynamically into the list model
Figure 225. A URL image fetched dynamically into the list model

16.12. Charts

Codename One includes a charting toolkit in the com.codename1.charts package that’s designed to integrate with regular UI layouts. Charts are drawn by creating an appropriate dataset and renderer pair, instantiating the matching chart view class, and wrapping it in a ChartComponent it can be added to a form:

XYSeriesRenderer seriesRenderer = new XYSeriesRenderer();
seriesRenderer.setColor(0xff0000);

XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
renderer.addSeriesRenderer(seriesRenderer);

XYSeries series = new XYSeries("Sales");
series.add(1, 42);
series.add(2, 57);

XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
dataset.addSeries(series);

BarChart chart = new BarChart(dataset, renderer, BarChart.Type.DEFAULT);
Form form = new Form(new BorderLayout());
form.add(BorderLayout.CENTER, new ChartComponent(chart));
form.show();

The following classes are available for different kinds of visualisations:

Chart classDataset & rendererNotes

BarChart

XYMultipleSeriesDataset / XYMultipleSeriesRenderer

Draws categorical data as vertical bars. The Type constructor parameter controls default, stacked, or heaped bars.

BubbleChart

XYMultipleSeriesDataset containing XYValueSeries / XYMultipleSeriesRenderer

Represents each data point as a circle whose size is proportional to a third value.

CombinedXYChart

XYMultipleSeriesDataset / XYMultipleSeriesRenderer

Combines several XY chart types in a single plot using XYCombinedChartDef to map series to chart implementations.

CubicLineChart

XYMultipleSeriesDataset / XYMultipleSeriesRenderer

Smooths line series with cubic interpolation. Pass a smoothness factor to the constructor to control the curve.

DialChart

CategorySeries / DialRenderer

Renders one or more gauges on a dial, making it useful for KPI dashboards.

DoughnutChart

MultipleCategorySeries / DefaultRenderer

Shows hierarchical proportions as concentric rings around a common center.

LineChart

XYMultipleSeriesDataset / XYMultipleSeriesRenderer

Connects series of points using straight line segments. Supports optional fill areas and point markers.

PieChart

CategorySeries / DefaultRenderer

Splits a circle into slices that are proportional to each category value.

RadarChart

AreaSeries / DefaultRenderer

Draws a spider/web chart that compares multiple categories across the same set of axes.

RangeBarChart

XYMultipleSeriesDataset / XYMultipleSeriesRenderer

Variation of BarChart that uses paired min/max values to render ranges.

RoundChart

CategorySeries / DefaultRenderer

Abstract base class for circular charts. Use subclasses such as PieChart, DoughnutChart, or DialChart directly.

ScatterChart

XYMultipleSeriesDataset / XYMultipleSeriesRenderer

Plots unconnected X/Y points with configurable marker shapes.

TimeChart

XYMultipleSeriesDataset / XYMultipleSeriesRenderer

Extends LineChart with date-aware labelling on the X axis for time series data.

17. Build-Time Vector & Animation Images

The build-time vector transcoder lets you author UI icons and illustrations as SVG or Lottie / Bodymovin JSON and have them rendered as native Codename One Image instances on every platform (iOS, Android, JavaSE simulator, JavaScript) without shipping a runtime SVG or Lottie parser.

Both formats share the same pipeline: each source file is lowered into the SVG transcoder’s model, the same JavaCodeGenerator emits a com.codename1.ui.GeneratedSVGImage subclass, and the same SVGRegistry makes the result available via Resources.getImage("name.<ext>"). The rest of this guide therefore covers SVG in detail; Lottie gets its own section at the end that only calls out the parts that differ.

17.1. Motivation

Codename One’s older Image.createSVG() API depends on a per-platform native SVG renderer that ships only on the JavaSE simulator; iOS and Android applications fall back to PNG multi-image buckets, giving up the resolution-independence that SVG was designed for. The legacy Flamingo SVG transcoder was a precursor to this work — a build-time tool that emitted Java drawing code from an SVG — but it pre-dated CN1’s affine transform pipeline and was missing a Maven hook, CSS integration, animations, and most of the SVG spec.

This transcoder is its successor and covers each of those gaps. Every SVG you drop into src/main/css/ is parsed by codenameone-svg-transcoder, emitted as a Java class that subclasses com.codename1.ui.GeneratedSVGImage, and rendered through the standard Graphics shape API. The same vector source produces pixel-perfect output at any size on every port.

17.2. Quick start

  1. Drop your SVG next to theme.css in src/main/css/:

    src/main/css/
      theme.css
      home.svg
  2. Reference it from CSS and pin its rendered size in millimeters — the recommended sizing knob, since it carries unchanged across every device DPI:

    HomeIcon {
        background: url(home.svg);
        cn1-svg-width: 6mm;
        cn1-svg-height: 6mm;
        cn1-background-type: cn1-image-scaled-fit;
    }
  3. Build the project:

    mvn package

That’s it. App code doesn’t call into the registry. The transcoder emits com.codename1.generated.svg.SVGRegistry only when SVGs are present, and the per-port build wiring (IPhoneBuilder, AndroidGradleBuilder, the JavaSE port) loads it automatically before init(Object). Resources.getGlobalResources().getImage("home.svg") returns the transcoded image; CSS rules that reference the SVG by URL pick it up via the same registry.

17.3. Why millimeters

cn1-svg-width / cn1-svg-height are the sizing knob you should reach for first.

  • A 6mm icon is 6mm tall on a 1x desktop, 6mm on a high-DPI handset, and 6mm on a 4K tablet. The transcoder routes both values through Display.convertToPixels() at install time, the same way font-size: 3mm behaves elsewhere in CN1 CSS.

  • SVGs in the wild routinely declare odd width/height attributes (a 1024×1024 export of a 24×24 icon, no dimensions at all, etc.). Pinning the rendered size in millimeters sidesteps that guesswork — the SVG’s declared pixel size and the device DPI become irrelevant.

  • It’s the only sizing mode that survives a re-export of the SVG from the asset pipeline. cn1-source-dpi and the implicit medium-density default both depend on the SVG’s declared pixel size, so a tool that rescales the source on export will change the rendered size without any warning.

StarIcon { background: url(star.svg); cn1-svg-width: 4mm; cn1-svg-height: 4mm; }
PrimaryIcon { background: url(home.svg); cn1-svg-width: 6mm; cn1-svg-height: 6mm; }
LogoBanner { background: url(logo.svg); cn1-svg-width: 32mm; cn1-svg-height: 12mm; }

Use cn1-source-dpi: <bucket> (accepted keywords: low, medium, high, very-high, hd, 560, 2hd, 4k) only when an SVG has sensible declared pixel dimensions for a known density target and you want the rendered size to track Display.getDeviceDensity() instead of millimeters. With no hint at all, the SVG’s declared dimensions are treated as design pixels at DENSITY_MEDIUM.

If both keys appear on the same rule, cn1-svg-width / cn1-svg-height wins.

17.4. How the build flow works

The cn1app archetype binds the transcode-svg goal to the generate-sources phase:

<execution>
    <id>transcode-svg</id>
    <phase>generate-sources</phase>
    <goals>
        <goal>transcode-svg</goal>
    </goals>
</execution>

That execution was added to the archetype after the Maven project format itself shipped, so a project generated before it has no transcoder bound. Because nothing fails when the transcoder is missing — the CSS compiler leaves a transparent placeholder in the theme and the app renders nothing where the icon should be — the build repairs the gap rather than waiting to be asked. A module that contains vector assets but binds no transcode-svg execution is transcoded in place during the current build and has the execution written into its POM, with the previous contents kept as pom.xml.bak. A project that already binds the goal, or that has no vector assets, is left untouched.

When Maven runs the mojo:

  1. It scans src/main/css/ and src/main/svg/ for *.svg files. If there are none, the goal is a no-op — no registry class is emitted, no per-port stub injection happens.

  2. For each SVG it emits target/generated-sources/svg/com/codename1/generated/svg/<Name>.java — one class per file — plus a single SVGRegistry class whose installGlobal() registers every transcoded image with the global Resources table.

  3. It scans src/main/css/*/.css for url(*.svg) occurrences and the enclosing rule’s cn1-svg-width / cn1-svg-height / cn1-source-dpi hints. Those values are baked into the registry’s installGlobal() call per image.

  4. It drops a 1×1 transparent PNG placeholder into target/css-resources/ so the standalone CSS compiler can finish even though the file extension on the URL is .svg. The placeholder is overwritten in the theme by the runtime registry call.

The simulator / desktop ports load SVGRegistry reflectively, so a project that adds its first SVG today rebuilds and runs without any code change. The iOS and Android builders detect the generated class in the user’s compile output and weave installGlobal() into the generated Stub right before the first init(Object); a project with no SVGs gets no weaving.

17.5. Calling the registry yourself

If you don’t use theme.css but still want a transcoded SVG, construct the generated class directly. It lands in com.codename1.generated.svg and is named after the file, so src/main/svg/logo.svg becomes com.codename1.generated.svg.Logo. The class exists only after a build has run the transcoder, which is why this listing isn’t one of the compiled examples:

import com.codename1.generated.svg.Logo;
import com.codename1.ui.Display;

Logo logo = new Logo();                      // declared size at DENSITY_MEDIUM
Logo dense = new Logo(Display.DENSITY_HIGH); // read as a higher-density design
Logo sized = new Logo(12f, 12f);             // 12mm square, converted per device

myButton.setIcon(sized);

Constructors come in three flavours, matching the three CSS sizing mechanisms above. The two-float constructor takes millimeters; that’s the one to prefer for the reasons in the previous section.

scaled(int, int) returns a lightweight view that reports the requested dimensions from getWidth() / getHeight() and shares the animation clock with its source.

17.6. SVG feature coverage

The transcoder targets the SVG 1.1 static-shape vocabulary plus the SMIL animation subset:

FeatureStatus

<rect>, <circle>, <ellipse>, <line>, <polyline>, <polygon>

Full

<path> (M/L/H/V/C/S/Q/T/A/Z, relative + smooth-curve reflection)

Full

<g> with transform="translate | scale | rotate | skew | matrix"

Full

fill, stroke, stroke-width, stroke-linecap/linejoin/miterlimit

Full

opacity, fill-opacity, stroke-opacity

Full (animatable)

<linearGradient>

Full (shape-clipped fill on every port)

<radialGradient>

First-stop fallback

<animate> (numeric attributes)

Full

<animateTransform type="translate | scale | rotate">

Full

<set> (instant value snap)

Full

<text> / <tspan> (single-style fills, transforms)

Supported

<clipPath> referenced via clip-path="url(#id)"

Supported (rect/circle/path); nested clip refs ignored

<mask>

Treated as clip — alpha masking falls back to opaque

SVG filter primitives

Not supported

CSS-keyframe animations

Not supported (SMIL only)

SMIL animations read the current time from com.codename1.ui.animations.AnimationTime, so tests can pin the clock with AnimationTime.setTime(t) to capture a deterministic frame. Animated SVGs return true from Image.isAnimation() — as with Timeline, you must register the image with a Form’s animation manager (or set it as a `Component.setIcon with isAnimation() true) for the repaint loop to tick the SMIL clock.

17.7. Lottie animations

Lottie / Bodymovin JSON files are picked up by the same transcode-svg goal. Drop them next to your CSS (or under src/main/lottie/) and the Lottie parser lowers each one into the SVG model — so everything in the previous sections (sizing keys, registry, theme url(…​) lookup, Resources.getImage(…​), the per-port wiring) applies unchanged:

src/main/css/
  theme.css
  spinner.json     <-- Lottie/Bodymovin export
SpinnerStyle {
    background: url(spinner.json);
    cn1-svg-width: 12mm;
    cn1-svg-height: 12mm;
    cn1-background-type: cn1-image-scaled-fit;
}
Image spin = Resources.getGlobalResources().getImage("spinner.json");
// or by stem, like a multi-image:
Image spin2 = Resources.getGlobalResources().getImage("spinner");

.lottie (dotLottie ZIP) files are accepted alongside .json for forward compatibility, but the archive container isn’t yet extracted — export your animation as a plain Bodymovin JSON for now.

17.7.1. Lottie feature coverage

The parser targets the subset of Bodymovin a "spinner" or "pulse" animation typically uses. Anything outside the subset is dropped without warning so a file with mixed coverage still produces a renderable class:

FeatureStatus

Shape layers (ty:4) with grouped rc / el / sh primitives

Full

Solid color layers (ty:1)

Rendered as a filled rect

Shape fills (fl) and strokes (st) — solid colors

Full

Layer transform (anchor, position, scale, rotation, opacity) — static

Full

Animated rotation / position / scale — 2 keyframes

Full (loops indefinitely over the comp duration)

Animated colors / opacity

Collapsed to the first keyframe

Bezier easing on keyframes

Linear interpolation (easing curves ignored)

Multi-keyframe properties (3+)

Collapsed to first vs. last (matches the SVG codegen’s from/to model)

Trim path (tm), repeater (rp), merge (mm), rounded corners (rd)

Ignored

Gradient fills (gf) / gradient strokes (gs)

Ignored

Text layers, image layers, precomp, mattes, expressions

Ignored

For animations that need higher fidelity than the subset above, export the relevant frame as an SVG and use the SVG transcoder path directly — the runtime classes are identical.

17.8. Troubleshooting

Resources.getImage("name.svg") returns null or a 1×1 transparent PNG

The transcoder ran with zero source files: the name in the CSS url(…​) doesn’t match any file under src/main/css/ (or src/main/svg/ / src/main/lottie/ for the dedicated directories). The build names each unmatched reference in a warning. A POM that doesn’t bind the transcode-svg goal at all is repaired automatically, so it’s not the likely cause. The same goal handles .svg, .json, and .lottie — one goal, both formats. For arbitrary Resources bundles loaded outside the global slot, call com.codename1.ui.util.Resources.registerGeneratedImage(name, image) yourself with a fresh new com.codename1.generated.svg.YourAsset(widthMm, heightMm).

Lottie animation looks frozen or starts halfway through

The Lottie parser collapses each animated property’s keyframe array to its first and last value, then loops indefinitely over the composition’s duration. Animations with three or more keyframes on the same property therefore play as a straight first-to-last interpolation. Re-export the comp split into two-keyframe segments or use an SVG/SMIL export for that animation if you need exact keyframe playback.

SVG looks the wrong size

Switch the rule to cn1-svg-width / cn1-svg-height in millimeters. The other sizing modes depend on the SVG’s declared pixel size, which is what’s biting you here.

Spinner / pulse renders but doesn’t animate

Check that the image is mounted into a Component whose animation manager ticks (Labels added to a Form do this automatically). For a pure-Graphics-driven capture (screenshot tests) pin AnimationTime.setTime(…​) and re-render.

18. 3D Graphics and Shaders

The com.codename1.gpu package provides a portable, hardware accelerated 3D graphics API focused on games but useful anywhere you need GPU rendered content. It runs from one code base on the JavaSE simulator (OpenGL via JOGL), Android (OpenGL ES 2), iOS and macOS (Metal), the native Windows port (Direct3D 11), and the JavaScript port (WebGL). The API integrates with the normal Codename One UI: a 3D scene lives inside a regular component that you add to a Form like any other.

Your Renderer callbacks run on the native platform render thread — NOT the Codename One EDT. This is the single most important thing to understand before you write any 3D code.

onInit, onResize, onFrame and onDispose are invoked on the underlying OS/GPU render loop (GL / Metal / Direct3D), not on the event dispatch thread. From inside them you must not touch Codename One UI components, show forms, or call other EDT-only APIs. To push data back to the UI (for example to update a HUD label or react to a game event) hop onto the EDT with CN.callSerially(…​). Conversely, treat the GraphicsDevice and the objects it hands you as owned by the render thread.

3D is a low-level, GPU dependent feature. Always guard usage with CN.isGpuSupported() (or RenderView.isSupported()); on a platform without a backend the RenderView reports unsupported so you can fall back to 2D.

18.1. Concepts

The API is intentionally "hybrid": a low level command layer (buffers, textures, render state, draw calls) for full control, plus high level helpers (meshes, materials, a camera) for common cases. Crucially, you never write shader source. Instead you describe a Material (a lighting model plus color and texture) and the engine generates the matching platform shader behind the scenes: GLSL ES on OpenGL ES and WebGL, GLSL on the desktop simulator, Metal Shading Language on iOS and Mac, and HLSL on the native Windows (Direct3D) port. This "engine-managed shader" approach is what keeps the same application code rendering identically across a range of different GPUs.

The main types are:

  • RenderView - the Component that hosts the GPU surface. You give it a Renderer.

  • Renderer - your callback: onInit, onResize, onFrame, onDispose. These run on the platform render thread, never the EDT.

  • GraphicsDevice - the command surface passed to your renderer. It creates buffers and textures, clears, sets the viewport, the camera and the light, and issues draw calls.

  • Mesh, Material, Camera, Light - the high level scene building blocks.

18.2. A first scene: A spinning cube

The renderer below draws a Phong lit cube. Primitives.cube builds the geometry, a Material describes the surface, and a Camera supplies the view. Notice there is no shader code anywhere.

setContinuous(true) runs an animation loop. For a static scene leave it off and call view.requestRender() whenever something changes; this conserves battery.

A Phong lit cube rendered by RenderView
Figure 226. A Phong lit cube rendered by RenderView in the simulator

18.3. Materials

A Material is a declarative description of a surface. Its Type selects the lighting model:

TypeDescription

UNLIT

Flat color/texture, no lighting. Ideal for UI, emissive surfaces.

LAMBERT

Diffuse (Lambert) lighting from one directional light.

PHONG

Diffuse + specular highlight (uses setShininess).

PBR

Physically based: metallic and roughness (setMetallic, setRoughness) with a GGX highlight, plus setEmissive for surfaces that glow. GltfLoader fills these from a model’s own materials.

SPRITE

Unlit, for screen aligned sprites and billboards.

SKYBOX

Unlit background, rendered behind the scene.

A material also carries a base color (setColor, packed 0xAARRGGBB), an optional Texture (setTexture), and a RenderState controlling depth testing, alpha blending and face culling. Textures come from a Codename One Image or raw ARGB pixels:

Texture tex = device.createTexture(myImage);     // or createTexture(w, h, argb)
// NEAREST keeps texel edges crisp, which is what the checkerboard in the
// figure below needs. LINEAR is the better default for photographic
// textures, where smoothing is wanted rather than avoided.
tex.setFilter(Texture.Filter.NEAREST).setWrap(Texture.Wrap.REPEAT);
Material m = new Material(Material.Type.UNLIT).setTexture(tex);
A checkerboard textured cube
Figure 227. An UNLIT cube with a checkerboard texture (NEAREST filtering)

18.4. Meshes and buffers

Primitives builds common shapes (cube, quad). For custom geometry, allocate a VertexBuffer with a VertexFormat, fill the interleaved float data, and (optionally) an IndexBuffer:

VertexBuffer vb = device.createVertexBuffer(VertexFormat.POSITION_NORMAL_TEXCOORD, 4);
vb.setData(new float[] { /* px,py,pz, nx,ny,nz, u,v  per vertex null */ });
IndexBuffer ib = device.createIndexBuffer(6);
ib.setData(new int[] { 0, 1, 2, 0, 2, 3 });
Mesh mesh = new Mesh(vb, ib, PrimitiveType.TRIANGLES);

Vertex buffers are allocated through the platform SIMD allocator, which on iOS (ParparVM) places the data at a fixed, aligned native address so it can be handed to Metal with no intermediate copy. You don’t need to do anything special to get this; just write into getData() and call setDirty() when you mutate it.

18.5. Loading models

Real scenes use authored geometry. GltfLoader loads a glTF 2.0 model, both the binary .glb container and the JSON .gltf form with embedded buffers. loadModel returns the mesh together with the base-color texture from the model’s own material, so a textured model renders with no extra setup:

InputStream in = Display.getInstance().getResourceAsStream(getClass(), "/boombox.glb");
GltfLoader.GltfModel loaded = GltfLoader.loadModel(device, in);
Material material = new Material(Material.Type.PHONG).setShininess(16f);
if (loaded.getBaseColorTexture() != null) {
    material.setTexture(loaded.getBaseColorTexture());
}
Mesh model = loaded.getMesh();           // draw it like any other mesh

The model below is the Khronos "BoomBox" glTF sample (a CC0 model carrying its own base-color texture), loaded this way and drawn Phong lit:

A textured glTF model loaded with GltfLoader
Figure 228. The Khronos BoomBox glTF sample loaded with GltfLoader

18.6. Animation

Drive a value (a rotation angle, a position) over time and redraw. A continuous RenderView calls onFrame every frame; an on-demand view redraws when you call requestRender(). The grid below captures six fixed rotation stages of a spinning cube, each drawn into its own viewport in a single frame:

Six rotation stages of an animated cube
Figure 229. Six rotation stages of an animated cube captured in one frame

18.7. Camera and math

Camera builds the view and projection matrices from an eye position, a look-at target and lens settings (setPerspective or setOrthographic). All matrix helpers live in Matrix4 (column-major float[16]): translation, scaling, rotation, multiply, lookAt, perspective, ortho. Pass a model matrix as the third argument to draw, or null for the identity.

18.8. Atmosphere, shadows and post processing

Three settings turn a correctly lit scene into one that looks shot outdoors through a lens. All three start off, so a scene that never touches them renders exactly as before.

An Environment (GraphicsDevice.setEnvironment, or getEnvironment() on a GameView) holds the atmosphere every draw is shaded in:

  • Fog — exponential squared in distance, thinned with height, so distant geometry melts into the haze.

  • Hemisphere ambient — a sky color lights upward faces and a ground color downward ones, which gives shape to everything in shadow.

  • Tone mapping and exposure — a filmic (ACES) curve, so bright light rolls off instead of clipping.

  • An open sky — setSky paints SKYBOX surfaces as a gradient from the horizon to the zenith, with soft clouds and the sun where the light comes from. Draw it on a large sphere around the camera; it needs no texture.

Light.setShadows(true) renders the scene from the light into a shadow map before each frame, and lit materials are darkened where it’s blocked. Keep setShadowMap’s extent as small as the view allows and move `setShadowCenter with the camera, since the map’s resolution is spread over the area it covers. A material that shouldn’t cast (grass, particles) says so with setCastShadows(false).

A PostProcess on the view renders the scene offscreen and adds bloom, a color grade, a vignette and film grain on the way to the screen. Touch controls are drawn after it and are never graded.

GameView view = new GameView() {
    protected void update(double deltaSeconds) {
    }
};
view.getEnvironment()
        .setFog(0xffb9c6cf, 0.0075f, 0.05f)
        .setHemisphere(0xffa9bdd2, 0xff4f5a3c)
        .setToneMapping(true)
        .setExposure(1.3f)
        .setSky(0xff4f7fb8, 0xffb9c6cf, 0xfffff0d0, 0.45f);
view.getLight().setShadows(true).setShadowMap(2048, 18f);
view.setPostProcess(new PostProcess()
        .setBloom(0.78f, 0.55f)
        .setGrade(1.12f, 0.86f, 0xff0b1720, 0xfffff2dc)
        .setVignette(0.42f)
        .setGrain(0.035f));

Match the horizon color to the fog color and the far edge of the world disappears into the sky. A device that can’t render shadows or offscreen says so through GpuCapabilities.isShadowsSupported() and isPostProcessSupported(), and the scene is then drawn directly. The JavaSE software rasterizer applies the fog, the ambient, tone mapping and the sky gradient, but not shadows, clouds or the post chain.

18.9. Platform notes

  • JavaSE simulator - OpenGL through JOGL, loaded from an isolated class so a missing or failing GL driver degrades to a built in software rasterizer instead of breaking the simulator. Lets you develop and debug 3D without a device.

  • Android - OpenGL ES 2 via a GLSurfaceView hosted as a native peer.

  • iOS and macOS - Metal. Shaders are generated as Metal Shading Language and compiled at runtime; vertex/index data is uploaded to `MTLBuffer`s, zero-copy where the SIMD allocation permits.

  • Native Windows - Direct3D 11. Shaders are generated as HLSL and compiled with D3DCompile; the offscreen render target is read back and composited into the UI.

  • JavaScript - WebGL on a <canvas> peer; the generated GLSL ES runs unmodified.

Querying capabilities at runtime:

if (CN.isGpuSupported()) {
    GpuCapabilities caps = device.getCapabilities();
    Log.p("GPU " + caps.getRendererName()
            + ", max texture " + caps.getMaxTextureSize()
            + ", shader level 3: " + caps.isShaderLevel3());

    // Size the atlas to what this device can actually hold rather than
    // assuming a figure: the limit is as low as 2048 on older hardware.
    int edge = Math.min(2048, caps.getMaxTextureSize());
    Log.p("atlas edge " + edge);

    if (caps.isIntIndicesSupported()) {
        // 32-bit indices are available, so a mesh may exceed 65535 vertices
    }
}

18.10. Threading

Renderer callbacks run on the platform render thread, not the Codename One EDT. Don’t touch UI components from inside them. To move data the other way (for example to update a HUD label from a game loop), use CN.callSerially(…​).

19. Augmented Reality

The com.codename1.ar package composites virtual 3D content into the live camera image: the session tracks the device’s position in the real world, detects surfaces, recognizes registered images and faces, and keeps virtual objects locked to real-world positions as the user moves. It’s backed by ARKit on iOS and by ARCore (Google Play Services for AR) on Android, behind one portable API.

Referencing any class in the package is enough to wire the build: the class scanner injects the camera permission, the NSCameraUsageDescription plist entry (override the text with the ios.NSCameraUsageDescription build hint), links ARKit and SceneKit on iOS and adds the ARCore dependency plus the com.google.ar.core manifest entry on Android. Apps that never touch the package pay no size, permission or store-visibility cost. By default the Android manifest marks AR optional so the app still installs on devices without ARCore; set the android.ar.required=true build hint to make the app AR-only.

Always guard AR functionality behind AR.isSupported(). Older devices, tvOS, watchOS, desktop builds and browsers report false; feature-specific hardware such as face tracking is gated through AR.getCapabilities().

19.1. Concepts

TypeRole

AR

Static entry point: support and capability checks, permission request, session opening.

ARSession

The running AR experience. One session may be open at a time; it owns the view, the anchors and the detected planes, and delivers all events.

ARView

The component that renders the camera image composited with the anchored content. Add it to a form like any other component.

ARPose

An immutable position + rotation in world space: meters, right-handed, Y up, -Z forward from the initial camera direction. Converts to a com.codename1.gpu.Matrix4 compatible matrix.

ARPlane

A detected real-world surface (floor, table, wall) that grows and refines as the session learns the environment.

ARHitResult

The intersection of a screen-point ray with real-world geometry; the bridge from a tap to a world position.

ARAnchor

A tracked fixed point in the real world. The attachment point for content; also delivered for recognized images (ARImageAnchor) and faces (ARFaceAnchor).

ARNode / ARModel

The content placed at an anchor: a small scene graph of nodes carrying glTF models or com.codename1.gpu.Mesh geometry.

ARLightEstimate

The real-world lighting estimate, polled per frame to shade content so it blends in.

19.2. Getting started: Place a model on the floor

The canonical AR loop is: open a session, show its view, wait for a plane, hit test a tap, anchor content at the hit.

if (!AR.isSupported()) {
    ToastBar.showInfoMessage("AR is not supported on this device");
    return;
}
final ARSession session = AR.open(new ARSessionOptions());
final ARView view = session.createView();

Form f = new Form("AR", new BorderLayout());
f.add(BorderLayout.CENTER, view);
f.show();

// modelBytes is a .glb asset, e.g. loaded from getResourceAsStream
view.addPointerReleasedListener(e -> {
    float xn = (e.getX() - view.getAbsoluteX()) / (float) view.getWidth();
    float yn = (e.getY() - view.getAbsoluteY()) / (float) view.getHeight();
    session.hitTest(xn, yn).ready(hits -> {
        if (hits.length > 0) {
            ARAnchor anchor = hits[0].createAnchor();
            anchor.setNode(new ARNode(ARModel.fromGltf(modelBytes)));
        }
    });
});

ARSessionOptions configures the session before it opens: the tracking mode (WORLD or FACE), which plane orientations to detect, whether to estimate lighting, and the reference images to recognize. The defaults open a world tracking session with horizontal plane detection and light estimation, which suits the place-content-on-a-surface use case above.

19.3. Plane detection

Planes are delivered through ARPlaneListener as immutable snapshots: an ADDED event when a new surface is found, UPDATED snapshots (sharing the same getId()) as the surface grows, and REMOVED when a plane merges into another. ARSession.getPlanes() always reflects the latest snapshots.

session.addPlaneListener(ev -> {
    ARPlane p = ev.getPlane();
    System.out.println(ev.getKind() + " " + p.getType()
            + " " + p.getExtentX() + "x" + p.getExtentZ() + "m");
});

The plane’s local frame has X/Z spanning the surface and Y along the normal; getCenterPose() positions that frame in the world. ARPlane.Type distinguishes upward-facing horizontal surfaces (floors, tables), downward-facing ones (ceilings) and vertical surfaces (walls) - request vertical detection with ARSessionOptions.planeDetection(ARPlaneDetection.HORIZONTAL_AND_VERTICAL).

19.4. Hit testing and anchors

hitTest(xNorm, yNorm) shoots a ray from a normalized view coordinate into the world and resolves - on the EDT - with the intersections ordered nearest first. Prefer ARHitResult.createAnchor() over session.createAnchor(pose) when placing on detected geometry: the platform can then anchor to the exact native raycast, which tracks better as the environment refines.

Anchors survive tracking refinements: the session updates getPose() over time and reports the change through ARAnchorListener. Remove an anchor (and its content) with detach(). Content attaches through setNode(ARNode):

ARNode root = new ARNode(ARModel.fromMesh(
        Primitives.sphere(0.15f, 24, 32, false), 0xffdd4433));
root.setLocalPosition(0, 0.15f, 0); // rest on the surface, not in it
anchor.setNode(root);

Node transforms are relative to the anchor, in meters. Nodes may nest (addChild), carry glTF assets (ARModel.fromGltf) or portable meshes (ARModel.fromMesh), and any mutation after attachment - position, rotation, scale, visibility, children - re-syncs the platform renderer automatically.

19.5. Light estimation

session.getLightEstimate() returns the latest estimate of the real-world lighting. It refreshes every frame without firing events, so poll it when rendering-relevant decisions are made. The ambient intensity is normalized so 1.0 means neutral indoor lighting; the color correction is a per-channel scale where {1, 1, 1} is neutral. Platform renderers already apply the estimate to anchored content; the API exposes it for custom logic such as prompting the user when the room is too dark.

19.6. Image tracking

Register printed images - posters, game boards, product labels - and the session anchors content to them when the camera sees them:

ARSessionOptions opts = new ARSessionOptions().referenceImages(new ARReferenceImage[]{
    new ARReferenceImage("poster", posterPngBytes, 0.42f) // physical width in meters
});
ARSession session = AR.open(opts);
session.addAnchorListener(ev -> {
    if (ev.getKind() == ARAnchorEvent.Kind.ADDED
            && ev.getAnchor() instanceof ARImageAnchor) {
        ARImageAnchor img = (ARImageAnchor) ev.getAnchor();
        System.out.println("Recognized " + img.getReferenceImageName());
        img.setNode(new ARNode(ARModel.fromGltf(overlayModel)));
    }
});

The physical width matters: the platform uses it to estimate the image’s distance, so measure the real print. The anchor pose is centered on the physical image with local X/Z spanning its surface.

19.7. Face tracking

Face tracking is a distinct session configuration using the front camera; open it with ARSessionOptions.trackingMode(ARTrackingMode.FACE) after checking AR.getCapabilities().isFaceTrackingSupported(). Detected faces arrive as `ARFaceAnchor`s through the anchor listener, carrying the head pose plus optional finer geometry:

  • getRegionPose(ARFaceRegion) returns the pose of a named region. Availability differs per platform (ARCore supplies the nose tip and forehead regions, ARKit supplies the eyes), which is why code must always handle a null region.

  • getMeshVertices() / getMeshTriangles() expose the tracked face mesh where the platform provides one, or null where it doesn’t.

19.8. Events and threading

Every listener fires on the EDT and every getter reflects the state as of the events delivered so far, so AR code follows normal Codename One threading rules with no extra synchronization. High-frequency refinements (anchor and plane updates, camera pose, light estimate) are coalesced: a slow EDT sees the latest values rather than a backlog. This contrasts with the com.codename1.gpu.Renderer callbacks used by the VR API, which run on the render thread.

19.9. The simulator and debugging

The Codename One simulator ships a simulated AR backend modeled on the Android emulator’s virtual scene, so the full AR loop is debuggable with breakpoints without a device. When a session opens, the simulator "detects" the floor (and, when requested, a wall) of a virtual room after a short startup delay, mimicking real AR initialization. The AR view renders the room and every anchored model; drive the virtual device camera with the mouse (drag to look around) and keyboard (W/A/S/D or the arrow keys to move, Q/E for up and down).

A model placed on the virtual room floor in the simulator

The Simulate menu’s AR Simulation window drives the paths that are hard to reproduce on demand with real hardware: force degraded tracking states and failure reasons, change the light estimate, re-run plane detection, trigger recognition of a registered reference image, and toggle a simulated face anchor for FACE sessions.

On devices, use the standard native tools: the generated Xcode project debugs the ARKit session and SceneKit scene directly (including Instruments), and Android Studio attaches to the Gradle project for ARCore logging. Note that Apple’s iOS Simulator has no ARKit support - real ARKit behavior needs a physical device - while the Android emulator can run ARCore against its own virtual scene.

19.10. Platform notes

  • Dependencies: injected automatically as described above. The ARCore dependency adds about 2 MB to Android binaries; iOS links the system ARKit/SceneKit frameworks at no size cost.

  • Capabilities: face tracking requires a capable front camera (a TrueDepth camera on iOS). Check ARCapabilities per feature rather than assuming.

  • Face regions: ARCore supplies NOSE_TIP, FOREHEAD_LEFT and FOREHEAD_RIGHT; ARKit supplies LEFT_EYE and RIGHT_EYE. Code that uses regions must handle a null region.

  • ARCore installation: on Android, Play Services for AR may need installing or updating; when AR.open triggers that flow it throws with a message saying to retry once installation completes.

  • tvOS / watchOS: AR compiles out entirely; AR.isSupported() reports false.

20. Virtual Reality and 360 Media

The com.codename1.vr package renders application scenes in stereoscopic VR and displays 360-degree panoramas, built entirely on the portable com.codename1.gpu pipeline and the com.codename1.sensors motion sensors. There is no platform SDK dependency: everything here runs wherever Display.getInstance().isGpuSupported() is true, which includes the simulator, and adds nothing to the build for apps that don’t use it.

Like com.codename1.gpu.Renderer, the VRRenderer and TextureSource callbacks run on the platform render thread that owns the GPU context - never touch Codename One UI components from them. Everything else in the package is ordinary EDT-friendly component API.

20.1. Concepts

TypeRole

VRView

The stereo component: clears the frame, splits the viewport per eye, positions the cameras from head tracking and invokes your renderer once per eye.

VRRenderer

Your scene callback: onInit, onEyeFrame(device, eye, camera) and onDispose.

VREye

Which eye a frame is for: LEFT, RIGHT, or CENTER in mono mode.

VRSettings

Interpupillary distance (default 0.064m), per-eye field of view, clip planes and the stereo default.

HeadTracker

Wires the gyroscope, accelerometer and magnetometer into an orientation with thread-safe snapshots for the render thread.

OrientationFilter

The deterministic sensor-fusion math behind the tracker, usable on its own.

VRCameraRig

Per-eye camera math over the existing com.codename1.gpu.Camera, usable without VRView for custom pipelines.

Media360View

A 360-degree panorama viewer: an equirectangular image on the inside of a sphere with drag or gyroscope look-around.

TextureSource

Extension point feeding dynamic textures (procedural animation, future video) to Media360View.

20.2. Getting started: A stereo scene

A VRRenderer draws the same scene for every eye; the camera differences produce the depth effect. The view configures the viewport and camera before each onEyeFrame, so the renderer only issues draw calls:

VRView vr = new VRView(new VRRenderer() {
    Mesh cube;
    Material material;

    public void onInit(GraphicsDevice device) {
        cube = Primitives.cube(device, 0.5f);
        material = new Material(Material.Type.PHONG).setColor(0xff3366ff);
    }

    public void onEyeFrame(GraphicsDevice device, VREye eye, Camera camera) {
        device.draw(cube, material, Matrix4.translation(0, 0, -2));
    }

    public void onDispose(GraphicsDevice device) { }
});
vr.setContinuous(true); // head tracked scenes want continuous rendering

Form f = new Form("VR", new BorderLayout());
f.add(BorderLayout.CENTER, vr);
f.show();

setStereo(false) switches to a single centered viewpoint (VREye.CENTER) at runtime, useful for a non-headset preview of the same scene. setPosition(x, y, z) moves the viewer through the world; setClearColor(argb) sets the background.

A stereo scene on an Android phone; the offset between the eye views is the depth cue

20.3. Head tracking

VRView starts its HeadTracker when the component appears and stops it when it leaves the screen; the sensors draw power only between the two. The tracker fuses the gyroscope with the accelerometer (tilt reference) and, when present, the magnetometer (yaw reference) through a complementary filter - tune the blend via getHeadTracker().getFilter().setGyroWeight(float).

Call recenter() to make the current view direction the new "straight ahead," keeping pitch and roll - the standard VR recentering gesture. On devices without a gyroscope the tracker falls back to accelerometer tilt: pitch and roll stay accurate but yaw has no stable reference. HeadTracker.isSupported() reports whether any usable motion hardware exists; without it the orientation simply stays put and the scene still renders.

20.4. The 360 photo viewer

Media360View displays equirectangular panoramas - the format produced by 360 cameras and phone panorama modes, where longitude maps to X and latitude to Y:

Media360View pano = new Media360View();
pano.setImage(EncodedImage.create("/panorama.jpg"));
f.add(BorderLayout.CENTER, pano);
An equirectangular panorama in side-by-side stereo

Dragging looks around with the grab-the-world gesture; setHeadTrackingEnabled(true) adds gyroscope look composed with the drag, and setStereo(true) renders side by side for cardboard-style viewers. Photo spheres are captured from a single point, so stereo intentionally uses zero eye separation - there is no parallax information in the image to reproduce. setYaw/setPitch position the view programmatically and reset() returns to straight ahead.

20.5. 360 video and dynamic content

There is no platform path from media frames to GPU textures yet, so 360 video isn’t supported directly. TextureSource is the extension point for dynamic content: the view calls createTexture once on the render thread and updateTexture before every frame, so procedurally animated panoramas work today and a future media-to-texture bridge can plug in without API changes.

pano.setTextureSource(new TextureSource() {
    public Texture createTexture(GraphicsDevice device) {
        return device.createTexture(1024, 512, initialPixels);
    }
    public boolean updateTexture(GraphicsDevice device, Texture texture) {
        // mutate pixels and re-upload as needed; return true when changed
        return false;
    }
    public void dispose(GraphicsDevice device) { }
});

20.6. The simulator

Both VRView and Media360View run in the simulator through the desktop 3D backend, and the Simulate menu’s Motion / Gesture Simulation window feeds synthetic sensor data to the HeadTracker, so head-tracked scenes are drivable from the desktop. Drag-look in Media360View works with the mouse as it does with a finger.

20.7. Limitations and notes

  • Lens distortion: the stereo output is undistorted side-by-side rendering. Barrel distortion for lens-based viewers requires an offscreen render pass the portable GPU API doesn’t expose yet, so there is no distortion setting to configure.

  • Battery: continuous rendering plus live sensors is the most power-hungry mode a phone UI can run; stop or pause the view whenever it isn’t visible (the component does this automatically on hide).

  • Coordinates: the world frame matches the AR and 3D graphics APIs (meters, right-handed, Y up, -Z forward), letting content and math move between the three without conversion.

21. Game Development

Codename One is a general purpose UI toolkit, but it ships with a package built specifically for games: com.codename1.gaming. It gives you the things games need — a tight update loop, sprite primitives, pollable input, low latency sound effects and rigid body physics — and renders on the GPU through the com.codename1.gpu package. Everything written here runs unchanged on every Codename One target, including iOS.

This chapter covers the real time game surface. For the "casual game" approach — building game elements out of regular Component`s and letting the layout system render them — the techniques in the Chapter 12, Animations chapter are often a better fit. Reach for `com.codename1.gaming when you want a frame driven loop and GPU sprite rendering.

21.1. Sample games

The samples project ships several runnable starting points. Each is a single file built entirely from art generated at runtime — no asset files — so you can copy one and start changing it immediately. The rest of this chapter draws on them to show how the pieces fit together.

Casual arena demo
Side scroller demo
3D world demo

CasualGameSample
A top-down arena: fly a thruster ship with the on-screen joystick, scoop up spinning gems and dodge drifting asteroids. Many sprites in a Scene, per-sprite animation, collision, particle bursts and a twinkling starfield.

ScrollerGameSample
A side-scroller: an AnimatedSprite runner with a walk cycle that flips to face its direction, a sun/cloud/hill parallax backdrop, hand-rolled jump physics, and a joystick + JUMP button.

Gaming3DDemoSample
A 3D world: a spinning multi-cube monument on a textured grid ground, ringed by colored Model buildings and billboarded coins, lit and orbited by a perspective camera.

Two more samples show how far the same 2D primitives stretch — one flat, one faked into 3D:

  • CardGameSample — a 2D Memory (Concentration) match. Each card is a Sprite in a grid; flipping one animates its horizontal scale through zero and swaps the image at the thin point, and taps are hit-tested against sprite bounds through GameInput. A compact illustration of flat 2D play with no camera tricks at all. Dissected in Section 21.6, “Case study: The card game (flat 2D)”.

  • BoardGameSample — faux-3D checkers on an isometric board. Every tile and piece is still a flat Sprite, but laying them out in an isometric (2:1 diamond) projection and raising the pieces off their tiles with a drop shadow gives a convincing 3D look without any GPU 3D, perspective camera or models. The screen pixel-to-board-cell mapping (and its inverse, for picking) is the same math behind any isometric strategy or tycoon game; it also implements the full move/jump/chain /crown rules and a small AI so you can play it solo. Dissected in Section 21.7, “Case study: Faux-3D checkers (isometric projection)”.

The action samples are driven by the joystick and buttons in Section 21.4, “On-screen touch controls”, so they’re equally playable on a touch device and in the desktop simulator (where the arrow keys and mouse stand in for the stick); the card and board games are pure tap.

21.2. The game loop: GameView

GameView is the heart of the package. It’s a GPU surface (a RenderView) that runs the frame loop for you — a display link on device, the dependency-free software rasterizer in the simulator — so there’s no EDT busy loop and no frame rate to manage. You build your world by adding Sprite`s to its `Scene, advance the game in update(double), and the view draws the scene every frame.

The dt passed to update is the wall clock time since the previous frame. Multiplying movement by it keeps the game running at the same speed regardless of the actual frame rate ("delta timing"). Notice there’s no draw method — positioning sprites is all you do; the GPU renderer handles the rest (see Section 21.5, “Sprites”).

21.2.1. Lifecycle

start() begins continuous rendering, stop() halts it, and pause()/resume() suspend update while the view keeps drawing the last frame. start() is safe to call before or after the form is shown.

setClearColor(int argb) sets the background the view is cleared to each frame.

21.2.2. Fixed timestep and interpolation

Variable time steps are simple but make physics nondeterministic. Call setFixedTimestep(seconds) to have update invoked at a fixed interval instead; the loop accumulates real time and may call update several times in one frame to catch up (capped to avoid a "spiral of death" after a long pause). The leftover fraction is available from getInterpolationAlpha() (0 to 1) so you can interpolate rendered positions between physics states:

game.setFixedTimestep(1.0 / 120.0);   // step physics at a steady 120Hz

21.2.3. Threading

update(double) runs on the render thread, together with drawing. Keep it non-blocking — offload asset loading, networking or other long work to a background thread and hand the result back with CN.callSerially.

21.3. Input: GameInput

Games usually want to ask "is the left key down right now?" rather than handle a stream of events. GameInput, obtained from GameView.getInput(), captures the view’s key and pointer events and exposes them as state. There are two flavors:

  • Level state, true for as long as the input is held: isKeyDown(int), isGameKeyDown(int gameAction), isPointerDown().

  • Edge state, true only during the single frame the transition happened: wasKeyPressed(int), wasKeyReleased(int), wasPointerPressed(), wasPointerReleased(). Edges are cleared at the end of each frame, after update has run.

isGameKeyDown works with the device independent game actions Display.GAME_UP, GAME_DOWN, GAME_LEFT, GAME_RIGHT and GAME_FIRE, so directional input works the same across keyboards and devices. Pointer coordinates are reported relative to the `GameView’s top left.

21.4. On-screen touch controls

A keyboard is fine in the simulator, but a phone has no arrow keys. Every GameView comes with a TouchControls (from getControls()) that draws an on-screen virtual joystick and buttons and feeds them into the same GameInput — so the input code you already wrote for the keyboard works untouched on touch devices.

  • The joystick reports analog direction through GameInput#getAxisX() / getAxisY() (each -1 to 1), and at the same time presses the digital game actions GAME_LEFT / GAME_RIGHT / GAME_UP / GAME_DOWN once it crosses its dead zone, so isGameKeyDown(…​) keeps working.

  • A button holds down a key code while it’s pressed, so isKeyDown(int) and wasKeyPressed(int) report it exactly like a hardware key. Map it to a game action with Display.getInstance().getKeyCode(Display.GAME_FIRE), or to any key code of your own.

Anchor controls to a corner of the view’s safe area with the alignment constants (TouchControls.LEFT / CENTER / RIGHT and TOP / CENTER / BOTTOM) and a margin. The framework keeps them clear of notches and home indicators and repositions them automatically when the view resizes or the device rotates — you never recompute coordinates:

TouchControls c = getControls();

// analog stick, bottom-left, 80px radius, 24px in from the safe-area edges
c.addJoystick(80, TouchControls.LEFT, TouchControls.BOTTOM, 24);

// a JUMP button, bottom-right, mapped to GAME_FIRE
int jumpKey = Display.getInstance().getKeyCode(Display.GAME_FIRE);
c.addButton(jumpKey, 55, TouchControls.RIGHT, TouchControls.BOTTOM, 30)
        .setLabel("Jump").setColor(0xc0ff7043);

// then read input exactly as you would for a keyboard:
float ax = getInput().getAxisX();                 // analog steering
boolean jump = getInput().wasKeyPressed(jumpKey);  // or GAME_UP, etc.

The joystick (bottom-left) and JUMP button (bottom-right) are visible in the sample screenshots above. There are also absolutely positioned overloads (addJoystick(centerX, centerY, radius)), and setVisible(false) hides the overlay — handy when a real keyboard is attached. Multi-touch is supported, so the player can steer and press a button at once.

21.5. Sprites

A Sprite is a lightweight data holder: an image plus position, rotation, scale, a normalized anchor and an ARGB tint. It describes what and where; a SpriteRenderer turns it into a GPU textured quad each frame using the com.codename1.gpu package — an orthographic camera mapping one world unit to one pixel, a com.codename1.gpu.Material.Type#SPRITE material and alpha blending. Because a sprite never touches the GPU directly you create one with just an com.codename1.ui.Image; the renderer uploads and caches the matching texture on demand.

getX()/getY() is the location of the anchor point (the image center by default), and rotation and scale pivot around that anchor.

getBounds() returns the axis aligned bounding box and intersects(Sprite) does a quick box overlap test, handy for broad phase collision before you involve physics.

21.5.1. Scenes

A Scene is a z-ordered collection of sprites with an optional camera offset, drawn for you by the renderer. Sprites are drawn from lowest to highest zOrder, so higher z-order sprites appear on top; the camera offset (setCamera(int, int)) scrolls the whole scene. GameView.getScene() is the scene the view draws.

You don’t need a GameView to render sprites: a SpriteRenderer is itself a com.codename1.gpu.Renderer, so you can host one in a plain RenderView.

21.5.2. Sprite sheets and animation

SpriteSheet slices one atlas image into a grid of equally sized frames, cutting and caching each frame on first use (cutting a sub image copies pixels, so caching matters).

AnimatedSprite is a Sprite that cycles through a sequence of frames over time; the scene advances it every frame, so adding it to the scene is all you need.

A six-frame run cycle laid out as a sprite sheet

A sprite sheet is just a strip (or grid) of frames like the run cycle above: the arms and legs swing a little further each frame, and playing them in sequence reads as motion. AnimatedSprite also accepts a plain com.codename1.ui.Image[] when you build the frames yourself, which is what `ScrollerGameSample’s runner does:

AnimatedSprite hero = new AnimatedSprite(runFrames, 0.09);   // Image[6], 90ms each
hero.play();
getScene().add(hero);

// in update(double dt):
if (moving) {
    hero.play();
    hero.setScale(facing, 1);     // facing is -1 (left) or 1 (right)
} else {
    hero.pause();
    hero.setCurrentFrame(0);      // standing pose
}

Setting a negative scale flips the sprite horizontally, so a single set of frames faces both ways — no mirrored art needed (sprites are drawn double-sided for exactly this reason). play(), pause(), stop(), setLooping(boolean) and setCurrentFrame(int) control playback.

21.6. Case study: The card game (flat 2D)

The Memory card game mid-flip: two matched pairs and one card face up

CardGameSample is Memory (Concentration): sixteen face-down cards in a four-by-four grid, tap two and they stay up when they match, flip back when they don’t. It’s the smallest complete example of turn-based 2D play with com.codename1.gaming — no joystick, no physics, no camera — which makes the three techniques it does use easy to see in isolation.

One sprite per card. Each card is a Sprite positioned at its grid slot. There are exactly two images at any moment: the shared card-back image and the card’s own face (all generated at runtime with Image.createImage and Graphics calls, so the sample needs no assets). Changing what a card shows is just sprite.setImage(…​).

A flip you can fake with scale. A real card flip is a 3D rotation, but squeezing the sprite’s horizontal scale through zero and swapping the image at the thin point reads exactly the same to the eye:

// in the card's per-frame animation; flip runs 0 -> 1 over ~0.4s
flip += dt * 5;
if (flip >= 1) {
    // Finish the animation: snap back to full width and stop. Without
    // this, abs(1 - 2 * flip) keeps climbing past 1 and the card grows
    // wider on every later frame instead of settling.
    sprite.setImage(face);
    sprite.setScale(1f, 1f);
    return;
}
float sx = Math.abs(1f - 2f * (float) flip);   // 1 -> 0 -> 1
if (flip >= 0.5 && !showingFace) {
    showingFace = true;
    sprite.setImage(face);     // swap sides while the card is edge-on
}
sprite.setScale(Math.max(0.05f, sx), 1f);

This is the same negative/positive scale trick the scroller uses to flip its runner, driven over time to play as an animation.

Polled taps against sprite bounds. There are no buttons to wire up; update(double) polls the GameInput edge state and hit-tests the tap against each card’s bounding box:

protected void update(double dt) {
    // ... advance flip animations, count down the mismatch timer ...
    if (getInput().wasPointerPressed()) {
        int px = getInput().getPointerX();
        int py = getInput().getPointerY();
        for (int i = 0; i < cards.length; i++) {
            Rectangle b = cards[i].sprite.getBounds();
            if (b.contains(px, py)) {
                flipUp(cards[i]);
                break;
            }
        }
    }
}

The rest of the sample is a small state machine living in plain fields: the first and second face-up cards, a mismatchTimer that counts down in update before flipping a failed pair back, and a moves counter surfaced through the form title. Note the timer: in a game loop you don’t schedule callbacks, you subtract dt from a countdown field each frame and act when it crosses zero.

21.7. Case study: Faux-3D checkers (isometric projection)

Isometric checkers mid-game with a selected piece and a highlighted destination

BoardGameSample plays a full game of checkers — moves, forced captures, chained jumps, crowning, and a small AI opponent — on a board that looks convincingly 3D — yet there is no perspective camera and no Model anywhere: every tile and piece is a flat Sprite. The 3D impression comes entirely from where the flat art is placed, a technique (isometric or "2.5D" projection) that powered decades of strategy and tycoon games and still works just as well on a GPU sprite pipeline.

The projection. Board cell (r, c) maps to screen pixels by laying the grid out as 2:1 diamonds — columns step right-and-down, rows step left-and-down:

private float tileCenterX(int r, int c) {
    return originX + (c - r) * (tileW / 2f);
}

private float tileCenterY(int r, int c) {
    return originY + (c + r) * (tileH / 2f);   // tileH = tileW / 2
}

Picking is the inverse. Because the mapping is linear it inverts with two divisions, turning a tap back into a board cell — no per-tile hit testing required:

private int[] pick(int px, int py) {
    float a = (px - originX) / (tileW / 2f);   // = c - r
    float b = (py - originY) / (tileH / 2f);   // = c + r
    int c = Math.round((a + b) / 2f);
    int r = Math.round((b - a) / 2f);
    if (r < 0 || r >= N || c < 0 || c >= N) {
        return null;                            // tap missed the board
    }
    return new int[]{r, c};
}

Depth from z-order. Cells further down the screen must draw over the cells behind them, and within one cell the stacking is tile, then shadow, then selection/move markers, then the piece. Both rules collapse into a single number — (r + c) strides the cells from back to front, and a small offset layers the sprites within a cell:

// shadow sits flat on the tile, the piece floats above it
addDynamic(shadow, cx, cy + tileH * 0.10f, (r + c) * 4 + 1, 0.5, 0.5);
addDynamic(piece,  cx, cy - tileH * 0.30f, (r + c) * 4 + 3, 0.5, 0.62);

That pair of lines is also the whole "3D height" illusion: the piece is drawn raised off its tile while its shadow stays put, and the eye reads the gap as elevation. The piece art helps — an elliptical top face over a darker side rim, again just fillArc calls on a runtime-generated image.

Rebuild, don’t mutate. After every move the sample throws away all its dynamic sprites (pieces, shadows, markers) and recreates them from the board[][] array in one syncPieces() pass. With a few dozen sprites this costs nothing, and it keeps the scene a pure function of the game state — there is no way for the display to drift out of sync with the rules, which eliminates the whole class of "the board shows X but the game thinks Y" bugs. The game logic itself (destinations, forced captures, chaining, crowning) never touches a sprite; it reads and writes the int[][] board only.

When fake 3D stops being enough — you want the camera to move through the world rather than look at it — the next section covers the real thing.

21.8. 3D and perspective

GameView renders on the GPU through the com.codename1.gpu package, so the same scene can be shown in 3D. Every view has a GameCamera that starts in 2D mode; switching it to perspective turns flat sprites into camera-facing billboards in a 3D world and lets you draw 3D meshes alongside them. That’s the basis for deeper gameplay modes — an over-the-shoulder racer, an isometric or top-down view with real depth, a 2.5D shooter.

The 3D sample: a textured grid ground, stacked cube models, ringed buildings and billboarded coins

Gaming3DDemoSample (above) is built entirely from the primitives this section describes — a textured ground plane, lit cube Model meshes, and billboarded Sprite coins and trees, all orbited by a perspective camera.

21.8.1. Perspective camera and billboard sprites

Call GameCamera#setPerspective(float, float, float) and position the camera with setPosition / setTarget. Once in perspective mode a Sprite is placed in world space with Sprite#setPosition(double, double, double) and is drawn as a billboard that always faces the camera, so your existing 2D art keeps working in 3D:

getCamera()
    .setPerspective(60, 0.1f, 500f)   // vertical FOV, near, far
    .setPosition(0, 6, 12)            // eye
    .setTarget(0, 0, 0);             // look-at

Sprite tree = new Sprite(treeImage);
tree.setPosition(0, 1, 0);            // world coordinates, y up
tree.setSize(2, 4);                   // size is now in world units, not pixels
getScene().add(tree);

World coordinates are right-handed with y up (the com.codename1.gpu convention), and a sprite’s size is world units rather than pixels — use Sprite#setSize(float, float) or Sprite#setScale(float) to pick a world-space size. Move the camera each frame in update(double) to follow the player.

21.8.2. 3D models

Model draws a real 3D mesh — a com.codename1.gpu.Material plus a position, rotation, and scale. Because GPU meshes need the com.codename1.gpu.GraphicsDevice, build them in GameView#onSetup(com.codename1.gpu.GraphicsDevice), the render-thread hook that runs once before the first frame:

protected void onSetup(GraphicsDevice device) {
    Mesh cubeMesh = Primitives.cube(device, 1f);
    Material gold = new Material(Material.Type.PHONG).setColor(0xffffcc33).setShininess(32);
    crate = new Model(cubeMesh, gold).setPosition(0, 0.5f, 0);
    addModel(crate);

    getLight().setDirection(-1, -1, -0.5f);   // shade the lit material
}

protected void update(double dt) {
    crate.setRotation(0, crate.getRotationY() + (float) (60 * dt), 0);  // spin
}

onSetup is also where you load real assets with com.codename1.gpu.GltfLoader (glTF .glb/.gltf models). Models are drawn opaque and depth-written before the alpha-blended billboards, and the billboards depth-test against them, so closer geometry correctly hides what’s behind it. GameView#getLight() controls the directional light that shades lit material types.

21.8.3. Meshes and textures

The built-in meshes are com.codename1.gpu.Primitives#cube(GraphicsDevice, float) and Primitives#quad(GraphicsDevice, float); a quad rotated flat makes a ground or a wall. Model#setScale(float, float, float) reshapes one cube mesh into crates, pillars or buildings of any proportion, so a whole skyline can share a single mesh. Lit materials multiply their base color by a texture, so you can detail a surface — a grid on the ground for depth, say — by drawing an com.codename1.ui.Image and uploading it with com.codename1.gpu.GraphicsDevice#createTexture(com.codename1.ui.Image):

Mesh ground = Primitives.quad(device, 64f);
Texture grid = device.createTexture(makeGridImage());      // any Image you draw
Material mat = new Material(Material.Type.LAMBERT)
        .setColor(0xff3f7d4f).setTexture(grid);
Model floor = new Model(ground, mat).setRotation(-90, 0, 0); // lay the quad flat
addModel(floor);

// one cube mesh, scaled into buildings of varying height:
Model tower = new Model(cubeMesh, brick).setScale(1.5f, 4f, 1.5f).setPosition(9, 2, 0);
addModel(tower);

For richer geometry, load glTF (.glb/.gltf) assets with com.codename1.gpu.GltfLoader from onSetup.

21.9. Low latency audio: SoundPool

Music and video use the regular MediaManager, but rapid overlapping sound effects — gunshots, coins, footsteps — need a different tool. SoundPool loads short clips once and triggers them with minimal latency, mixing several at the same time.

play returns a voice id (or -1 if the pool is momentarily exhausted — it never blocks on the hot path). The parameters are: volume 0 to 1, pan -1 (left) to 1 (right), rate playback speed/pitch (1.0 is normal), and loop (0 once, -1 forever, n extra repeats). stop, pause, resume, stopAll, autoPause and autoResume manage playback; release() frees the pool.

On platforms with a purpose built low latency audio engine — Android’s SoundPool, iOS AVAudioEngine, the desktop javax.sound.sampled mixer and WebAudio in the browser — the pool uses it directly with full volume/pan/pitch support. Where none exists it falls back to a MediaManager based pool that still works everywhere but has higher latency and ignores pan and rate. isNativeAccelerated() tells you which path is active.

To react as a sound finishes — chaining clips, recycling a game object when its effect ends — register a VoiceListener. It’s called on the EDT with the voice id as each voice completes. Not every native engine can report completion, so guard with isVoiceCompletionSupported():

if (sfx.isVoiceCompletionSupported()) {
    sfx.setVoiceListener(new VoiceListener() {
        public void onComplete(int voiceId) {
            onEffectFinished(voiceId);
        }
    });
}
Load your sounds once, up front — ideally on a background thread with SoundPool.loadAsync(…​) — and keep the SoundEffect references for the life of the game. Decoding on the fly defeats the purpose.

21.10. Physics

The com.codename1.gaming.physics package adds 2D rigid body physics. It’s an idiomatic wrapper around a pure Java port of the well known Box2D engine, so it runs on every platform — including iOS, where it’s translated to C with no native code.

21.10.1. Units: Pixels, meters and the y-axis

Box2D is tuned for objects a few meters across, so the world works in meters internally while exposing pixels to you. The conversion is governed by setPixelsPerMeter(float) (default 30). The wrapper also flips the y-axis — Box2D points y up, the screen points y down — so your code stays in screen coordinates. The practical consequence: a positive gravity y pulls bodies down the screen.

21.10.2. Worlds and bodies

Create a PhysicsWorld, populate it with PhysicsBody objects, and step it once per frame from your update:

PhysicsWorld world = new PhysicsWorld(0, 900);   // gravity 900 px/s^2 downward

// a STATIC floor that never moves
world.createBox(160, 460, 320, 40, BodyType.STATIC);

// a DYNAMIC crate affected by gravity and collisions
PhysicsBody crate = world.createBox(160, 0, 32, 32, BodyType.DYNAMIC);
crate.setRestitution(0.4f);   // bounciness
crate.setFriction(0.5f);

// in update(double dt):
world.step((float) dt);

Bodies come in three kinds, the BodyType values: STATIC (immovable — ground, walls), KINEMATIC (moved by you via velocity, unaffected by forces) and DYNAMIC (fully simulated). Bodies can be boxes, circles or polygons (createBox, createCircle, createPolygon) and respond to setLinearVelocity, applyForce, applyLinearImpulse, applyTorque, setBullet (continuous collision for fast objects), setFixedRotation and more.

For an arbitrary outline, createShape(x, y, shape, type) takes a Codename One com.codename1.ui.geom.Shape — typically the same com.codename1.ui.geom.GeneralPath you would draw with — and builds the collision fixtures from it, flattening any Bezier curves. Each subpath becomes a fixture (so a figure with several outlines is a compound body); a closed convex subpath of up to eight points becomes a solid polygon usable by any body type, while a concave, larger, or open subpath becomes a one-sided edge chain (ideal for static terrain). This lets the hit-shape and the drawn shape come from one piece of geometry:

GeneralPath ramp = new GeneralPath();
ramp.moveTo(0, 0);
ramp.lineTo(240, 0);
ramp.lineTo(240, 80);
ramp.closePath();
world.createShape(40, 380, ramp, BodyType.STATIC);   // collide with exactly what you draw

21.10.3. Driving sprites from physics

A body can drive a sprite directly. Sprite implements PhysicsLinkable, so linking the two means world.step(…​) updates the sprite’s position and rotation automatically (in pixels, screen space) — and the scene draws it there:

Sprite crateSprite = new Sprite(crateImage);
crate.setLinkedSprite(crateSprite);
getScene().add(crateSprite);

// in update(double dt):
world.step((float) dt);   // moves crate, which moves crateSprite, which the scene draws

21.10.4. Collisions

Register a ContactListener to be told when bodies start and stop touching. Callbacks fire from inside step(…​) — on the game loop thread — so you can read and update game state directly, but you must not create or destroy bodies during the callback; defer that until after step returns.

If you need a feature the wrapper doesn’t expose, PhysicsWorld.getNativeWorld() and PhysicsBody.getNativeBody() give you the underlying engine objects (which work in meters, y up).

21.10.5. Joints

Joints constrain how two bodies move relative to each other — hinges, ropes, axles, welds. PhysicsWorld creates them in pixel coordinates and returns a PhysicsJoint handle:

// a hinge the two bodies pivot around (anchor in pixels)
world.createRevoluteJoint(bodyA, bodyB, pivotXpx, pivotYpx);
// a fixed-length link, like a rod between two crates
world.createDistanceJoint(bodyA, bodyB, ax, ay, bx, by, 0f, 0f);
// drag a body toward the finger -- great for "pick up and throw"
PhysicsJoint drag = world.createMouseJoint(ground, body, px, py, 1000f);
// ... while the finger moves:
drag.setTarget(getInput().getPointerX(), getInput().getPointerY());
// ... on release:
drag.destroy();

createWeldJoint and createPrismaticJoint (a sliding axis) round out the set.

21.10.6. Debugging physics

When sprites and bodies drift apart it helps to see the raw simulation. Call world.debugDraw(Graphics) to overlay every fixture, joint and contact straight onto a Codename One Graphics — shapes, centers of mass and bounding boxes — in pixel space, with the y-axis flip already applied. Choose what to show with setDebugDrawFlags(shapes, joints, boundingBoxes), and soften the translucent shape fill with setDebugFillAlpha(alpha). Because it draws to an ordinary Graphics you can render it over a regular Codename One component, not only a GameView.

21.11. Putting it together: Anatomy of a game

Every sample follows the same shape, which is the recipe for your own game:

  1. Subclass GameView and, in its constructor, create your Sprite and AnimatedSprite objects and add them to getScene().

  2. Allocate GPU resources in onSetup(GraphicsDevice) — meshes, textures and 3D Model objects — because those need the device.

  3. Add controls (a joystick and buttons) once the view has a size.

  4. Advance the world in update(double dt): read getInput(), move sprites or step a PhysicsWorld, scale all movement by dt, and trigger SoundPool effects.

  5. Show it: add the view to a Form and call start().

The samples project has several runnable examples to copy from:

  • CasualGameSample — sprites, per-sprite animation, collision and particle bursts in a top-down arena (see Section 21.1, “Sample games”).

  • ScrollerGameSample — an AnimatedSprite walk cycle, a parallax backdrop and a scrolling Scene camera.

  • Gaming3DDemoSample — lit cube Model objects, a textured ground and billboarded sprites under a perspective camera.

  • GamingDemoSample — the physics tour, built on a PhysicsWorld with a floor and walls, tap-to-drop balls that bounce (each Sprite linked to its body) and a SoundPool blip whose pitch varies per drop.

  • CardGameSample — a flat 2D Memory match: a grid of card Sprite objects with a flip animation and tap hit-testing.

  • BoardGameSample — faux-3D checkers: flat sprites placed in an isometric projection, with screen-to-cell picking, full rules and a small AI.

Each is a single self-contained file that generates its art at runtime, so it needs no assets — a compact starting point you can copy and reshape.

21.12. Performance notes

  • Keep update non-blocking — it runs on the render thread. Load assets off the render thread and hand them back with CN.callSerially.

  • Reuse images: the renderer caches one GPU texture per Image, so sharing an image across many sprites uploads it once. Cache cut sprite frames (use SpriteSheet, which does it for you) rather than re-slicing every frame.

  • Load every SoundEffect up front and reuse it.

  • Tune setPixelsPerMeter so your moving bodies are on the order of a meter (tens of pixels) in size; bodies far larger or smaller than that make the simulation unstable.

The physics engine in com.codename1.gaming.physics.box2d is a derived work of JBox2D (a Java port of the Box2D engine), used under the BSD 2-Clause license; see the project NOTICE file for attribution.

22. The Game Builder

The Game Builder is a visual level / map editor for the com.codename1.gaming API. You lay out a game world — tiles, characters, items, the camera — set per-object behavior values, preview it live, and Build it into your project as a data file plus a small Java companion that the runtime plays. It’s to games what the GUI builder is to forms.

This chapter covers the whole feature: the underlying model, the editor UI, building a level, defining game rules, the supported game types, and the Maven workflow.

22.1. How it fits together

A game built with this tool has three layers:

LayerRoleWho authors it

Level data (*.game)

A JSON description of the scene: grid, layers, placed elements + their properties, camera, lights.

The Game Builder (visual)

Companion class (*.java)

A thin GameSceneView subclass that loads the data and holds your game logic.

Generated once, then you edit the onUpdate body

Gaming engine (com.codename1.gaming)

Renders and runs the scene on the GPU, with pollable input, sound and optional Box2D physics.

The framework

The key idea: the editor produces data, your companion adds rules, the engine runs it. Because the level is data you can re-edit it any time without touching your code, and your onUpdate logic is preserved across regeneration.

22.1.1. The level model — com.codename1.gaming.level

ClassPurpose

GameLevel

The saveable level: getMode() (MODE_2D / MODE_3D / MODE_BOARD), grid, layers(), elements(), camera, lights(), getTerrain(). load(json) / toJson().

GameElement

A placed thing: id, name, assetId, layer, a transform and a typed property bag (getInt/getDouble/getString/getBoolean). It’s not a Sprite, so the same model works in 2D and 3D.

Layer

A named band: KIND_TILE (an assetId-per-cell grid), KIND_ENTITY, KIND_MODEL; plus isVisible() / isLocked().

AssetCatalog / AssetPack / AssetDef

Resolve an assetId to artwork and default properties. Packs ship as JSON.

GameSceneView

A turnkey GameView that plays a level: it realizes 2D/board sprites and, in 3D, sets up the perspective camera, lights and a Model per element. Put game logic in onUpdate(double dt).

IsoProjection, TileLayer, LevelLight, TerrainGrid

Board isometric math, fast single-tileset grids, and 3D lighting / terrain data.

Loading and playing a level at runtime is three lines:

GameLevel level = GameLevel.load(
        // Flat resource namespace on the device -- "/Level1.game", not
        // "/games/Level1.game", which resolves to null there. This is the
        // path the editor's generated companion uses.
        Display.getInstance().getResourceAsStream(MyScene.class, "/Level1.game"));
// load() only parses the pack definitions. resolveArt() is what loads the
// images, sheets and meshes they name, and the 2D constructor realizes
// sprites immediately -- so resolve before constructing, or the scene is
// built from placeholders and stays that way.
AssetCatalog catalog = AssetCatalog.load(packsJson);
catalog.resolveArt();
GameSceneView view = new GameSceneView(level, catalog);
form.add(BorderLayout.CENTER, view);
form.show();
view.start();

22.2. Getting started

Create a scene from a Java 17 Codename One project:

mvn cn1:create-game-scene -DclassName=com.example.game.Level1 -Dmode=2d

-Dmode is 2d (default), 3d or board. This writes common/src/main/resources/games/Level1.game (an empty level of that type) and common/src/main/java/com/example/game/Level1.java (the GameSceneView companion).

Open the editor bound to the project — the same way cn1:guibuilder launches the GUI builder:

mvn cn1:gamebuilder

The editor itself is delivered through Maven: the goal resolves the com.codenameone:codenameone-gamebuilder artifact from the Codename One Maven repository (the same mechanism that delivers the Designer resource editor), so there is no separate install step. The cn1:gamebuilder goal only applies to Java 17 Codename One projects.

22.3. The editor at a glance

The Game Builder editing a 2D platformer
  • Top bar — the project / scene dropdown (switch scenes, rename, or start a new scene of any game type), undo / redo, the grid and snap toggles, zoom, a text-size toggle (Small / Medium / Large), the </> button (opens the scene’s Java in your IDE), Live (play in place) and Build (save into the project).

  • Tool rail (left) — Select, Move, Brush, Fill, Erase, Pan.

  • Resizable panels — drag the thin divider on the inner edge of the left panel or the inspector to resize it.

  • Hierarchy — the scene card plus the layers. Each layer shows its item count, a visibility eye (hides the layer), a lock (prevents edits) and a ⋮ menu to rename or delete it; drag a placed object onto another layer (or above/below a sibling) to move or reorder it. Placed objects nest under their layer, and unique objects (the player) carry a UNIQUE badge.

  • Canvas — the editable stage is the bright-bordered rectangle with the grid; painting only happens inside it.

  • Asset Library (center-bottom) — pick a pack tab, then click a thumbnail to select an asset. Selecting a tile asset switches to a tile layer; selecting an actor switches to an entity layer, so the brush always works on the next click. Import (top-right) brings in your own artwork as a new asset.

  • Inspector (right) — scene settings when nothing is selected, or the selected object’s properties.

Because it’s a desktop application, every command is also available from the native menu bar (drawn by the OS), grouped by convention: File (New 2D / 3D / Board, Open Scene, Save), Edit (Undo, Redo, Delete Selection), View (Toggle Grid / Snap, Zoom In / Out, Show Generated Code), Tools (Select / Move / Brush / Fill / Erase / Pan), Layer (Add Layer) and Game (Play / Stop). The standard accelerators work too — Cmd/Ctrl+Z undo, Cmd/Ctrl+S save, Cmd/Ctrl+R play, Cmd/Ctrl+= / Cmd/Ctrl+- zoom. Every on-screen control also has a tooltip.

22.4. Building a level

  1. Choose a game type — scene dropdown → New scene → 2D Platformer, 3D Map or Board (or scaffold with -Dmode).

  2. Paint terrain — pick the Brush, click a tile in the Asset Library, then click/drag inside the stage. Fill flood-fills a region; Erase clears cells.

  3. Place characters and items — click an actor asset and click on the stage to stamp it. With Snap on, actors land on grid cells. The Player is unique — stamping it again moves it.

  4. Organize with layers — placed objects nest under their layer in the hierarchy, so you can always see which band each one is on. The eye hides a layer while you work (its name dims), the lock prevents edits to it, the chevron collapses its children, and + adds a layer. To move a selected object to a different layer (changing its draw order), use the Layer picker in the Inspector’s Transform section.

  5. Undo / redo every change with the toolbar arrows.

  6. Save with Build — it writes Level1.game and, the first time, the companion Level1.java.

22.5. Defining game rules

Game rules live in two complementary places.

22.5.1. Data — set in the Inspector

Editing a selected object’s properties

Select an object to edit its Transform (name, position, Layer dropdown) and its Behavior properties — the typed values that parameterize how it acts:

ObjectBehavior properties

Player / Hero

lives, jumpHeight

Coin / Gem

value

Enemy (slime)

speed, patrol

Door / Goal

target (next scene)

Torch

lightRadius

Card / Token / Dice

suit/rank, player/cell, sides

These defaults come from the asset — the Inspector’s read-only Asset section shows the id, kind, size and unique flag, and Edit asset defaults… lets you change an asset’s default size and properties (for example, tune ground/coin). Use Add property… to attach your own game metadata (hitPoints, value, …) to a single object, readable at runtime via el.getInt(…​) / el.getDouble(…​). This is the player marks which element the preview and arrow keys drive (otherwise a player/hero/spawn asset is used).

Scene-wide rules are set in the Inspector when nothing is selected: gravity, background theme, grid Cols / Rows / Tile size and the Mode. These are saved into the .game file and are available at runtime on each GameElement.

22.5.2. Logic — written in the companion

The behavior values are data; the behavior itself is code you write in the generated companion’s onUpdate(double dt). GameSceneView realizes every element into a sprite whose getUserData() is the source GameElement, so you read the properties you set in the editor:

@Override
protected void onUpdate(double dt) {
    // The generated companion switches the built-in arcade behaviour on, and
    // that already patrols enemies and collects pickups. A scene doing the
    // work itself calls setArcadeBehavior(false) in its constructor -- with
    // both running, the built-in patrol and the step below cancel out and
    // the slime stalls.
    GameInput in = getInput();
    Scene scene = getScene();
    // The editor names a stamped object after the asset's display name, so
    // the generated companion has a field like duke1 rather than "player".
    // Look the sprite up by asset id instead of assuming a field name.
    Sprite player = findByAsset("player");
    // Backwards, because collecting a coin removes it from the scene and a
    // forward loop would step over the next sprite.
    for (int i = scene.size() - 1; i >= 0; i--) {
        Sprite s = scene.get(i);
        // Tile sprites carry a Layer in their user data, not a GameElement, so
        // a plain cast fails on the first frame of any scene with painted
        // tiles. elementOf() answers null for those. It also matters that this
        // is not a cast: ParparVM does not check them, so on iOS a bad cast
        // reads the wrong object's fields instead of throwing.
        GameElement el = elementOf(s);
        if (el == null) continue;
        switch (el.getAssetId()) {
            case "player" -> {
                if (in.isGameKeyDown(Display.GAME_RIGHT)) s.setX(s.getX() + 200 * dt);
                // jump height, lives, gravity... all read from el.getInt(...)/getDouble(...)
            }
            // speed is pixels per second, so scale it by the frame delta --
            // otherwise the patrol runs at whatever rate the device renders at
            case "slime" -> s.setX(s.getX() + el.getDouble("speed", 60) * dt);
            case "coin"  -> {
                if (s.intersects(player)) {
                    addScore(el.getInt("value", 10));
                    scene.remove(s);   // consume it, or it scores again every frame
                }
            }
        }
    }
}

Win/lose conditions, scoring, enemy AI and level transitions (using a door’s target) are all decided here. For rigid-body games use com.codename1.gaming.physics inside onUpdate. In short: the editor decides the layout and the numbers; your companion decides the behavior; the engine runs it.

22.6. Game types

The mode (chosen per scene) plus the asset pack determine how the same level model is realized:

ModeRealized asPacksUse for

MODE_2D

`Sprite`s in pixel space, tile grids

Platformer, Top-Down RPG

platformers, shooters, top-down adventures

MODE_BOARD

Sprite`s placed through an isometric `IsoProjection

Board & Card

board games, strategy, card games

MODE_3D

Model`s under a perspective `GameCamera, with LevelLight`s and a `TerrainGrid

3D Kit

3D maps, arena / tycoon layouts

Switch type from the scene dropdown’s New scene buttons or scaffold with -Dmode=2d|3d|board. In 3D mode the Inspector also exposes the camera rig, lighting and terrain; placed elements become meshes (import your own glTF via GltfLoader from the companion’s buildModels hook).

Editing a 3D map — the board autofits the canvas and zooms

In 3D mode the board is edited top-down (placement, terrain and lighting), and the grid autofits the canvas so it stays usable at any size and zoom. Each placed element reads as a single object on the grid rather than a flat sprite filling the board.

22.7. Live preview

Live preview — playing the level in a device frame

Press Live to play the level in place inside a device frame with a HUD. The preview ships default behaviors so common cases work without any code: in a 2D platformer the arrow keys move the player and Up / Space jumps (gravity and tile collision are simulated), coins/gems are collected for score, and enemies patrol and cost a life on contact. The on-screen hint shows the controls, and the SCORE / LIVES HUD is live. Press Stop to return to editing — playing never mutates the level.

For a 3D map the preview switches to a true perspective view — a receding ground grid with the placed meshes rendered as depth-sorted objects under an orbiting camera — so you see 3D gameplay rather than a flat top-down board:

The 3D live preview — perspective camera over the board

The in-editor preview is for quick iteration; for full-fidelity play on device, run the companion in your app, where the scene is rendered by the GPU-accelerated GameSceneView.

22.8. Build, save and run

Build writes the level to src/main/resources/games/<Scene>.game and (once) the companion <Scene>.java. To show the scene in your app, instantiate the companion and start() it:

Form game = new Form("Play", new BorderLayout());
// The generated scene takes the catalog as a constructor argument, and
// neither the scaffold nor the build produces one: it is yours to supply.
// Bundle the pack JSON your level references as an app resource and load
// it here. StarterPacks, which the editor uses, ships with the editor and
// is not on an application's classpath.
AssetCatalog catalog = AssetCatalog.load(
        Display.getInstance().getResourceAsStream(Level1.class, "/my-packs.json"));

// load() only parses the definitions. Nothing else loads the images,
// sprite sheets and meshes they name, so without this the scene renders
// placeholders and the sheets never animate.
catalog.resolveArt();
Level1 scene = new Level1(catalog);
game.add(BorderLayout.CENTER, scene);
game.show();
scene.start();

The level is plain data, so you can ship many .game files and load whichever level the player selects.

22.9. Maven goals

GoalPurpose

cn1:create-game-scene -DclassName=… -Dmode=2d|3d|board

Scaffold a .game + companion (Java 17 projects only).

cn1:gamebuilder

Launch the editor bound to the current project.

22.10. Extending

  • Asset packs are JSON ({"packs":[{"id","name","assets":[{"id","kind","w","h","color","unique","source","defaults"}]}]}) loaded by AssetCatalog.load. Add your own pack with real art.

  • Asset art follows the SVG/Lottie approach: reference source art per asset and let the build translate it to code/raster; where no art is supplied the catalog draws a recognizable placeholder so a level always renders.

  • Behaviors can be factored into reusable helpers driven entirely from the property bag, keeping levels data-only.

22.10.1. Importing your own art

To bring in custom artwork, click Import in the Asset Library header and pick an image.

Importing a custom image into the Custom asset pack

The image is added to a Custom pack as a new asset (a tile when a tile layer is active, otherwise an actor), selected and ready to paint or stamp immediately. When the editor is bound to a project, the picture is copied into src/main/resources/games/assets/ and recorded in games/custompack.json, so it survives reloading and ships with the project — the generated game resolves it through the same AssetCatalog.

23. Game Assets

Every visible thing in a Game Builder level — the ground a player walks on, a coin to collect, an enemy, a 3D crate — is drawn from an asset. This chapter explains what an asset is, how assets are organized into packs and resolved by the catalog, where their artwork comes from, and how to create your own (either by authoring a pack JSON entry or by importing an image inside the editor). It closes with a note on terrain materials, a related-but-separate concept, and pointers for finding more art.

The classes live in com.codename1.gaming.level: AssetDef, AssetPack and AssetCatalog.

23.1. What an asset is

An asset is a reusable template — an AssetDef — not a thing in your level. It says "this is what a coin looks like and what default values a coin has," and any number of coins in any number of levels reference that one definition by id.

An AssetDef carries:

FieldMeaning

getId()

The stable string key (for example, coin, player, ground). A placed element references this id, the catalog indexes by it, and imported art is filed under it.

getName()

The human-readable display name shown in the editor palette (for example, Coin). Defaults to the id.

getKind()

AssetDef.KIND_TILE (painted into a cell of a tile layer’s grid) or AssetDef.KIND_ACTOR (a free-form entity / model). isTile() is a convenience.

getWidth() / getHeight()

The natural pixel size of the art (default 32×32).

getColor()

A base ARGB colour used to render a flat placeholder until real artwork is available (default 0xff888888).

isUnique()

Whether a level should hold at most one of these (for example, the player / spawn point).

getSource()

An optional reference to the source art (a resource path, an SVG/Lottie key, or the assets/<id>.png path written for an imported image).

defaultProperties()

The default authoring property values copied onto a freshly placed element — a coin’s value, a player’s lives and jumpHeight, and more.

23.1.1. Asset (template) versus placed element (instance)

How a placed element relates to its asset template

Keep this distinction clear:

  • An asset (AssetDef) is the shared template. There is exactly one coin definition.

  • A placed element (GameElement) is one instance in a level. It stores its own position, size and property values, and references the template through GameElement#getAssetId().

When you drop a coin into a level, the editor creates a GameElement whose assetId is coin and copies the asset’s defaultProperties() into the element’s own property bag (see StarterPacks.addActor, which does exactly this with el.properties().putAll(def.defaultProperties())). You can then tweak that one coin’s value without affecting the template or any other coin. Changing the asset’s size or art, conversely, affects how every instance that references it’s drawn.

23.2. How assets are structured

Assets are grouped into packs, and packs are indexed by a catalog:

  • AssetPack — a named, ordered group of AssetDef`s (`add(def), get(id), assets()). The order is the order they appear in the palette. A GameLevel names the pack it draws from via GameLevel#getAssetPack().

  • AssetCatalog — holds one or more packs and answers two questions for any asset id: def(id) returns the AssetDef (used for kind, size and default props), and image(id) returns the artwork. Real art is supplied via setImage(id, image); until then image(id) returns a cached solid-colour placeholder sized from the def and tinted with its getColor(), so a level always realizes to something visible.

23.2.1. The built-in packs

The editor ships four starter packs in the classpath resource /gamebuilder-packs.json, loaded by StarterPacks.loadCatalog() (which calls AssetCatalog.load(InputStream)). The same catalog drives both the editor palette and a generated game’s runtime loader.

Pack idNameAsset ids

platformer

Platformer

ground, grass, brick, crate, ladder, spike (tiles); coin, gem, player, slime, door, flag (actors)

topdown

Top-Down RPG

floor, wall, water, tree, path (tiles); hero, npc, chest, torch (actors)

board

Board & Card

boardtile, start (tiles); card, token, dice (actors)

kit3d

3D Kit

block, crate3d, barrel, pillar, tree3d, rock, spawn (all actors)

StarterPacks.defaultPackFor(mode) picks kit3d for MODE_3D, board for MODE_BOARD and platformer otherwise.

The JSON format is {"packs":[{"id":..,"name":..,"assets":[ …​ ]}]}. Here is one real asset entry from the platformer pack — the player:

{ "id": "player", "name": "Player", "kind": "actor",
  "w": 28, "h": 32, "color": "#4D86FF", "unique": true,
  "defaults": { "lives": 3, "jumpHeight": 96 } }

Each JSON key maps onto an AssetDef field (see AssetDef.fromMap): kind is "tile" or "actor", w/h are the pixel size, color is #rrggbb, unique is a boolean, source is the optional art reference, and defaults becomes defaultProperties().

23.3. Where the art comes from

An AssetDef names an art format — TYPE_IMAGE, TYPE_SHEET or TYPE_MESH — and a getSource() art file. AssetCatalog.resolveArt() loads each asset’s art from that file into the catalog, so the same definition drives the editor palette and a shipped game.

23.3.1. Static images (TYPE_IMAGE)

A single .png/.jpg. resolveArt() decodes it; image(id) returns it and the level realizer wraps it in a com.codename1.gaming.Sprite. The starter packs ship one image file per asset (at the flat resource root, loaded as /<id>.png), so every starter sprite — ground, the player, the mountains — is a real file you can open in any editor and replace.

23.3.2. Sprite sheets (TYPE_SHEET)

One image laid out as a grid of equal frames, plus a frame size and rate (frameW, frameH, fps). resolveArt() builds a com.codename1.gaming.SpriteSheet; the realizer creates an animated com.codename1.gaming.AnimatedSprite that the scene advances each frame. The starter coin is a six-frame sheet, so it spins at runtime with no code; image(id) returns its first frame for the editor palette.

23.3.3. Meshes (TYPE_MESH)

A glTF/.glb model for a 3D level. resolveArt() keeps the file’s bytes and GameSceneView.buildModels loads them with com.codename1.gpu.GltfLoader, realizing a com.codename1.gaming.Model (and falling back to a primitive cube for an asset that has no mesh). Sprite sheets and glTF loading are existing Codename One features; the asset model just makes them first-class so the editor and runtime treat them as assets.

23.3.4. Imported art (the editor’s Import button)

The Import action opens the gallery (Display#openGallery) and hands the chosen image’s bytes to GameBuilder.registerImportedAsset(…​), which builds an image AssetDef (kind from the active layer), adds it to a Custom pack and persists the PNG to <gamesDir>/assets/ plus the pack definition to <gamesDir>/custompack.json. On the next launch ProjectIO.loadCustomPack reads them back, so an imported image survives a reload. Sprite sheets and glTF meshes are added the same way at the file level — drop the file into <gamesDir>/assets/ and add a pack entry with the matching type (and frame size for a sheet); resolveArt then loads it like any other asset. (A dedicated sheet/mesh import UI is a natural follow-up.)

23.3.5. Generating the starter images

The bundled starter PNGs are produced once by a build-time generator (StarterArtGenerator, which draws each sprite with Graphics through AssetArt) and committed as resources — there’s no art-drawing code in the shipped runtime. Re-run the generator after changing a starter sprite or pack.

In every case the catalog falls back to the flat-colour placeholder when an asset’s art is missing, so a level is never un-renderable.

23.4. Creating your own asset

There are two practical paths.

23.4.1. Path 1: Author a pack JSON entry

Add an entry to a pack’s assets array using the same format as the built-ins. For example, a collectible key:

{
  "id": "key",
  "name": "Key",
  "kind": "actor",
  "w": 24,
  "h": 24,
  "color": "#E0C040",
  "unique": false,
  "defaults": { "opens": "door", "value": 1 }
}

Field by field:

  • id — unique string key your placed elements and any art will reference. Required.

  • name — display name in the palette. Optional; defaults to the id.

  • kind — "tile" to paint into grid cells, "actor" for a free-form entity. Anything other than "tile" is treated as an actor.

  • w / h — natural pixel size. Optional; default 32.

  • color — #rrggbb placeholder colour used until real art is supplied. Optional.

  • unique — true to limit the level to one instance. Optional; default false.

  • defaults — a map of default property values copied onto each placed element.

  • source — the art file the runtime loads: a .png/.jpg (image, sheet) or a .glb/.gltf (mesh). Optional; the starter packs default it to <id>.png.

  • type — "image", "sheet" or "mesh". Optional; inferred from source (a .glb is a mesh) or frameW (a sheet) when omitted.

  • frameW / frameH / frames / fps — sprite-sheet frame size, frame count (0 = all) and playback rate, for a "sheet" asset.

You can add this to a copy of gamebuilder-packs.json, or build a pack in code with new AssetPack(id, name).add(new AssetDef(…​)) and register it with catalog.addPack(pack). To give it real art, point source at a bundled art file and call catalog.resolveArt(), or supply an image directly with catalog.setImage("key", image).

23.4.2. Path 2: Import an image in the editor

The no-code path: open your level in the Game Builder, select the layer you want the asset to belong to (a tile layer for tiles, an entity/actor layer otherwise), and use the Import action ("Import your own image as a new asset"). Pick a PNG (or other supported image), and the editor creates the AssetDef and files it under the Custom pack. Once bound to a project, the editor also saves the PNG and a pack-JSON entry under the project’s games/assets/ directory as described above. The new asset appears in the palette and is immediately placeable.

23.5. Terrain materials

3D terrain surfaces use a different, pluggable concept: materials, not sprite assets. A Material (com.codename1.gaming.level.Material) describes a surface — a base colour, whether it’s solid (blocks movement), a friction multiplier, and an optional artId for textured rendering — and is referenced everywhere by its string id.

Materials are resolved through MaterialRegistry, a process-wide registry that ships six built-ins (MaterialRegistry.GRASS, ROAD, STONE, SAND, WATER, DIRT). WATER is registered as solid. Applications add their own without changing the level format:

MaterialRegistry.register(new Material("lava", "Lava", 0xc0392b).setSolid(true));
Material m = MaterialRegistry.get("lava");   // never null; unknown ids return gray

Unknown ids resolve to a neutral gray placeholder, so a level that references a not-yet-registered material still loads. Materials cover terrain cells and `TerrainFeature`s; the sprite/model assets covered above are a separate system.

23.6. Where to get more

  • Reuse the built-in packs. The four starter packs cover platformer, top-down RPG, board/card and a small 3D kit out of the box — start there and only add what you need.

  • Import your own art. Any PNG (or supported sprite image) can be imported through the editor’s Import action and becomes a first-class asset in your project’s Custom pack. Authoring at the asset’s natural pixel size keeps it crisp.

  • Author packs as JSON. For larger sets, hand-author or generate AssetPack JSON entries alongside the built-ins so the whole pack loads through AssetCatalog.load.

  • Use external game-art sources. Plenty of open game-art libraries and your own design tools (vector editors, pixel-art tools) can produce sprite sheets and tiles. Whichever source you use, you are responsible for honoring its license — check the terms for attribution and commercial-use requirements before shipping art you didn’t create.

24. Running Flutter applications

Codename One builds a Flutter application from its Dart source. The Dart is translated to Java at build time, and the result is an ordinary Codename One application: no Dart VM, no embedded rendering engine and no platform view ship with it. It builds for every platform Codename One targets, and it comes out smaller, quicker to start and lighter on memory than the same application built by Flutter.

Dart support is experimental. Most widgets render, but some callbacks and parameters are accepted and then ignored, and the pipeline has so far been verified against one large sample application. Test every interaction your screens depend on before shipping.

24.1. Smaller, faster and lighter than Flutter

The charts below come from one application, the Flutter Gallery, built both ways from the same Dart source: once by the Flutter toolchain’s own release build, and once by Codename One. Both builds are measured on the same machine, in interleaved rounds, on every change to the project. Lower is better throughout.

Installed size of the Flutter Gallery per platform: Codename One against Flutter
Executable code of the Flutter Gallery per platform: Codename One against Flutter
Cold start to the first frame per platform: Codename One against Flutter
Memory at rest per platform: Codename One against Flutter

The comparison is tilted toward Flutter. The application is Flutter’s own showcase, written by the Flutter team in Flutter’s idioms, and Codename One runs it as it is. To do that the Codename One build carries a runtime that reimplements Flutter’s widget, element and layout model on top of Codename One components, which is work an application written for Codename One never pays for. The same screens written directly against Codename One’s own components would be smaller and faster again. The numbers above are what a team gets on the day it moves its Flutter code over, before changing a line of it.

Two platforms aren’t measured in full, and the charts leave them out rather than estimate them:

  • Start-up and memory on iOS. Flutter can’t compile Dart ahead of time for the simulator, so a simulator run would time Flutter’s debug engine against a Codename One release build. iOS sizes come from release device bundles.

  • Start-up and memory on the web. Timing a browser build needs a driver for the browser’s developer tools, which the benchmark doesn’t have, so it reports web sizes only.

Android start-up and memory come from an emulator rather than a phone. They compare the two builds on one machine; they aren’t phone timings. Section 24.10, “How the numbers are measured” explains how each metric is taken.

24.2. What it looks like

The Flutter Gallery’s demos, rendered by Flutter on the left and by Codename One on the right from the same Dart source:

The Flutter Gallery home screen rendered by Flutter and by Codename One
The Cards demo rendered by Flutter and by Codename One
The Text fields demo rendered by Flutter and by Codename One
The Bottom navigation demo rendered by Flutter and by Codename One
The Colors demo rendered by Flutter and by Codename One
The Text button demo rendered by Flutter and by Codename One
The Cupertino buttons demo rendered by Flutter and by Codename One
The Shrine study’s login screen rendered by Flutter and by Codename One
The Reply study’s inbox rendered by Flutter and by Codename One

The Codename One side is a real Codename One component tree, not a picture of one: it uses the theme, the event dispatch thread, the accessibility tree and the native build like any other Codename One screen, and it can share a Form with hand-written Codename One code.

24.3. Importing a Flutter application

One command brings a Flutter project into a Codename One project:

mvn cn1:import-flutter-project -Dcn1.flutter.import=/path/to/flutter_app

Run it in a project generated from the Codename One archetype or the initializr. It does what wiring Flutter in by hand would take:

  • Copies the Dart source in lib into common/src/main/flutter.

  • Copies every asset and font pubspec.yaml declares, including whole asset directories and the assets of the packages the application depends on, which it finds through the project’s .dart_tool/package_config.json or the pub cache.

  • Adds the Flutter runtime to common/pom.xml and makes sure the build translates the Dart.

  • Writes the application’s entry class so that it runs the Dart main(). A class that was already there is saved beside it with a .pre-flutter-import suffix.

  • Carries the application name and version over from pubspec.yaml.

It then lists the application’s pub dependencies and says which of them Codename One provides. A package is provided one of two ways. A pure Dart package is copied and transpiled with the application, file by file, as far as the application’s imports reach into it. A plugin, or a package the runtime implements natively (provider, intl, go_router, firebase_auth and the others in Section 24.8, “Plugin coverage”), is provided by a stub pack: Dart declarations of the package’s API backed by Java. A dependency listed as not covered is the first thing to look at if a screen misbehaves.

24.3.1. The import report

The same report is written as JSON to common/target/flutter-import-report.json, for a script or a CI step to read. Each package has a status (covered or unsupported), the note or the reason, and the application’s own files that reach it. An unsupported package that’s only unsupported because of something it depends on carries the chain that verdict came through, ending with the package that’s unsupported itself:

{"package": "ui_kit", "status": "unsupported",
 "note": "depends on vector_graphics_compiler, which needs dart:ffi",
 "cause": "needs dart:ffi",
 "chain": ["ui_kit", "vector_graphics_compiler"],
 "reachedFrom": ["lib/login/login_screen.dart"]}

The report also lists, under googleFonts, every Google Fonts family the application names. The google_fonts stub draws only fonts bundled with the application, so those are the families to add as assets.

A few kinds of imports are resolved rather than reported:

  • A conditional import (if (dart.library.html) …​) takes the branch for a library the runtime has, so a web-only branch and everything it imports are never read.

  • A plugin that implements only desktop or web platforms is transpiled as Dart. Its calls into the platform answer MissingPluginException, as they would on a mobile device in Flutter.

24.3.2. Parameters that are accepted and not applied

Some stub parameters are accepted so the application compiles, and then have no effect: an HTTP header a media player can’t send, a fit mode an image renderer lacks. A call that passes one gets a build warning at that argument:

[WARNING] src/main/flutter/feed/post.dart:[41,6] 'httpHeaders' of networkUrl is accepted but not applied on Codename One (dart2java:W0002)

Re-running the command later picks up changes made on the Flutter side. A file you edited after the earlier import is left as you edited it, and a file the Flutter project no longer has is removed.

No Dart or Flutter SDK is needed to build the result. The transpiler is Java and runs as part of the normal Maven build. The command reads the pub cache only to find package assets, so run flutter pub get once in the Flutter project if it reports a package it can’t find.

24.4. Migrating an entire application

After the import, the Dart is the application: the entry class calls the Dart main(), whose runApp mounts the widget tree as the root of a Form. Build and run it like any Codename One application, in the simulator or for a device.

FlutterUI.runApp is the same call from Java, the analog of Flutter’s own runApp. It installs the Material base theme, because the widget tree is expected to be the whole UI and to look the way its author intended:

// runApp mounts the tree in a Form of its own and shows it. Unlike
// wrap(), this installs the Material base theme, because the widget
// tree is expected to be the whole UI.
FlutterUI.runApp(new Text("The entire application"));

A port is mostly a question of how much of the Dart language and of the Flutter libraries the application uses. The transpiler reports what it can’t handle rather than guessing: a construct outside the supported subset fails the build with a code naming the feature, so the gaps are a list to work through rather than a runtime surprise. At runtime, a widget that isn’t implemented is recorded through the error inventory instead of drawing nothing.

24.5. Migrating a single form

The same build can carry Dart screens inside an application otherwise written in Codename One, so a migration can go one screen at a time in either direction.

Put the Dart files under common/src/main/flutter; the import command does this, or copy them by hand. Each Dart widget class becomes a Java class of the same name in com.codename1.generated.flutter, with its parameters as constructor arguments in declaration order and the widget key first. A Dart MyHomePage({super.key, required this.title}) is created from Java as new MyHomePage(null, "Inbox").

FlutterUI.wrap inflates the widget into a plain Container, which goes anywhere an ordinary component can:

Form dashboard = new Form("Dashboard", BoxLayout.y());
dashboard.add(new Label("Written in Codename One"));

// A Dart widget tree, compiled to Java at build time. wrap() returns
// an ordinary Container, so it is added like any other component.
dashboard.add(FlutterUI.wrap(new Text("Rendered from Dart")));

dashboard.add(new Button("Also Codename One"));
dashboard.show();

The wrapped widget is a component like any other: it takes part in the parent’s layout, scrolls with it and is styled by the same theme. It doesn’t install the Material base theme, so a Dart screen dropped into an existing form won’t restyle the rest of it.

A wrapped widget isn’t inside a navigator, so it has no Overlay of its own. Dart code that calls Overlay.of(context) from inside it gets the same error it would get outside a Navigator on Flutter; show such a screen as a route of its own instead.

24.6. Calling between Java and Dart

Java and Dart run in the same application, on the same thread, so calls between them are ordinary method calls. There are three ways to make them, and the first is the one a Flutter developer already knows.

24.6.1. Platform channels

A Flutter application talks to its platform code through MethodChannel and EventChannel from package:flutter/services.dart. Those work unchanged: the Dart side compiles unchanged, and the platform side, which is Kotlin or Swift in a Flutter project, becomes Java in the Codename One project. The Java classes in com.codename1.flutter.platform mirror Flutter’s Android io.flutter.plugin.common API, so Android handler code ports by changing its imports.

Dart calling Java. The Dart side invokes a method on a named channel:

// Calls the Java handler registered with MethodChannel.setMethodCallHandler
// on the platform side (FlutterInteropSnippets.answerDartWithAJavaHandler).
final batteryChannel = MethodChannel('com.example.app/battery');

Future<int> getBatteryLevel() async {
  final level = await batteryChannel.invokeMethod('getBatteryLevel');
  return level as int;
}

A Java handler registered under the same channel name answers it:

MethodChannel channel = new MethodChannel("com.example.app/battery");
channel.setMethodCallHandler(new MethodChannel.MethodCallHandler() {
    @Override
    public void onMethodCall(MethodCall call, MethodChannel.Result result) {
        if ("getBatteryLevel".equals(call.method())) {
            result.success(87);
        } else {
            result.notImplemented();
        }
    }
});

result.error(…​) reaches Dart as a PlatformException, and result.notImplemented(), or no handler at all, as a MissingPluginException, as on Flutter. The handler doesn’t have to answer before it returns: keep the Result and complete it when the answer arrives.

Java calling Dart. The direction reverses with the same two classes. Dart registers a handler on the channel:

// Answers calls the Java side makes with MethodChannel.invokeMethod
// (FlutterInteropSnippets.invokeADartRegisteredHandler).
void installBatteryRefreshHandler() {
  batteryChannel.setMethodCallHandler((MethodCall call) async {
    if (call.method == 'refreshBatteryLevel') {
      return getBatteryLevel();
    }
    throw MissingPluginException();
  });
}

Java invokes it and gets the reply through a callback:

MethodChannel channel = new MethodChannel("com.example.app/battery");
channel.invokeMethod("refreshBatteryLevel", null, new MethodChannel.Result() {
    @Override
    public void success(Object result) {
        System.out.println("Dart replied: " + result);
    }

    @Override
    public void error(String errorCode, String errorMessage, Object errorDetails) {
        System.out.println("Dart reported an error: " + errorCode);
    }

    @Override
    public void notImplemented() {
        System.out.println("no Dart handler is registered");
    }
});

Events from Java to Dart. An EventChannel carries a stream of events: a sensor reading, a download’s progress, a message from a server. Java pushes them through the EventSink it receives when Dart starts listening:

EventChannel channel = new EventChannel("com.example.app/sensor");
final EventChannel.EventSink[] activeSink = new EventChannel.EventSink[1];
channel.setStreamHandler(new EventChannel.StreamHandler() {
    @Override
    public void onListen(Object arguments, EventChannel.EventSink events) {
        activeSink[0] = events;
    }

    @Override
    public void onCancel(Object arguments) {
        activeSink[0] = null;
    }
});

// Called whenever a new reading arrives, from wherever that is.
EventChannel.EventSink sink = activeSink[0];
if (sink != null) {
    sink.success(42.5);
}

Dart listens to the stream as it would on Flutter:

// Listens to events the Java side pushes through an EventSink
// (FlutterInteropSnippets.pushEventsFromAJavaStreamHandler).
final sensorChannel = EventChannel('com.example.app/sensor');

StreamSubscription<dynamic> listenToSensorReadings(void Function(double value) onReading) {
  return sensorChannel.receiveBroadcastStream().listen((event) {
    onReading(event as double);
  });
}

onListen runs when the first listener subscribes and onCancel when the last one cancels, so a sensor or a connection is only active while something is listening.

Values cross the channel in the types each side expects, as Flutter’s message codec does:

DartJava

int

Long. An Integer, Short or Byte sent from Java arrives as int.

double

Double. A Float sent from Java arrives as double.

String, bool, null

String, Boolean, null

List, Map

java.util.List, java.util.Map, converted element by element

Every handler runs on the event dispatch thread, and a reply is always delivered asynchronously, never inside the call that asked for it, as on Flutter.

24.6.2. Calling Dart functions directly

Without a channel, Java can call transpiled Dart directly. Each Dart file becomes a class named after it, with Lib appended: lib/greeting.dart becomes LibGreetingLib, and its top-level functions are public static methods of that class. Dart’s main is renamed main$.

String greeting = LibGreetingLib.greet("World");
System.out.println(greeting);

This is the quickest way to reach Dart logic that has no UI, a parser or a pricing rule, from Java. Channels are the better boundary for code that a Flutter build must also keep running, because the Dart side doesn’t change.

24.6.3. Sharing state and callbacks

A ValueNotifier or ChangeNotifier is an ordinary Java object on the Codename One side. Java code that holds one can set its value or call notifyListeners(), and every Dart widget listening to it, through ValueListenableBuilder or AnimatedBuilder, rebuilds. Callback parameters work the other way: an onPressed or onChanged that a Java caller passes into a Dart widget’s constructor is a Java lambda, and the Dart code calls it.

24.7. How it fits together

The pipeline has three stages, and each is an ordinary build step you can run and inspect on its own.

Dart source through the transpiler to the Codename One ports

Dart widget source in src/main/flutter is read by the transcode-flutter goal during generate-sources. It emits Java into target/generated-sources/flutter, which the normal compile phase picks up. At runtime those generated classes call into the Flutter runtime library, which implements the widget, element and render-object model on top of Codename One containers.

The key design point is where the boundary sits. The runtime reimplements Flutter’s layout and composition model — constraints down, sizes up, elements reconciled against widgets — but it doesn’t reimplement Flutter’s rasterizer. Painting is Codename One’s, which is what makes the output a real Codename One component tree rather than a texture.

The goal is bound in every project generated from the archetype and does nothing while src/main/flutter doesn’t exist. To wire a project by hand instead of importing, add the runtime dependency to the common module, where generated projects already carry it commented out:

<dependency>
    <groupId>com.codenameone</groupId>
    <artifactId>codenameone-flutter-runtime</artifactId>
    <version>${cn1.version}</version>
</dependency>

The generated package and the paths are configurable:

PropertyMeaning

cn1.flutter.sourceDir

Where the Dart lives. Defaults to src/main/flutter.

cn1.flutter.outputDir

Where the generated Java is written. Defaults to target/generated-sources/flutter.

cn1.flutter.package

The package the generated classes are emitted into. Defaults to com.codename1.generated.flutter.

24.7.1. Localization and right-to-left layout

GlobalMaterialLocalizations.delegate and GlobalCupertinoLocalizations.delegate supply English, Spanish and Hebrew strings for the built-in widgets, picked by the locale’s language code; any other language falls back to English. Your own delegates and ARB-generated localizations work as they do in Flutter.

Under a right-to-left Directionality, rows, wraps, AlignmentDirectional, stacks, text alignment, list tiles and app bars are mirrored, and the directional arrow and chevron icons swap. A plain Alignment never mirrors, as in Flutter.

24.8. Plugin coverage

These are the pub packages the runtime provides, and how. A package that’s not listed and is pure Dart is transpiled from its own sources.

PackageBacked byAccepted and not applied

firebase_core, firebase_auth

The Identity Toolkit REST API: email and password, anonymous accounts, and Google, Apple and OAuth credentials exchanged through signInWithIdp. signInWithProvider runs Google’s and Apple’s sign-in.

Phone sign-in, multi-factor, account linking

google_sign_in

GoogleConnect, Google’s OIDC sign-in with PKCE in the system browser

signInSilently answers the current run’s account only; hostedDomain

firebase_ui_auth, firebase_ui_oauth_google, firebase_ui_oauth_apple

SignInScreen and ProfileScreen built from the runtime’s Material widgets, over firebase_auth; the Google and Apple buttons sign in as signInWithProvider does

styles, sideBuilder, breakpoint, headerMaxExtent; reported as W0002 warnings

firebase_analytics, firebase_messaging

Logged events and AnalyticsService; Codename One push, including onBackgroundMessage and provisional permission

firebase_ai

The Firebase AI Logic REST API, Gemini through Google AI or Vertex AI, with the App Check token and the signed-in user’s ID token

Function calling, responseSchema, toolConfig; generateContentStream delivers the whole reply as one event; Live and Imagen models

firebase_app_check

The debug provider’s token, from the firebase.appCheck.debugToken Display property

Play Integrity, DeviceCheck and App Attest: there is no attestation, so they yield no token

dio

ConnectionRequest: interceptors, DioException types, CancelToken, FormData, downloads

go_router

The runtime’s navigator: routes, redirects, extra, transitions

cached_network_image

ConnectionRequest with an in-memory cache: placeholder, progressIndicatorBuilder and errorWidget are built

fadeInDuration

google_maps_flutter

MapView: markers with hued or byte icons, polylines, circles, camera, taps

image_picker, camera

Capture and com.codename1.camera; maxWidth, maxHeight and imageQuality re-encode the picked image

The child overlay of CameraPreview

video_player

MediaManager

httpHeaders, captions, playback speed

video_thumbnail, video_compress

No frame extraction or transcoding in the core: every thumbnail call fails, and compressVideo answers the original file with a warning

webview_flutter

BrowserComponent, JavaScript channels through addJSCallback

A POST body, JavaScriptMode.disabled, clearCache

flutter_svg

Image.createSVG where the port renders SVG, otherwise an empty box of the requested size

colorFilter, fit, alignment, placeholderBuilder

file_picker

The native open and save dialogs

audioplayers

MediaManager

flutter_image_compress

Image and ImageIO, JPEG and PNG

HEIC and WebP where the platform can’t encode them

geocoding

The Google Geocoding REST API, keyed by the google.geocoding.key Display property

mixpanel_flutter

Mixpanel’s HTTP ingestion API, with setServerURL for EU residency

flutter_web_auth_2

An in-app browser that watches for the callback URL

emoji_picker_flutter

A Codename One emoji grid with recents and search

Config, except height

app_settings, flutter_timezone

Display.execute with the platform’s settings URL; java.util.TimeZone

android_play_install_referrer

Nothing: installReferrer always fails with UnsupportedError

shared_preferences, path_provider, package_info_plus, device_info_plus, connectivity_plus, geolocator, share_plus, url_launcher, app_links, flutter_local_notifications

Preferences, FileSystemStorage, the build and Display properties, NetworkManager, LocationManager, Display.share, Display.execute (an in-app BrowserComponent for LaunchMode.inAppWebView), LocalNotification with Android channels, raw sounds and a background tap callback

24.9. Writing a stub pack

A package the runtime doesn’t provide can be provided by a stub pack of your own, in the application or in a library jar. A pack has two parts.

The Dart half is a file under META-INF/dart/ on the compile class path — in an application, common/src/main/resources/META-INF/dart/. It declares the package’s API with external members, and names the Java class behind each type with @JavaName. The cn1:covers line tells the import report that the pack stands in for the package:

// cn1:package lottie
// cn1:covers lottie Lottie.asset over a Codename One animation
@JavaName('com.codenameone.developerguide.flutter.Lottie')
class Lottie extends Widget {
  @Unapplied('fit')
  external static Lottie asset(String name, {double? width, double? height,
      bool repeat, BoxFit? fit});
}

Stub types share one namespace. When two packages export the same name — the AppleProvider of firebase_app_check and of firebase_ui_oauth_apple — give each file a // cn1:package <package> line: a library then sees the declaration of the package it imports, and a class of the application’s own with the same name is never shadowed by a stub of a package it doesn’t import.

The Java half is an ordinary class with the members the declarations map to:

public class Lottie extends StatelessWidget {
    private String name;

    public static Lottie asset(String name, Double width, Double height,
            Boolean repeat, Object fit) {
        Lottie l = new Lottie();
        l.name = name;
        return l;
    }

    @Override
    public Widget build(BuildContext context) {
        // Play the animation; a label stands in for it here.
        return new Text(name);
    }
}

The mapping rules:

  • Named parameters become positional Java parameters, in the order they’re declared. A parameter the call leaves out is passed as null.

  • int is Long (or long when it can’t be null), double is Double, bool is Boolean, List and Map are dart.core.DartList and dart.core.DartMap, Future and Stream are dart.async.Future and dart.async.Stream, and a function is a dart.runtime.Funcs interface.

  • A constructor whose parameters are all named is a public no-argument constructor plus one method per parameter, named after it, which the generated code calls for each argument passed.

  • An instance getter is a method with no arguments. A static getter is a public static field.

  • @Unapplied('a, b') on a constructor or method names the parameters that are accepted and not applied, so that the build warns where one is passed.

Every stub on the class path shares one namespace, so a type that another stub already declares mustn’t be declared again. The transpiler ignores the import of the package itself. For a pack outside the application, pass its jar to the import with -Dcn1.flutter.stubPacks=path/to/pack.jar so that the report counts it.

24.10. How the numbers are measured

The benchmark lives in scripts/flutter-bench. It builds the Flutter Gallery both ways on each platform and measures both builds on the same machine, and continuous integration runs it on every change, publishing the numbers to the pull request and to the port status page.

What it reports, per platform:

MetricWhat it means

Installed size

The sum of the artifact’s file lengths, which is what the user’s device gives up. Not du, which rounds every file up to a block.

Executable code

Every compiled binary in the artifact, added together. Counting only the main executable is wrong on iOS, where a Flutter application’s own code isn’t in the executable at all — it’s in the frameworks beside it.

Download size

The artifact compressed, because that’s what a store ships.

Cold start

Wall time from launching the process to the first frame being on the screen, measured from outside so neither runtime is trusted to time itself.

Memory at rest

The platform’s own accounting for a settled, idle application.

Three rules keep the numbers honest, and each exists because the obvious alternative produced a flattering result:

  • Interleaved rounds. One launch of each build, alternating, repeated. A machine that gets busier halfway through then penalizes both builds equally instead of whichever happened to run second, and start-up and memory are judged round by round: the ratio is the median of the per-round ratios.

  • Start-up is a bracket where the two runtimes report different events. On the web, Flutter’s earliest marker fires before its first frame is rasterized while Codename One’s fires once the frame is on the screen, so the benchmark takes Flutter’s figure as a range and computes the ratio from the end least favorable to Codename One.

  • A platform that can’t be measured says so. iOS start-up and memory are reported as not measured rather than taken from a simulator, for the reason given above.

To run it locally against builds you already have:

python3 scripts/flutter-bench/run_bench.py --list

python3 scripts/flutter-bench/run_bench.py --platform macos \
    --cn1-app     /path/to/Bench.app \
    --flutter-app /path/to/gallery.app \
    --json out/macos.json --markdown out/macos.md

--list also reports which platform adapters have been exercised end to end, which isn’t the same question as which ones exist. The charts in Section 24.1, “Smaller, faster and lighter than Flutter” are rendered from the benchmark’s result files by scripts/flutter-bench/render_doc_charts.py.

Data, media and networking

25. File system, storage, network, and parsing

25.1. JAR resources

Resources packaged within the "JAR" don’t belong in this section of the developer guide, but they’re often confused with Storage and FileSystemStorage, so this is a good place to clarify them.

You can place arbitrary files within the src directory of a Codename One project. The file is packaged into the final distribution. In standard Java SE you can do something like:

InputStream i = getClass().getResourceAsStream("/myFile");

This isn’t guaranteed to work on all platforms and will probably fail on some. Instead, use something like:

InputStream i = Display.getInstance().getResourceAsStream(getClass(), "/myFile");

This isn’t the limitation. You can’t use hierarchies, so something like this fails:

InputStream i = Display.getInstance().getResourceAsStream(getClass(), "/res/myFile");

You can’t use relative paths either, so this also fails (notice the missing first slash):

InputStream i = Display.getInstance().getResourceAsStream(getClass(), "myFile");

Those limitations exist for portability. iOS and Android handle resources differently, so supporting the full Java SE semantics is unrealistic.

This is even worse sometimes. Because of the way iOS works with resources, some file names can fail. For example, names with the @ character or more than one . can cause problems (for example, file.ext.act).

Just like in Java SE, the entries within the "JAR" are read and can’t be modified. You can access the stream, but not the actual file.

25.2. Storage

Codename One gives you four places to keep data, and picking the wrong one is the usual source of trouble later:

The four Codename One data stores and what each is for
Figure 230. What each store is for, and what it isn’t

Storage is accessed through the Storage class. It’s a flat, filesystem-like interface that can list, delete, and write named storage entries.

The Storage API also provides convenient methods to write objects to Storage and read them back with readObject and writeObject.

Objects in Storage are deleted when an app is uninstalled, but they’re retained between application updates. A notable exception is Android, which on some devices keeps objects in Storage after uninstalling an app. To force Android to remove them on uninstall, use the build hint android.allowBackup=false.

The sample code below demonstrates listing storage content, adding and viewing entries, and deleting entries:

Toolbar.setGlobalToolbar(true);
Form hi = new Form("Storage", new BoxLayout(BoxLayout.Y_AXIS));
hi.getToolbar().addCommandToRightBar("+", null, e -> {
    TextField tf = new TextField("", "File Name", 20, TextField.ANY);
    TextArea body = new TextArea(5, 20);
    body.setHint("File Body");
    Command ok = new Command("OK");
    Command cancel = new Command("Cancel");
    Command result = Dialog.show("File Name", BorderLayout.north(tf).add(BorderLayout.CENTER, body), ok, cancel);
    if(ok == result) {
        String name = tf.getText();
        boolean isNew = !Arrays.asList(Storage.getInstance().listEntries()).contains(name);
        try(OutputStream os = Storage.getInstance().createOutputStream(name);) {
            os.write(body.getText().getBytes("UTF-8"));
        } catch(IOException err) {
            Log.e(err);
            return;
        }
        // entrySize() is only right once the stream is closed, and an
        // overwrite already has a row whose size label is now stale
        if(isNew) {
            createFileEntry(hi, name);
        } else {
            hi.removeAll();
            for(String file : Storage.getInstance().listEntries()) {
                createFileEntry(hi, file);
            }
        }
        hi.getContentPane().animateLayout(250);
    }
});
for(String file : Storage.getInstance().listEntries()) {
    createFileEntry(hi, file);
}
hi.show();
private void createFileEntry(Form hi, String file) {
   Label fileField = new Label(file);
   Button delete = new Button();
   Button view = new Button();
   FontImage.setMaterialIcon(delete, FontImage.MATERIAL_DELETE);
   FontImage.setMaterialIcon(view, FontImage.MATERIAL_OPEN_IN_NEW);
   Container content = BorderLayout.center(fileField);
   int size = Storage.getInstance().entrySize(file);
   content.add(BorderLayout.EAST, BoxLayout.encloseX(new Label(size + "bytes"), delete, view));
   delete.addActionListener(e -> {
       Storage.getInstance().deleteStorageFile(file);
       content.setY(hi.getWidth());
       hi.getContentPane().animateUnlayoutAndWait(150, 255);
       hi.removeComponent(content);
       hi.getContentPane().animateLayout(150);
   });
   view.addActionListener(e -> {
       try(InputStream is = Storage.getInstance().createInputStream(file);) {
           String s = Util.readToString(is, "UTF-8");
           Dialog.show(file, s, "OK", null);
       } catch(IOException err) {
           Log.e(err);
       }
   });
   hi.add(content);
}
List of files within the storage
Figure 231. List of files within the storage
Content of a file added to the storage
Figure 232. Content of a file added to the storage

25.2.1. The preferences API

Storage also offers a simple API in the form of the Preferences class. The Preferences class lets developers store simple variables, strings, numbers, booleans, and similar values without writing storage code. This is a common use case in applications. For example, you might need to store a server token:

Preferences.set("token", myToken);

You can then read the token like this:

String token = Preferences.get("token", null);

The backing store filename defaults to "codenameone.properties", but you can override it by calling Preferences.setPreferencesLocation(String) before your app touches the API. This is useful when you need separate preference namespaces per user or when you want to plug in an encrypted storage layer.

When you have a batch of updates, prefer the Preferences.set(Map<String,Object>) overload so that all values are persisted with a single disk write.

Preferences can also tell interested code when a key changes. Register a PreferenceListener with addPreferenceListener() to react to updates made in other parts of your code or triggered remotely through Codename One Push. Remember to remove listeners you no longer need to avoid leaks.

This gets somewhat confusing with primitive numbers for example: if you use Preferences.set("primitiveLongValue", myLongNumber) then invoke Preferences.get("primitiveLongValue", 0) you might get an exception!
This would happen because the value is physically a Long object but you’re trying to get an Integer. The workaround is to remain consistent and use code like this Preferences.get("primitiveLongValue", (long)0).

25.3. File system

FileSystemStorage provides file system access. It maps to the underlying OS’s file system API providing most of the common operations expected from a file API somewhat in the vain of java.io.File & java.io.FileInputStream for example: opening, renaming, deleting etc.

Notice that the file system API is somewhat platform specific in its behavior. All paths used the API should be absolute otherwise they aren’t guaranteed to work.

The main reason java.io.File & java.io.FileInputStream weren’t supported directly has a lot to do with the richness of those two APIs. They effectively allow saving a file anywhere, but mobile devices are far more restrictive and don’t allow apps to see/change files that are owned by other apps.

25.3.1. File paths & app home

All paths in FileSystemStorage are absolute, this simplifies the issue of portability since the concept of relativity and current working directory aren’t portable.

All URLs use the / as their path separator you try to enforce this behavior even on Windows.

Directories end with the / character and thus can be distinguished by their name.

The FileSystemStorage API provides a getRoots() call to list the root directories of the file system (you can then "dig in" through the listFiles API). For example, this is confusing and unintuitive for developers.

To simplify the process of creating/reading files Codename One provides the getAppHomePath() method. This method allows you to get the path to a directory where files can be stored/read.

You can use this directory to place an image to share as you did in the share sample.

A common Android hack is to write files to the SDCard storage to share them among apps. Android 4.x disabled the ability to write to arbitrary directories on the SDCard even when the appropriate permission was requested.

25.3.2. Native file chooser

Use Display.openFileChooser() or the shorter CN.openFileChooser() when the user needs to select a general document such as a PDF, text file, private key, or import file. This is different from Display.openGallery(), which is intended for photo and video library media.

The callback source is a String path that can be read with FileSystemStorage.openInputStream(). If the user cancels the picker the event source is null.

CN.openFileChooser(evt -> {
    if(evt == null || evt.getSource() == null) {
        return;
    }
    String path = (String)evt.getSource();
    try(InputStream in = FileSystemStorage.getInstance().openInputStream(path)) {
        String text = Util.readToString(in, "UTF-8");
        // import the selected file
    } catch(IOException err) {
        Log.e(err);
    }
}, "pdf,txt");

The second argument is a comma-separated accept list. It can contain filename extensions such as pdf,txt,p8, MIME types such as application/pdf, or null// for any file. JavaSE uses the native AWT file dialog. Android uses the system document picker and copies content URIs into an app-readable file path when needed. Ports without a native document picker fall back to a Codename One file tree.

No photo-library or media permissions are added by this API. On Android the system document picker grants read access to the selected document. On iOS this API should be implemented with a document picker, not the photo library; ios.NSPhotoLibraryUsageDescription is only needed for openGallery().

25.3.3. Open and save dialogs

openFileChooser() picks one file. Desktop applications usually need more: a Save dialog with a suggested name and a choice of formats, several named filters, extra controls such as an Include charts checkbox, and a live preview while the user browses. Display.showOpenDialog() and Display.showSaveDialog() cover these cases. Each takes a request object from com.codename1.io.filechooser and a callback that runs on the EDT, including when the user cancels.

Display.getInstance().showOpenDialog(new OpenFileRequest()
        .title("Import photos")
        .multiSelect(true)
        .addFilter(new FileTypeFilter("Images")
                .extensions("png", "jpg").mimeTypes("image/*"))
        .addOption(FileDialogOption.checkbox("strip", "Remove location data", true))
        .preview(path -> {
            try (InputStream in = FileSystemStorage.getInstance().openInputStream(path)) {
                return new ScaleImageLabel(Image.createImage(in));
            } catch (IOException err) {
                return new Label("No preview");
            }
        }),
    result -> {
        if (result.isCancelled()) {
            return;
        }
        boolean strip = "true".equals(result.getOptionValue("strip"));
        for (String path : result.getPaths()) {
            // import each file, honouring strip
        }
    });

A save request supplies its content after the user has chosen a location. Pass either a SaveContent writer, which runs off the EDT and can see the chosen format and option values, or sourceFile() to save a copy of an existing file:

Container formatPanel = BoxLayout.encloseY(new Label("JPEG quality"), new Slider());
Display.getInstance().showSaveDialog(new SaveFileRequest()
        .title("Export")
        .suggestedName("Report.pdf")
        .addFilter(new FileTypeFilter("PDF document")
                .extensions("pdf").mimeTypes("application/pdf").utTypes("com.adobe.pdf"))
        .addFilter(new FileTypeFilter("Plain text")
                .extensions("txt").mimeTypes("text/plain"))
        .addOption(FileDialogOption.choice("pages", "Pages", "All", "Current"))
        .accessory(formatPanel)
        .hint(FileDialogRequest.HINT_MAC_SHOWS_TAG_FIELD, true)
        .hint(FileDialogRequest.HINT_WIN_CLIENT_GUID, "6f1c2c7e-9a1b-4c55-8f2a-3e5d1b0a7c11")
        .content((result, out) -> {
            boolean pdf = result.getSelectedFilterIndex() == 0;
            boolean all = "All".equals(result.getOptionValue("pages"));
            // write the report to out as PDF or text
        }),
    result -> {
        if (result.getError() != null) {
            ToastBar.showErrorMessage("Export failed");
        }
    });

Every platform can open and save a single file. Some features apply only where the platform has them, and the other platforms ignore them, so one request works everywhere:

  • Filters (FileTypeFilter) carry extensions, MIME types and Apple type identifiers, and each platform reads the form it understands. Extensions alone work everywhere.

  • Options (FileDialogOption) are declarative checkboxes, choice lists and text fields. Each desktop maps them to its own controls. Where a platform shows none, FileDialogResult.getOptionValue() returns the default value.

  • Accessory components are Codename One components embedded in the dialog. Today only the Codename One fallback save form shows one, so prefer options.

  • Hints (FileDialogRequest.hint() with a FileDialogRequest.HINT_ constant) are platform specific settings, such as the macOS tag field, a Windows client GUID or the folder Android starts in. A platform that doesn’t recognize a hint ignores it.

Call Display.isFileDialogFeatureSupported() with a FileDialogFeatures constant to check a feature at runtime:

if (Display.getInstance().isFileDialogFeatureSupported(FileDialogFeatures.PREVIEW)) {
    // offer the richer import flow
}
Table 11. File dialog features by platform
PlatformOpenSaveFilters, options, accessory and preview

Android

System document picker, several files, folders

Storage Access Framework create document. The content streams straight into the document and needs no storage permission.

One MIME filter. The picker UI is fixed, so it shows no options, accessory or preview.

iOS

Document picker, several files, folders, starting folder

The content goes to a temporary file, which the document picker then exports

Type filter. The picker shows its own preview, and options and accessories aren’t shown.

macOS

NSOpenPanel

NSSavePanel

Format list, options and tag field. No accessory or preview.

Windows

IFileOpenDialog

IFileSaveDialog

Filter list, options as dialog controls and client GUID. No accessory or preview.

Linux

GtkFileChooser

GtkFileChooser with overwrite confirmation

Filter list. Options appear as chooser choices, with text fields in the extra area. No accessory or preview.

Simulator and desktop

The native file dialog, or Swing JFileChooser when the request needs more

Same

Filter list, options and preview. No accessory.

JavaScript

The browser file picker, several files

A download with the suggested name and extension

None

Other ports

A Codename One file tree. With multiSelect(true) each file toggles a check mark and Open returns every checked file.

A Codename One form with a name field, saved into the starting folder or the app home

Filter list, options and accessory on the save form only

A more advanced usage of the FileSystemStorage API can be a FileSystemStorage Tree:

Form hi = new Form("FileSystemTree", new BorderLayout());
TreeModel tm = new TreeModel() {
    @Override
    public Vector getChildren(Object parent) {
        String[] files;
        if(parent == null) {
            files = FileSystemStorage.getInstance().getRoots();
            return new Vector<Object>(Arrays.asList(files));
        } else {
            try {
                files = FileSystemStorage.getInstance().listFiles((String)parent);
            } catch(IOException err) {
                Log.e(err);
                files = null;
            }
            if(files == null) {
                // the directory went away or cannot be read
                files = new String[0];
            }
        }
        String p = (String)parent;
        Vector result = new Vector();
        for(String s : files) {
            result.add(p + FileSystemStorage.getInstance().getFileSystemSeparator() + s);
        }
        return result;
    }

    @Override
    public boolean isLeaf(Object node) {
        return !FileSystemStorage.getInstance().isDirectory((String)node);
    }
};
Tree t = new Tree(tm) {
    @Override
    protected String childToDisplayLabel(Object child) {
        String n = (String)child;
        // the paths above are built with the platform separator, which is
        // a backslash on Windows
        char sep = FileSystemStorage.getInstance().getFileSystemSeparator();
        // roots arrive with a trailing separator
        while(n.length() > 1 && n.charAt(n.length() - 1) == sep) {
            n = n.substring(0, n.length() - 1);
        }
        int pos = n.lastIndexOf(sep);
        if(pos < 0 || pos == n.length() - 1) {
            return n; // a bare root has no basename to show
        }
        return n.substring(pos + 1);
    }
};
hi.add(BorderLayout.CENTER, t);
hi.show();
Simple sample of a tree for the FileSystemStorage API
Figure 233. Simple sample of a tree for the FileSystemStorage API

25.3.4. Storage vs. file system

The question of storage vs. file system is often confusing for novice mobile developers. This embeds two separate questions:

  • Why are there 2 APIs where one would have worked?

  • Which one should you pick?

The main reasons for the 2 APIs are technical. Many OSes provide 2 ways of accessing data specific to the app and this is reflected within the API. For example: on Android the FileSystemStorage maps to APIs such as java.io.FileInputStream whereas the Storage maps to Context.openFileInput().

The secondary reason for the two APIs is conceptual. FileSystemStorage is more powerful and in a sense provides more ways to fail, this is compounded by the complex on-device behavior of the API. Storage is designed to be friendlier to the uninitiated and more portable.

You should pick Storage unless you have a specific need that prevents it. Some APIs such as Capture expect a FileSystemStorage URI so in those cases this would also be a need.

Another case where FileSystemStorage is beneficial is the case of hierarchy or native API usage. If you need a directory structure or need to communicate with a native API the FileSystemStorage approach is easier.

In some OSes the FileSystemStorage API can find the content of the Storage API. As one is implemented on top of the other. This is undocumented behavior that can change at any moment!

To summarize the differences between the 3 file storage options:

Table 12. Compare Storage, FileSystem & Jar Resources
OptionStorageFile SystemJAR Resource

Main Use Case

General application Data

low-level access

Ship data within the app

Initial State

Blank

Blank

As defined by developer

Modifiable

Yes

Yes

No

Supports Hierarchies

No

Yes

No

25.4. SQL

SQLite is a small SQL database designed for embedding into an application. Codename One exposes it through com.codename1.db, an API similar in spirit to JDBC but much smaller, since the abstractions JDBC needs for pluggable drivers make no sense for a local file.

Use it when you have tabular data, need to query it, or have enough of it that loading the lot into memory is unreasonable. For a handful of values Storage is simpler.

Portability of SQLite

The database API behaves the same on every platform Codename One targets: Android, iOS, the native Windows and Linux builds, JavaScript and the simulator. One contract, documented in the com.codename1.db package documentation, and a single test suite that every port has to pass.

This wasn’t always the case, and it’s worth knowing what changed if you have existing code. Cursors used to count rows from zero on some platforms and from one on others; first() reported success on an empty result set on iOS; the simulator couldn’t seek at all; execute() ran only the first statement of a script on some ports without saying so; and blobs couldn’t be read on iOS. Every one of those is now uniform. If your application depended on the old behaviour, see Section 25.4.8, “Compatibility with the previous behaviour”.

Two platforms don’t compile their own SQLite. Android uses the engine in the operating system, so its version follows the OS. Everything else runs a single pinned engine. The file format is stable across SQLite versions regardless, so a database file remains portable either way.

The Database API opens a database by name:

void openDatabase() throws IOException {
    // A plain identifier is the portable form: it creates the file on first
    // use and every platform decides where it lands. Where
    // Database.isCustomPathSupported() answers true a "file://" path works
    // instead; where it does not, a name with a separator in it throws.
    //
    // Its own database, not the propertiesdemo.db the SQLMap walkthrough
    // later in this chapter creates -- SQLMap.createTable will not migrate
    // a Contact table this left behind with fewer columns.
    Database db = Database.openOrCreate("opendemo.db");
    try {
        // A fresh database is empty, so create before reading or writing.
        db.execute("CREATE TABLE IF NOT EXISTS Person ("
                + "id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)");
        db.execute("INSERT INTO Person (name) VALUES (?)", new String[] { "Ada" });
    } finally {
        Util.cleanup(db);
    }
}

Some SQLite apps ship with a "ready made" database. You allow you to replace the DB file by using the code:

String path = Display.getInstance().getDatabasePath("databaseName");

You can then use the FileSystemStorage class to write the content of your DB file into the path. Notice that it must be a valid SQLite file!

In the JavaScript port databases live in a browser storage pool rather than a filesystem, so getDatabasePath() returns the name within that pool and FileSystemStorage can’t open it.
The browser engine changed. Earlier JavaScript builds kept databases in WebSQL, which Chrome removed and Firefox never implemented; the current engine is SQLite compiled to WebAssembly, and it can’t read a WebSQL store. If your application ran on a browser old enough to still have one, openOrCreate refuses to create a database whose name it finds there rather than handing you an empty one, because an application that writes as it goes would overwrite the user’s data with an empty state. Export what the old store holds from a build that still reads it, or set the cn1.db.ignoreLegacyWebSql property to true to continue with a new empty database — nothing removes the old store, so an application that has finished with it needs that property to move on.

This is useful for applications that need to synchronize with a central server or applications that ship with a large database as part of their core product.

Working with a database is pretty trivial, the application logic below can send arbitrary queries to the database and present the results in a Table. You can probably integrate this code into your app as a debugging tool:

Toolbar.setGlobalToolbar(true);
Style s = UIManager.getInstance().getComponentStyle("TitleCommand");
FontImage icon = FontImage.createMaterial(FontImage.MATERIAL_QUERY_BUILDER, s);
Form hi = new Form("SQL Explorer", new BorderLayout());
hi.getToolbar().addCommandToRightBar("", icon, (e) -> {
    TextArea query = new TextArea(3, 80);
    Command ok = new Command("Execute");
    Command cancel = new Command("Cancel");
    if(Dialog.show("Query", query, ok, cancel) == ok) {
        Database db = null;
        Cursor cur = null;
        try {
            db = Display.getInstance().openOrCreate("MyDB.db");
            String sql = query.getText().trim().toLowerCase();
            // Deciding this properly means parsing the statement, which is a
            // long way outside a sample about Database and Cursor. These four
            // prefixes always return rows; a CTE can do either, so it goes to
            // execute() and a WITH that ends in a SELECT will report success
            // without a table.
            boolean returnsRows = sql.startsWith("select") ||
                    sql.startsWith("pragma") || sql.startsWith("explain") ||
                    sql.startsWith("values");
            if(returnsRows) {
                cur = db.executeQuery(query.getText());
                int columns = cur.getColumnCount();
                hi.removeAll();
                if(columns > 0) {
                    boolean next = cur.next();
                    if(next) {
                        ArrayList<String[]> data = new ArrayList<>();
                        String[] columnNames = new String[columns];
                        for(int iter = 0 ; iter < columns ; iter++) {
                            columnNames[iter] = cur.getColumnName(iter);
                        }
                        while(next) {
                            Row currentRow = cur.getRow();
                            String[] currentRowArray = new String[columns];
                            for(int iter = 0 ; iter < columns ; iter++) {
                                currentRowArray[iter] = currentRow.getString(iter);
                            }
                            data.add(currentRowArray);
                            next = cur.next();
                        }
                        Object[][] arr = new Object[data.size()][];
                        data.toArray(arr);
                        hi.add(BorderLayout.CENTER, new Table(new DefaultTableModel(columnNames, arr)));
                    } else {
                        hi.add(BorderLayout.CENTER, "Query returned no results");
                    }
                } else {
                    hi.add(BorderLayout.CENTER, "Query returned no results");
                }
            } else {
                db.execute(query.getText());
                hi.add(BorderLayout.CENTER, "Query completed successfully");
            }
            hi.revalidate();
        } catch(IOException err) {
            Log.e(err);
            hi.removeAll();
            hi.add(BorderLayout.CENTER, "Error: " + err);
            hi.revalidate();
        } finally {
            Util.cleanup(db);
            Util.cleanup(cur);
        }
    }
});
hi.show();
The rows a select returned presented in a Table
Figure 234. The rows a select returned, presented in a Table
Issuing a query
Figure 235. Issuing a query

25.4.1. Encrypting a database

Pass a DatabaseConfig to encrypt a database at rest. Check that the platform can do it first:

if (Database.isEncryptionSupported()) {
    DatabaseConfig config = DatabaseConfig.managed();
    Database db = Database.openOrCreate("secure.db", config);
    config.wipe();
}

There are three ways to key a database.

DatabaseConfig.passphrase(String)

The key is derived from a secret your application supplies, usually one the user typed. Nothing is stored on the device, so losing the passphrase loses the data.

DatabaseConfig.managed()

A random key is generated on first use and kept in the platform key store, the Android Keystore or the iOS keychain. Your application never handles the key. This is the right default when there is nobody to prompt.

DatabaseConfig.rawKey(byte[])

Thirty-two bytes of key material you already have, for instance issued by your server. No key derivation is applied, so the bytes must already be uniformly random.

A passphrase written into your source code isn’t a secret. String literals are recoverable from a shipped .ipa or .apk in minutes, so a constant passphrase buys you nothing against anyone holding the file. If your application can’t ask a human for one, use managed(): a random key in the platform key store beats a constant compiled into the binary.

Encryption protects data at rest, and nothing else. It’s no defense against a rooted or jailbroken device, a debugger attached to the running process, or a memory dump, because the key is in memory for as long as the database is open.

Managed keys aren’t recoverable. Losing the key store entry, through an application uninstall, a device wipe or, on Android, restoring a backup onto a different device, leaves the database permanently unreadable. Android keystore keys can’t be exported; iOS keychain entries do survive an encrypted backup and restore. If the data has to outlive the device, use a passphrase your user or your server holds.

The simulator has no hardware key store, so a managed key there is protected only by a software derived key in your desktop user profile. It’s fine for development, and it’s no evidence that real user data is protected. DatabaseConfig.isKeyHardwareBacked() reports the difference, and the simulator logs a warning the first time you use a managed key.
What encryption costs your build

Nothing is added to an application that doesn’t use it. The build scans your own classes — not the framework’s — and decides from what they reference:

What your code referencesWhat the build adds

nothing in com.codename1.db

Nothing at all. No SQLite engine on the platforms that bundle one, no browser payload.

com.codename1.db, but never DatabaseConfig

The plain SQLite engine where the platform needs one: compiled into the native Windows and Linux binaries, and about 1.5MB of WebAssembly in a JavaScript build. Android and iOS use the engine already in the operating system.

DatabaseConfig

The cipher as well. On Android that’s net.zetetic:sqlcipher-android and androidx.sqlite; on iOS a bundled SQLCipher build that replaces the system libsqlite3.

On Android, encryption raises android.min_sdk_version to 23 and requires android.useAndroidX=true, because that’s SQLCipher’s floor. If your application targets an older API level the build will raise it for you, and devices below API 23 will no longer see your app in the store. This applies as soon as anything in your code mentions DatabaseConfig, so a build hint alone won’t opt out of it — remove the reference if you need the lower floor.
Converting an existing database

An application that already ships a plaintext database can convert it in place:

if (!Database.isEncrypted("myapp.db")) {
    Database.encrypt("myapp.db", DatabaseConfig.managed());
}

Database.decrypt is the reverse, and Database.changeKey re-keys a database that’s already open. An interruption leaves the original file intact, and schema metadata such as PRAGMA user_version survives.

How that’s achieved differs by platform, which matters only if you’re watching the filesystem. Most platforms re-key the file in place. Android can’t: its SQLCipher engine re-keys only between two encrypted states and refuses to convert to or from plaintext, so the port writes the converted database alongside the original and swaps it in once it’s complete. A .cn1migrate file next to your database means a conversion was interrupted partway; the original is still the live one, and the leftover is cleaned up on the next attempt.

The on-disk format

Every platform reads and writes one format, so a database created on a phone can be pulled off the device and opened in the simulator while you are debugging. The parameters are fixed: AES-256 in CBC mode, PBKDF2-HMAC-SHA512 key derivation at 256000 iterations, a 4096 byte page size and per-page HMAC-SHA512. This is the SQLCipher 4 format, so standard tools such as the sqlcipher command line client can open these files too.

25.4.2. Transactions

Transactions are flat, because that’s the only model all the underlying engines can express. A beginTransaction() while one is already open throws, and so does a commitTransaction() or rollbackTransaction() with none open. Both end the transaction and return the connection to autocommit, and closing a database with one open rolls it back.

A commit can fail. SQLite checks a deferred constraint when the transaction commits, not when the offending row is inserted, so that’s where the failure surfaces. When it does, the transaction is over: the port ends it for you and beginTransaction() works again straight away. Don’t roll back afterward, because there’s nothing left to roll back and the call throws. The engines don’t agree here on their own — Android ends the transaction before it reports the failure, while the SQLite C API and JDBC leave it open — so the port reconciles them and your code sees one behaviour.

25.4.3. Schema migrations

The first release of an app creates its tables. Every later release has to cope with whichever of the earlier schemas a device still holds, and a user who skips three updates has to end up with the same tables as one who took each of them. A migration is one change to the schema, written once as a script. Each script runs exactly once per database, in order, so one call brings any database a device holds up to the schema this build expects.

Scripts go in the common module, in a directory of their own:

common/src/main/db/migration/
    V1__create_note.sql
    V2__add_note_created.sql

A file called V<version>__<description>.sql holds one change. Versions are digits separated by dots or underscores and sort as numbers, and a change to the schema is always a new file with a higher version: a script that has shipped is never edited, because devices that ran the old text would no longer match the ones that ran the new text.

-- V2__add_note_created.sql
ALTER TABLE note ADD COLUMN created BIGINT;
UPDATE note SET created = 0 WHERE created IS NULL;

The build compiles the scripts into the app, so they aren’t resources and add no files to it. Run them when the database is opened, before anything else touches it:

Database db = Display.getInstance().openOrCreate("notes.db");
Migrations.migrate(db);

EntityManager.open(name) does this by itself, since it opens the database and nothing else has used it yet:

EntityManager manager = EntityManager.open("notes.db");

Each script runs in a transaction, and is recorded with a checksum in a table called flyway_schema_history. A script that fails is rolled back and the call throws, so a database is never left halfway between two versions. Run the call on the thread that owns the database, and off the event dispatch thread when the scripts move a lot of data.

The naming and the history table are Flyway’s, and the same engine runs the server’s migrations.

When the data is newer than the app

A user can install an older build over data that a newer one already migrated, by restoring a backup or downgrading. The older build can’t know what the newer scripts did to its tables, so the call refuses before changing anything:

Database db = Display.getInstance().openOrCreate("notes.db");
try {
    Migrations.migrate(db);
} catch (MigrationException refused) {
    if (refused.getCode() == MigrationException.FUTURE_SCHEMA) {
        db.close();
        // the data was written by a newer version of the app: ask the user to update
        return null;
    }
    throw refused;
}
An app that already shipped

A database created by a release from before the app had migrations has tables and no history, and is refused for the same reason a server refuses one: V1 would run against a schema it didn’t create. Write the scripts so they add up to the schema the shipped releases created, and tell the first run which version that schema corresponds to:

Migrations.of(db).baselineOnMigrate(true).baselineVersion("3").migrate();

A fresh installation ignores the baseline and runs every script.

Scripts that rebuild a table

SQLite can’t drop a constraint or change a column’s type in place, so those changes rebuild the table. Foreign key enforcement can only be switched inside no transaction at all, so such a script manages its own. Put a file with the same name plus .conf beside it, containing executeInTransaction=false:

-- V7__rebuild_note.sql, with V7__rebuild_note.sql.conf holding executeInTransaction=false
PRAGMA foreign_keys = OFF;
BEGIN;
CREATE TABLE note_new (id INTEGER PRIMARY KEY, body TEXT NOT NULL, created INTEGER NOT NULL DEFAULT 0);
INSERT INTO note_new (id, body, created) SELECT id, body, COALESCE(created, 0) FROM note;
DROP TABLE note;
ALTER TABLE note_new RENAME TO note;
COMMIT;
PRAGMA foreign_keys = ON;

Keep migration SQL to what every device’s SQLite accepts. Use single quotes for strings, and prefer the oldest form of ALTER TABLE that does the job, since the engine on an older phone is older than the one in the simulator.

Without the build step

A project that isn’t built with Maven or Gradle has no step to compile the scripts in. Register them in code instead; everything else works the same way:

MigrationSet set = MigrationSet.builder("default")
        .sql("1", "create note", "CREATE TABLE note (id INTEGER PRIMARY KEY, body TEXT)")
        .sql("2", "add note created", "ALTER TABLE note ADD COLUMN created INTEGER")
        .build();
Migrations.of(db, set).migrate();

25.4.4. Attaching a second database

ATTACH makes another database part of the connection, and SQLite holds it until you detach it or close the connection. Codename One counts an attached database as open, so deleting it, converting it or changing its key is refused while it’s attached, the same as for the database you opened directly. That’s the protection you want: unlinking a file SQLite still has open loses everything written through it.

SQLite lets you attach one file under several schema names at once. The file stays protected until the last of them is detached, so a DETACH of one name doesn’t release a database the connection still holds under another.

Write the filename as a single quoted literal, or bind it as a parameter. SQLite also accepts an expression there — ATTACH '/data/' || name AS aux — but nothing can tell which file that names until the engine evaluates it, which is after the database is already attached and too late to refuse. Those are rejected, and the message says so; build the name in your own code and pass it as a parameter.

Run ATTACH and DETACH through execute(). executeQuery() refuses them, because a cursor runs its statement when it’s stepped — so the attachment would happen after the bookkeeping, and the file could then be deleted while SQLite still holds it.

A path that runs through a symbolic link identifies the same database as the resolved path does. The engine resolves links when it reports what it opened, so Codename One resolves them too before it decides two names are one file — on the platforms where the engine does. Windows is the exception, because SQLite’s Windows layer collapses . and .. as text and steps over a junction rather than through it, so the unresolved name is what identifies the file there.

Name the file with an absolute path from Database.getDatabasePath(). A relative name is resolved by SQLite against the process working directory, which is a different place on every platform and isn’t something a Codename One application controls, while Codename One would look for it in the database directory — so the database protected wouldn’t be the database attached. Those are rejected on every port whose engine has a working directory to resolve against; in the browser, where a name is an entry in a storage pool and means the same thing either way, they’re accepted. If an attachment turns out to name a database that something else is deleting or converting, it’s detached again and the next call on that connection throws to tell you.

25.4.5. Threading

A Database and its cursors aren’t thread safe. Either give each thread its own connection, or wrap one in ThreadSafeDatabase, which routes every call through a single worker thread:

Database threadSafeDb = new ThreadSafeDatabase(Database.openOrCreate("shared.db"));

The wrapper costs a thread handoff per call, so a connection per thread is faster when the threads don’t genuinely need to share one.

25.4.6. Text and column indexes

Text is stored and read back exactly as written, for every character a Java String can hold: accented characters, scripts outside ASCII, emoji, and even the character with code point zero, which SQLite stores in a TEXT value like any other. A string written on one platform reads back identical on every other.

Reading a column the result set doesn’t have — a negative index, or one past the last column — raises an IOException. It’s never reported as a null value, because SQLite’s own C interface answers an out-of-range index with SQL NULL, and passing that on would make a mistyped index impossible to tell apart from stored data.

25.4.7. Cursor performance

Iterating forward with next() costs the same everywhere. Seeking backwards or to an absolute row is cheap on Android, which keeps a window of rows, and costs time proportional to the distance from the start elsewhere, because a SQLite statement only steps forward and seeking back means rewinding and stepping again. Prefer next() for large result sets.

One consequence is worth knowing: because a backward seek re-runs the statement, a cursor is a repeatable read only inside a transaction. Outside one, another thread can write between the two passes, changing what the second pass sees.

There’s a limit on Android that follows from the same mechanism. A statement that changes the database and returns rows — INSERT …​ RETURNING and its relatives — runs once, and Android reads its rows through a window it can only refill by running the statement again. The rows that fit in the first window are therefore readable and the rest aren’t: reaching them would apply the insert a second time. Codename One refuses that rather than doing it, and says so in the error, including that the changes are already applied and the statement must not be retried. If the result set may be large, run the statement with execute() and query for what you need afterward. Every other port steps through such a statement once and has no such limit.

25.4.8. Compatibility with the previous behaviour

This API predates the portable contract, and its behaviour used to differ between platforms. If your application depends on the old behaviour, set the db.legacy build hint, or call Database.setLegacyBehavior(true) before opening any database. It restores each platform’s previous behaviour exactly.

What your project gets by default

An Ant project that uses com.codename1.db is built in compatibility mode automatically. Ant projects predate the portable contract, so a rebuild shouldn’t change how their queries behave unless you ask for it. A Maven project gets the portable contract, which is the documented default everywhere else in this section.

The build server decides this from the project itself, and says so in the build log when it turns compatibility mode on. It only applies when your application actually references com.codename1.db; an Ant project with no database is unaffected.

The build hint always wins, in either direction:

db.legacyAnt projectMaven project

unset

compatibility mode

portable contract

false

portable contract

portable contract

true

compatibility mode

compatibility mode

An Ant project can therefore opt in to the portable contract by setting db.legacy=false, and a Maven project can pin compatibility mode with db.legacy=true. Setting it explicitly is worth doing once you’ve decided, because it makes the choice visible in the project rather than inferred from how it’s built. If you migrate an Ant project to Maven without setting the hint, the default flips, so set it before you migrate if you want the behaviour to stay put.

The hint works in the simulator too, so you can test either mode without a device.

Restored behaviourPlatforms

first() rewinds without landing on a row and always reports success

iOS

getPosition() counts from one

Simulator

wasNull() reports true before any value has been read

Android, iOS

Parameters bind as text rather than by type

iOS

execute(String) runs only the first statement of a script

Android, Simulator

The parameterized methods discard statements after the first, without saying so

all

A nested beginTransaction() is accepted

Android

Malformed SQL surfaces from next() rather than from executeQuery

Android

rollbackTransaction leaves the connection outside autocommit

Simulator

getColumnName reports the table column rather than the result set label

Simulator

executeQuery accepts a transaction control statement such as BEGIN

all

executeQuery accepts ATTACH and DETACH

all

ATTACH accepts an expression for the filename rather than a literal or a parameter

all

ATTACH accepts a relative filename

all but the browser

The flag doesn’t cover defects, nor capabilities that used to throw and now work: last(), prev() and position(int) on iOS and the simulator, reading blobs on iOS, blob query parameters, binding null inside a String[], the existence of a database at all on the native Windows and Linux ports, or seeking backwards through a statement that writes, which used to run that statement a second time and repeat what it wrote. No application can depend on those.

25.4.9. Two settings the contract can’t reach

Everything above is behaviour Codename One implements, so it can be made the same everywhere. Two things are decided when the SQLite engine itself is compiled, and Codename One only compiles one of those engines — Android uses the platform’s, the simulator uses the JDBC driver’s, and iOS uses Apple’s unless the application encrypts:

  • Double-quoted string literals. SELECT "value" isn’t valid SQL — the double quotes make it an identifier — but SQLite has a compatibility mode that turns an unknown identifier into a string, and that mode is fixed when the engine is compiled, with no pragma to change it. The Android and Apple engines accept it; the simulator’s driver rejects it with a message that tells you to use single quotes. Write string literals in single quotes and the question never arises. The engine Codename One bundles for Windows, Linux and encrypted iOS keeps SQLite’s default, so switching encryption on never changes what a statement means.

  • Foreign keys. SQLite ignores declared foreign keys unless asked, and one driver enables them on its own. Codename One puts every port on SQLite’s default so a violation behaves the same in the simulator as on a device; run PRAGMA foreign_keys = ON after opening if you want them enforced, which works everywhere.

Both are easy to settle for yourself: SELECT "value" either returns the string or reports an error, and PRAGMA foreign_keys reports whether they’re on. Codename One’s own port conformance run reports both for every platform it covers.

25.5. Network manager & connection request

One of the more common problems in Network programming is spawning a new thread to handle the network operations. In Codename One this is done seamlessly and becomes unessential thanks to the NetworkManager.

NetworkManager effectively alleviates the need for managing network threads by managing the complexity of network threading. The connection request class can be used to ease web service requests when coupled with the JSON/XML parsing capabilities.

That convenience comes with one rule worth learning before the API: the callbacks that read and write the request run on a network thread, while postResponse, a response listener and an error listener all run on the EDT.

A network request and which thread each of its callbacks runs on
Figure 236. A request through the queue, and the thread each callback arrives on

To open a connection one needs to use a ConnectionRequest object, which has some similarities to the networking mechanism in JavaScript but is obviously somewhat more elaborate.

You can send a get request to a URL using something like:

ConnectionRequest request = new ConnectionRequest(url, false);
request.addResponseListener((e) -> {
    // process the response
});

// request will be handled asynchronously
NetworkManager.getInstance().addToQueue(request);

Notice that you can also implement the same thing and much more by avoiding the response listener code and instead overriding the methods of the ConnectionRequest class which offers many points to override for example:

ConnectionRequest request = new ConnectionRequest(url, false) {
   protected void readResponse(InputStream input) {
        // just read from the response input stream
   }

   protected void postResponse() {
        // invoked on the EDT after processing is complete to allow the networking code
        // to update the UI
   }

   protected void buildRequestBody(OutputStream os) {
        // writes post data, by default this "just works" but if you want to write this
       // manually then override this
   }
};
NetworkManager.getInstance().addToQueue(request);
Notice that overriding buildRequestBody(OutputStream) will work for POST requests and will replace writing the arguments
You don’t need to close the output/input streams passed to the request methods. They’re implicitly cleaned up.

NetworkManager also supports synchronous requests which work in a similar way to Dialog through the invokeAndBlock call and thus don’t block the EDT [8] illegally. For example: you can do something like this:

ConnectionRequest request = new ConnectionRequest(url, false);
// request will be handled synchronously
NetworkManager.getInstance().addToQueueAndWait(request);
byte[] resultOfRequest = request.getResponseData();

Notice that in this case the addToQueueAndWait method returned after the connection completed. Also notice that this was totally legal to do on the EDT!

25.5.1. Timeouts & retries

Each request can override the global timeout using setTimeout(int), which expects a duration in milliseconds. This is useful when you’re talking to endpoints that occasionally need a longer window than the default NetworkManager setting. You can also configure how many times Codename One should retry a failing call by using setSilentRetryCount(int). When the silent retry limit is reached the standard error handling kicks in (for example: listeners fire, fail dialogs show, etc.).

25.5.2. Threading

By default the NetworkManager launches with a single network thread. This is enough for simple applications that don’t do too much networking but if you need to fetch many images concurrently and perform web services in parallel this might be an issue.

Once you increase the thread count there is no guarantee of order for your requests. Requests might not execute in the order with which you added them to the queue!

To update the number of threads use:

NetworkManager.getInstance().updateThreadCount(4);

The callbacks you override on a ConnectionRequest occur on the network thread and not on the EDT!

The callbacks you register are the other way round. postResponse(), designed to update the UI after the networking code completes, is dispatched back to the EDT with callSerially, and so are the listeners added through addResponseListener and NetworkManager.addErrorListener.

Never change the UI from a ConnectionRequest callback. You can either use a listener on the ConnectionRequest, use postResponse() (which is the exception to this rule) or wrap your UI code with callSerially.

25.5.3. VPN detection (best effort)

NetworkManager includes two APIs for querying VPN state:

NetworkManager nm = NetworkManager.getInstance();
if (nm.isVPNDetectionSupported()) {
    boolean vpnActive = nm.isVPNActive();
}
This is a heuristic signal, not a security control.

Both Android and iOS implementations rely on platform networking metadata and interface-name patterns (for example: tun, ppp, utun, ipsec). This means the result can be wrong in either direction:

  • False negatives: Some VPNs may hide or avoid these patterns.

  • False positives: Other virtual/tunnel interfaces may look like VPNs.

Use this API for UX or diagnostics (for example: warnings, telemetry, or logging), not for access control or fraud prevention by itself.

25.5.4. Arguments, headers & methods

HTTP/S is a complex protocol that expects complex encoded data for its requests. Codename One tries to simplify and abstract most of these complexities behind common sense APIs while still providing the full low-level access you would expect from such an API.

Arguments

HTTP supports many "request methods," most commonly GET & POST but also a few others such as HEAD, PUT, DELETE etc.

Arguments in HTTP are passed differently between GET and POST methods. That’s what the setPost method in Codename One determines, whether arguments added to the request should be placed using the GET semantics or the POST semantics.

If you continue your example from above you can do something like this:

ConnectionRequest request = new ConnectionRequest(url, false);
request.addArgument("MyArgName", value);

This will implicitly add a get argument with the content of value. Notice that you don’t care what value is. It’s implicitly HTTP encoded based on the get/post semantics. In this case it will use the get encoding since you passed false to the constructor.

A simpler implementation could do something like this:

ConnectionRequest request = new ConnectionRequest(url +
    "?MyArgName=" + Util.encodeUrl(value), false);

This would be almost identical but doesn’t provide the convenience for switching back and forth between GET/POST and it isn’t as fluent.

You can skip the encoding in complex cases where server code expects illegal HTTP characters (this happens) using the addArgumentNoEncoding method. You can also add many arguments with the same key using addArgumentArray.

Methods

As you explained above, the setPost() method allows you to manipulate the get/post semantics of a request. This implicitly changes the POST or GET method submitted to the server.

For example, if you wish to have finer grained control over the submission process for example: for making a HEAD request you can do this with code like:

ConnectionRequest request = new ConnectionRequest(url, false);
request.setHttpMethod("HEAD");
Headers

When communicating with HTTP servers you often pass data within headers for authentication/authorization but also to convey various properties.

Some headers are built-in as direct APIs for example: content type is directly exposed within the API since it’s a pretty common use case. You can set the content kind of post request using:

ConnectionRequest request = new ConnectionRequest(url, true);
request.setContentType("text/xml");

You can also add any arbitrary header type you want, for example: a common use case is basic authorization where the authorization header includes the Base64 encoded user/password combination as such:

String authCode = user + ":" + password;
String authHeader = "Basic " + Base64.encodeNoNewline(authCode.getBytes());
request.addRequestHeader("Authorization", authHeader);

This can be tedious to do if you want all requests from your app to use this header. For this use case you can use:

String authCode = user + ":" + password;
String authHeader = "Basic " + Base64.encodeNoNewline(authCode.getBytes());
NetworkManager.getInstance().addDefaultHeader("Authorization", authHeader);
Server headers

Server returned headers are a bit trickier to read. You need to subclass the connection request and override the readHeaders method for example:

ConnectionRequest request = new ConnectionRequest(url, false) {
    protected void readHeaders(Object connection) throws IOException {
        String[] headerNames = getHeaderFieldNames(connection);
        for(String headerName : headerNames) {
            String headerValue = getHeader(connection, headerName);
            //....
        }
    }
    protected void readResponse(InputStream input) {
        // just read from the response input stream
    }
};
NetworkManager.getInstance().addToQueue(request);

Here you can extract the headers one by one to handle complex headers such as cookies, authentication etc.

Error handling

As you noticed above practically all the methods in the ConnectionRequest throw IOException. This allows you to avoid the try/catch semantics and let the error propagate up the chain so it can be handled uniformly by the application.

There are two distinct places where you can handle a networking error:

  • The ConnectionRequest - by overriding callback methods

  • The NetworkManager error handler

Notice that the NetworkManager error handler takes precedence thus allowing you to define a global policy for network error handling by consuming errors.

For example: to block all network errors from showing anything to the user you could do something like this:

NetworkManager.getInstance().addErrorListener((e) -> e.consume());
NetworkManager.getInstance().addToQueue(request);

The error listener is invoked first with the NetworkEvent matching the error. Consuming the event prevents it from propagating further down the chain into the ConnectionRequest callbacks.

You can also override the error callbacks of the various types in the request for example: for a server error code you can do:

ConnectionRequest request = new ConnectionRequest(url, false) {
    protected void handleErrorResponseCode(int code, String message) {
        if(code == 444) {
            // do something
            return;
        }
        super.handleErrorResponseCode(code, message);
    }
    protected void readResponse(InputStream input) {
        // just read from the response input stream
    }
};
NetworkManager.getInstance().addToQueue(request);
The error callback is triggered in the network thread!
As a result it can’t access the UI to show a Dialog or anything like that.

Another approach is to use the setFailSilently(true) method on the ConnectionRequest. This will prevent the ConnectionRequest from displaying any errors to the user. It’s a powerful strategy if you use the synchronous version of the APIs for example:

ConnectionRequest request = new ConnectionRequest(url, false);
request.setFailSilently(true);
NetworkManager.getInstance().addToQueueAndWait(request);
if(request.getResponseCode() < 200 || request.getResponseCode() > 299) {
    // probably an error...
}
This code will work with the synchronous "AndWait" version of the method since the response code will take a while to return for the non-wait version.
Error stream

When you get an error code that isn’t 200/300 you ignore the result. This is problematic as the result might contain information you need. For example: many webservices provide further XML/JSON based details describing the reason for the error code.

Calling setReadResponseForErrors(true) will trigger a mode where even errors will receive the readResponse callback with the error stream. This also means that APIs like getData and the listener APIs will also work in case of error.

25.5.5. GZIP

Gzip is a common compression format based on the lz algorithm, it’s used by web servers around the world to compress data.

Codename One supports GZIPInputStream and GZIPOutputStream, which allow you to compress data seamlessly into a stream and extract compressed data from a stream. This is useful and can be applied to every arbitrary stream.

Codename One also features a GZConnectionRequest, which will automatically unzip an HTTP response if it’s indeed gzipped. Notice that some devices (iOS) always request gzip’ed data and always decompress it for you, but for iOS it doesn’t remove the gziped header. The GZConnectionRequest is aware of such behaviors so it’s better to use that when connecting to the network (if applicable).

By default GZConnectionRequest doesn’t request gzipped data ( unzips it when its received) but its pretty easy to do so add the HTTP header Accept-Encoding: gzip for example:

GZConnectionRequest con = new GZConnectionRequest();
con.addRequestHeader("Accept-Encoding", "gzip");

Do the rest as usual and you should have smaller responses from the servers.

25.5.6. File upload

MultipartRequest tries to simplify the process of uploading a file from the local device to a remote server.

You can always submit data in the buildRequestBody but this is flaky and has some limitations in devices/size allowed. HTTP standardized file upload capabilities through the multipart request protocol, this is implemented by countless servers and is well documented. Codename One supports this out of the box:

MultipartRequest request = new MultipartRequest();
request.setUrl(url);
request.addData("myFileName", fullPathToFile, "text/plain");
NetworkManager.getInstance().addToQueue(request);
MultipartRequest is a ConnectionRequest most stuff you expect from there should work. Even addArgument etc.

Since you assume most developers reading this will be familiar with Java here is the way to implement the multipart upload in the servlet API:

This is server-side Java rather than Codename One, so it isn’t one of the compiled examples:

@WebServlet(name = "UploadServlet", urlPatterns = {"/upload"})
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 100,
        maxFileSize = 1024 * 1024 * 150,
        maxRequestSize = 1024 * 1024 * 200)
public class UploadServlet extends HttpServlet {
    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        // By name, matching the addData(...) call above: getParts() also
        // carries any addArgument values and comes off an unordered map,
        // so the first part is not necessarily the file.
        Part data = req.getPart("myFileName");
        try (InputStream in = data.getInputStream()) {
            // Persist the bytes wherever the upload belongs.
        }
    }
}

25.5.7. Parsing

Codename One has many built in parsers for JSON, XML, CSV & Properties formats. You can use those parsers to read data from the Internet or data that’s shipping with your product. For example: use the CSV data to setup default values for your application.

All your parsers are designed with simplicity and small distribution size; they don’t check and will fail in odd ways when faced with broken data. The main logic behind this is that validation takes up CPU time on the device where CPU is a precious resource.

Parsing CSV

CSV is probably the easiest to use, the "Comma Separated Values" format is a list of values separated by commas (or some other character) with new lines to show another row in the table. These map well to an Excel spreadsheet or database table and are supported by default in all spreadsheets.

To parse a CSV use the CSVParser class as such:

Form hi = new Form("CSV Parsing", new BorderLayout());
CSVParser parser = new CSVParser();
try(Reader r = new CharArrayReader("1997,Ford,E350,\"Super, \"\"luxurious\"\" truck\"".toCharArray());) {
String[][] data = parser.parse(r);
String[] columnNames = new String[data[0].length];
for(int iter=  0 ; iter < columnNames.length ; iter++) {
columnNames[iter] = "Col " + (iter + 1);
}
TableModel tm = new DefaultTableModel(columnNames, data);
hi.add(BorderLayout.CENTER, new Table(tm));
} catch(IOException err) {
Log.e(err);
}
hi.show();
CSV parsing results notice the escaped parentheses and comma
Figure 237. CSV parsing results, notice the escaped parentheses and comma

The data contains a two-dimensional array of the CSV content. You can change the delimiter character by using the CSVParser constructor that accepts a character.

Notice that you used CharArrayReader from the com.codename1.io package for this sample. You would want to use java.util.InputStreamReader for real world data.
JSON

The JSON ("JavaScript Object Notation") format is popular on the web for passing values to/from webservices since it works so well with JavaScript. Parsing JSON is as easy but has two different variations. You can use the JSONParser class to build a tree of the JSON data as such:

JSONParser parser = new JSONParser();
Hashtable response = parser.parse(reader);

The response is a Map containing a nested hierarchy of Collection (java.util.List), Strings and numbers to represent the content of the submitted JSON. To extract the data from a specific path iterate the Map keys and recurs into it.

The sample below uses results from an API of ice and fire that queries structured data about the "Song Of Ice & Fire" book series. Here is a sample result returned from the API for the query https://www.anapioficeandfire.com/api/characters?page=5&pageSize=3 :

[
  {
    "url": "http://www.anapioficeandfire.com/api/characters/13",
    "name": "Chayle",
    "culture": "",
    "born": "",
    "died": "In 299 AC, at Winterfell",
    "titles": [
      "Septon"
    ],
    "aliases": [],
    "father": "",
    "mother": "",
    "spouse": "",
    "allegiances": [],
    "books": [
      "http://www.anapioficeandfire.com/api/books/1",
      "http://www.anapioficeandfire.com/api/books/2",
      "http://www.anapioficeandfire.com/api/books/3"
    ],
    "povBooks": [],
    "tvSeries": [],
    "playedBy": []
  },
  {
    "url": "http://www.anapioficeandfire.com/api/characters/14",
    "name": "Gillam",
    "culture": "",
    "born": "",
    "died": "",
    "titles": [
      "Brother"
    ],
    "aliases": [],
    "father": "",
    "mother": "",
    "spouse": "",
    "allegiances": [],
    "books": [
      "http://www.anapioficeandfire.com/api/books/5"
    ],
    "povBooks": [],
    "tvSeries": [],
    "playedBy": []
  },
  {
    "url": "http://www.anapioficeandfire.com/api/characters/15",
    "name": "High Septon",
    "culture": "",
    "born": "",
    "died": "",
    "titles": [
      "High Septon",
      "His High Holiness",
      "Father of the Faithful",
      "Voice of the Seven on Earth"
    ],
    "aliases": [
      "The High Sparrow"
    ],
    "father": "",
    "mother": "",
    "spouse": "",
    "allegiances": [],
    "books": [
      "http://www.anapioficeandfire.com/api/books/5",
      "http://www.anapioficeandfire.com/api/books/8"
    ],
    "povBooks": [],
    "tvSeries": [
      "Season 5"
    ],
    "playedBy": [
      "Jonathan Pryce"
    ]
  }
]

You will place that into a file named "anapioficeandfire.json" in the src directory to make the next sample simpler:

Form hi = new Form("JSON Parsing", new BoxLayout(BoxLayout.Y_AXIS));
JSONParser json = new JSONParser();
try (Reader r = new InputStreamReader(
        Display.getInstance().getResourceAsStream(getClass(), "/anapioficeandfire.json"), "UTF-8")) {
    Map<String, Object> data = json.parseJSON(r);
    java.util.List<Map<String, Object>> content =
            (java.util.List<Map<String, Object>>) data.get("root"); (1)
    for (Map<String, Object> obj : content) { (2)
        String url = (String) obj.get("url");
        String name = (String) obj.get("name");
        java.util.List<String> titles = (java.util.List<String>) obj.get("titles"); (3)
        if (name == null || name.length() == 0) {
            java.util.List<String> aliases = (java.util.List<String>) obj.get("aliases");
            if (aliases != null && aliases.size() > 0) {
                name = aliases.get(0);
            }
        }
        MultiButton mb = new MultiButton(name);
        if (titles != null && titles.size() > 0) {
            mb.setTextLine2(titles.get(0));
        }
        mb.addActionListener((e) -> Display.getInstance().execute(url));
        hi.add(mb);
    }
} catch (IOException err) {
    Log.e(err);
}
hi.show();
1The JSONParser returns a Map which is great if the root object is a Map but sometimes its a list of elements (as is the case above). In this case a special case "root" element is created to contain the actual list of elements.
2This relies on the entries all being maps, which might not be the case for every API type.
3Notice that the "titles" and "aliases" entries are both lists of elements. You use java.util.List to avoid a clash with com.codename1.ui.List.
Parsed JSON result, clicking the elements opens the URL from the JSON
Figure 238. Parsed JSON result, clicking the elements opens the URL from the JSON
The structure of the returned map is sometimes unintuitive when looking at the raw JSON. The easiest thing to do is set a breakpoint on the method and use the inspect variables capability of your IDE to inspect the returned element hierarchy while writing the code to extract that data

An alternative approach is to use the static data parse() method of the JSONParser class and implement a callback parser for example:

JSONParser.parse(reader, callback);

Notice that a static version of the method is used! The callback object is an instance of the JSONParseCallback interface, which includes many methods. These methods are invoked by the parser to show internal parser states, this is like the way traditional XML SAX event parsers work.

Writing JSON — JSONWriter

For typed DTO serialization use the @Mapped annotation framework (see JSON / XML Object Mapping) plus Mappers.toJson(…​). For ad-hoc maps / lists where a build-time Mapper would be overkill, the com.codename1.io.JSONWriter class is the complement of JSONParser:

// One-shot encoding of any Map / List / String / Number / Boolean / null tree
Map<String, Object> tree = new HashMap<>();
tree.put("name", "ada");
tree.put("values", Arrays.asList(1, 2, 3));
String json = JSONWriter.toJson(tree);

// Streaming variants for large outputs (UTF-8)
JSONWriter.toJson(value, writer);
JSONWriter.toJson(value, outputStream);

For tiny request bodies the fluent builders are usually faster to read than a Map literal:

String body = JSONWriter.object()
        .put("email", email)
        .put("password", password)
        .toJson();

String coords = JSONWriter.array()
        .add(JSONWriter.object().put("lat", 37.7749).put("lng", -122.4194))
        .add(JSONWriter.object().put("lat", 51.5074).put("lng",   -0.1278))
        .toJson();

Strings are double-quoted with the standard backslash escapes for ", \, \n, \r, \t, \b, \f, and control chars below 0x20 are emitted as \u00xx. The writer doesn’t pretty-print; if you need indented output, run the result through an external formatter at debug time.

XML parsing

The XMLParser started its life as an HTML parser built for displaying mobile HTML. That usage has since been deprecated but the parser can still parse many HTML pages and is "loose" in verification. This is both good and bad as the parser will work with invalid data without complaining.

The simplest usage of XMLParser looks a bit like this:

XMLParser parser = new XMLParser();
Element elem = parser.parse(reader);

The Element contains children and attributes. It represents a tag within the XML document and even the root document itself. You can iterate over the XML tree to extract the data from within the XML file.

You’ve had a great sample of working with XMLParser in the Tree Section of this guide.

XMLParser has the complimentary XMLWriter class which can generate XML from the Element hierarchy. This allows developers to mutate (change) the elements and save them to a writer stream.

XPath processing

The Result class provides a subset of XPath, but it isn’t limited to XML documents, it can also work with JSON documents, and even with raw Map objects.

Start by demonstrating how to process a response from the Google Reverse Geocoder API. Start with this XML snippet:

<?xml version="1.0" encoding="UTF-8"?>
<GeocodeResponse>
  <status>OK</status>
  <result> <!-- (irrelevant content removed) -->
      <address_component>
          <long_name>London</long_name>
          <short_name>London</short_name>
          <type>locality</type>
          <type>political</type>
      </address_component>
      <!-- (irrelevant content removed) -->
     <address_component>
          <long_name>Ontario</long_name>
          <short_name>ON</short_name>
          <type>administrative_area_level_1</type>
          <type>political</type>
      </address_component>
      <address_component>
         <long_name>Canada</long_name>
         <short_name>CA</short_name>
         <type>country</type>
         <type>political</type>
      </address_component>
  </result>
</GeocodeResponse>

You want to extract some data above into simpler string results. You can do this using:

Result result = Result.fromContent(input, Result.XML);
String country = result.getAsString("/result/address_component[type='country']/long_name");
String region = result.getAsString("/result/address_component[type='administrative_area_level_1']/long_name");
String city = result.getAsString("/result/address_component[type='locality']/long_name");

If you’re at all familiar with processing responses from webservices, you will notice that what would require many lines of code of selecting and testing nodes in regular java can now be done in a single line using the new path expressions.

In the code above, input can be any of:

  • InputStream directly from ConnectionRequest.readResponse(java.io.InputStream).

  • XML or JSON document in the form of a String

  • XML DOM Element returned from XMLParser

  • JSON DOM Map returned from JSONParser

To use the expression processor when calling a webservice, you could use something like the following to parse JSON (notice this is interchangeable between JSON and XML):

Form hi = new Form("Location", new BoxLayout(BoxLayout.Y_AXIS));
hi.add("Pinpointing Location");
Display.getInstance().callSerially(() -> {
    Location l = Display.getInstance().getLocationManager().getCurrentLocationSync();
    if(l == null) {
        hi.add("Location unavailable");
        hi.revalidate();
        return;
    }
    ConnectionRequest request = new ConnectionRequest("https://maps.googleapis.com/maps/api/geocode/json", false) {
        private String country;
        private String region;
        private String city;
        private String json;

        @Override
        protected void readResponse(InputStream input) throws IOException {
                Result result = Result.fromContent(input, Result.JSON);
                country = result.getAsString("/results/address_components[types='country']/long_name");
                region = result.getAsString("/results/address_components[types='administrative_area_level_1']/long_name");
                city = result.getAsString("/results/address_components[types='locality']/long_name");
                json = result.toString();
        }

        @Override
        protected void postResponse() {
            hi.removeAll();
            hi.add(country);
            hi.add(region);
            hi.add(city);
            hi.add(new SpanLabel(json));
            hi.revalidate();
        }
    };
    request.setContentType("application/json");
    request.addRequestHeader("Accept", "application/json");
    request.addArgument("key", googleApiKey);
    request.addArgument("latlng", l.getLatitude() + "," + l.getLongitude());

    NetworkManager.getInstance().addToQueue(request);
});
hi.show();
/* omitted */

The returned JSON looks something like this (notice it’s snipped because the data is too long):

{
  "status": "OK",
  "results": [
    {
      "place_id": "ChIJJ5T9-iFawokRTPGaOginEO4",
      "formatted_address": "280 Broadway, New York, NY 10007, USA",
      "address_components": [
        {
          "short_name": "280",
          "types": ["street_number"],
          "long_name": "280"
        },
        {
          "short_name": "Broadway",
          "types": ["route"],
          "long_name": "Broadway"
        },
        {
          "short_name": "Lower Manhattan",
          "types": [
            "neighborhood",
            "political"
          ],
          "long_name": "Lower Manhattan"
        },
        {
          "short_name": "Manhattan",
          "types": [
            "sublocality_level_1",
            "sublocality",
            "political"
          ],
          "long_name": "Manhattan"
        },
        {
          "short_name": "New York",
          "types": [
            "locality",
            "political"
          ],
          "long_name": "New York"
        },
        {
          "short_name": "New York County",
          "types": [
            "administrative_area_level_2",
            "political"
          ],
          "long_name": "New York County"
        },
        {
          "short_name": "NY",
          "types": [
            "administrative_area_level_1",
            "political"
          ],
          "long_name": "New York"
        },
        {
          "short_name": "US",
          "types": [
            "country",
            "political"
          ],
          "long_name": "United States"
        },
        {
          "short_name": "10007",
          "types": ["postal_code"],
          "long_name": "10007"
        },
        {
          "short_name": "1868",
          "types": ["postal_code_suffix"],
          "long_name": "1868"
        }
      ],
      "types": ["street_address"],
      "geometry": {
        "viewport": {
          "northeast": {
            "lng": -74.0044642197085,
            "lat": 40.7156470802915
          },
          "southwest": {
            "lng": -74.0071621802915,
            "lat": 40.7129491197085
          }
        },
        "location_type": "ROOFTOP",
        "location": {
          "lng": -74.00581319999999,
          "lat": 40.7142981
        }
      }
    }
    /* SNIPED the rest */
  ]
}
Running the geocode sample above in the simulator
Figure 239. Running the geocode sample above in the simulator

The XML processor handles global selections by using a double slash anywhere within the expression, for example:

// get all address_component names anywhere in the document with a type "political"
String array[] = result.getAsStringArray("//address_component[type='political']/long_name");

// get all types anywhere under the second result (dimension is 0-based)
String[] types = result.getAsStringArray("/result[1]//type");
Notice that Google’s JSON webservice uses plural form for each of the node names in that API (ie. results, address_components, and types) where they don’t in the XML services (that’s result, address_component etc.)
Second example

It’s also possible to do some more complex expressions. You’ll use the following XML fragment for the next batch of examples:

<rankings type="aus" gender="male" date="2011-12-31">
    <player id="1036" coretennisid="6752" rank="1"
       delta="0" singlespoints="485000" doublespoints="675"
       deductedpoints="0" totalpoints="485675">
        <firstname>Bernard</firstname>
        <lastname>Tomic</lastname>
        <town>SOUTHPORT</town>
        <state>QLD</state>
        <dob>1992-10-21</dob>
    </player>
    <player id="2585" coretennisid="1500" rank="2"
       delta="0" singlespoints="313500" doublespoints="12630"
       deductedpoints="0" totalpoints="326130">
        <firstname>Mathew</firstname>
        <lastname>Ebden</lastname>
        <town>CHURCHLANDS</town>
        <state>WA</state>
        <dob>1987-11-26</dob>
    </player>
    <player id="6457" coretennisid="287" rank="3"
        delta="0" singlespoints="132500" doublespoints="1500"
        deductedpoints="0" totalpoints="134000">
       <firstname>Lleyton</firstname>
       <lastname>Hewitt</lastname>
       <town>EXETER</town>
       <state>SA</state>
       <dob>1981-02-24</dob>
    </player>
    <!-- ... etc ... -->
</rankings>

Above, if you want to select the IDs of all players that are ranked in the top 2, you can use an expression like:

int top2[] = result.getAsIntegerArray("//player[@rank < 3]/@id");
Notice above that the expression is using an attribute for selecting both rank and id. In JSON documents, if you try to select an attribute, it will look for a child node under the attribute name you ask for.

If a document is ordered, you might want to select nodes by their position, for example:

String first2[] = result.getAsStringArray("//player[position() < 2]/firstname");

String secondLast = result.getAsString("//player[last() - 1]/firstname");

It’s also possible to select parent nodes, by using the .. expression. For example:

int id = result.getAsInteger("//lastname[text()='Hewitt']/../@id");

Above, you globally find a lastname element with a value of ‘Hewitt’, then grab the parent node of lastname which happens to be the player node, then grab the ID attribute from the player node. Or, you could get the same result from the following simpler statement:

int id = result.getAsInteger("//player[lastname='Hewitt']/@id");

A predicate can’t hold another predicate. An expression such as //player[//address[country/isocode='CA']]/@id is rejected with Syntax error: unclosed predicate, because the outer predicate is split at its comparator before it’s tokenized and that cuts the inner one in half. Select the inner nodes first and match on what comes back.

To select a node based on the existence of an attribute:

int id[] = result.getAsIntegerArray("//player[@rank]/@id");

Above, you selected the IDs of all ranked players. Conversely, you can select the non-ranked players like this:

int id[] = result.getAsIntegerArray("//player[@rank=null]/@id");
Logical not (!) operators aren’t implemented.

There’s no matching test for a child node. A predicate that names one with no comparison in it — //player[middlename] — is rejected with Could not create a comparator, so test for a child by comparing it to something, or select the child and work from what comes back.

Keep in mind that the Codename One path expression language isn’t a full implementation of XPath 1.0, but does already handle many of the most useful features of the specification.

Properties files

Properties files are standard key/value pairs encoded into a text file. This file format is familiar to Java developers and the Codename One specific version tries to be as close as possible to the original Java implementation.

Notice that properties file both in Java proper and in Codename One don’t support non-ascii characters. To encode Unicode values into the properties file format you should use the native2ascii tool that ships with the JDK.

One major difference between standard Java properties and the ones in Codename One is that Codename One sorts properties alphabetically when saving. Java uses random order based on the Hashtable natural ordering.

This was done to provide consistency for saved files.

25.6. Debugging network connections

Debugging Network Connections
Figure 240. Debugging Network Connections

Codename One includes a Network Monitor tool which you can access through the simulator menu option. This tool reflects all the requests made through the connection requests and displays them in the left pane. This allows you to track issues in your code/web service and see everything the is "going through the wire."

This is a useful tool for optimizing and for figuring out what’s happening with your server connection logic.

25.6.1. Simpler downloads

A common task is file download to storage or filesystem.

The Util class has simple utility methods:

downloadUrlToFileSystemInBackground, downloadUrlToStorageInBackground, downloadUrlToFile & downloadUrlToStorage.

These all delegate to a feature in ConnectionRequest:

ConnectionRequest.setDestinationStorage(fileName) & ConnectionRequest.setDestinationFile(fileName);

Both of which simplify the whole process of downloading a file.

Downloading images

Codename One has many ways to download an image and the general recommendation is the URLImage. For example, the URLImage assumes that you know the size of the image in advance or that you’re willing to resize it. In that regard it works great for some use cases but not so much for others.

The download methods mentioned above are great alternatives but they’re a bit verbose when working with images and don’t provide fine grained control over the ConnectionRequest for example: making a POST request to get an image.

Adding global headers is another use case but you can use addDefaultHeader to add those.

To make this process simpler there is a set of helper methods in ConnectionRequest that downloads images directly.

These methods complement the Util methods but go a bit further and feature terse syntax for example: you can download a ConnectionRequest to Storage using code like this:

request.setUrl(url);
request.downloadImageToStorage("cached-image", (img) -> theImageIsHereDoSomethingWithIt(img));

This effectively maps the ConnectionRequest directly to a SuccessCallback for further processing.

URLImage caching

URLImage is great. It changed the way you do some things in Codename One.

For example, when it was introduced there was no support for the cache filesystem or for the JavaScript port. The cache filesystem is probably the best place for images of URLImage so supporting that as a target is an obvious choice, but JavaScript seems to work so why would it need a special case?

JavaScript already knows how to download and cache images from the web. URLImage is actually a step back from the things a good browser can do so why not use the native abilities of the browser when you’re running there and fallback to using the cache filesystem if it’s available and as a last resort go to storage…​

That’s what the new method of URLImage does:

public static Image createCachedImage(String imageName, String url,
                                      Image placeholder, int resizeRule);

A few important things you need to notice about this method:

  • It returns Image and not URLImage. This is crucial. Down casting to `URLImage* will work on the simulator but might fail in some platforms (for example: JavaScript) so don’t do that!
    Since this is implemented natively in JavaScript you need a different abstraction for that platform.

  • It doesn’t support image adapters and instead uses a simplified resize rule. Image adapters work on URLImage since you have a lot of control in that class. For example, in the browser your control is limited and so an adapter won’t work.

If you do use this approach it would be far more efficient when running in the JavaScript port and will make better use of caching in most OSes.

25.7. Rest API

The Rest API makes it easy to invoke a RESTful webservice without many of the nuances of ConnectionRequest. You can use it to define the HTTP method and start building based on that. To get a parsed JSON result from a URL you could do:

Map<String, Object> jsonData = Rest.get(myUrl).getAsJsonMap().getResponseData();

For a lot of REST requests this will fail because you need to add an HTTP header indicating that you accept JSON results. You have a special case support for that:

Map<String, Object> jsonData = Rest.get(myUrl).acceptJson().getAsJsonMap().getResponseData();

POST requests use the same builder pattern:

Map<String, Object> jsonData = Rest.post(myUrl).body(bodyValueAsString).getAsJsonMap().getResponseData();

Notice the usage of post and the body builder method. MANY methods exist in the builder class that cover pretty much everything you would expect and then some when it comes to the needs of rest services.

Some highlights that are easy to miss:

  • .priority(byte) lets you change the underlying ConnectionRequest priority when you need certain calls to jump the queue.

  • .cookiesEnabled(boolean) controls whether cookies are persisted for the request when you need stateless behavior.

  • .useBoolean(boolean) and .useLongs(boolean) toggle how the JSON parser materializes number and boolean types inside the resulting Map, which is handy when your back end is strict about data types.

  • .cacheMode(…​) and .postParameters(…​) expose the same knobs as ConnectionRequest, keeping you in the fluent API even for advanced tweaks.

25.7.1. Top-level JSON arrays — fetchAsJsonList

When the endpoint returns a top-level JSON array (for example [{...}, {...}]), use fetchAsJsonList rather than fetchAsJsonMap. The underlying JSONParser wraps top-level arrays under a synthetic "root" key; fetchAsJsonList unwraps that envelope for you so the callback receives the array directly:

Rest.get("https://api.example.com/items")
    .header("Authorization", "Bearer " + token)
    .acceptJson()
    .fetchAsJsonList(response -> {
        List items = response.getResponseData();
        renderItems(items);
    });

There is no separate builder for the ambiguous "object or array" case: when the response shape isn’t known up-front, use fetchAsJsonMap and branch on data.get("root") instanceof List.

25.7.2. Typed responses — fetchAsMapped and fetchAsMappedList

Rest.fetchAsJsonMap returns a generic Map<String, Object> that the caller casts and inspects key by key. Once your DTOs are @Mapped-annotated (see JSON / XML Object Mapping), fetchAsMapped returns the typed object directly:

// Model
@Mapped
public class Pet {
    @JsonProperty("id")        public long id;
    @JsonProperty("name")      public String name;
    @JsonProperty("photoUrls") public List<String> photoUrls;
}
// Call site
Rest.get(baseUrl + "/pet/" + petId)
    .header("Authorization", "Bearer " + token)
    .acceptJson()
    .fetchAsMapped(Pet.class, response -> {
        Pet pet = response.getResponseData();    // already typed -- no Map casts
        renderPet(pet);
    });

For endpoints that return a list of DTOs, use fetchAsMappedList:

Rest.get(baseUrl + "/albums")
    .header("Authorization", "Bearer " + token)
    .acceptJson()
    .fetchAsMappedList(Album.class, response -> {
        List<Album> albums = response.getResponseData();
        renderAlbums(albums);
    });

Both builders fall back to the untyped fetchAsJsonMap / fetchAsJsonList path internally and then route every map element through the build-time mapper that the @Mapped annotation processor generated. If a mapper isn’t registered for the requested class (typical cause: the process-annotations Mojo didn’t run on the class, or the class isn’t @Mapped-annotated), the callback completes with null data — so always inspect response.getResponseCode() rather than response.getResponseData() to differentiate a server error response from the missing-mapper case.

The code in the kitchen sink webservice sample was updated to use this API. The result is shorter and more readable without sacrificing anything.

25.7.3. Rest in practice - twilio

The best way to explain the usage of this API is through a concrete "real world" example. Twilio provides many great telephony-oriented webservices to developers. One of those is an SMS sending webservice which can be useful for things such as "device activation."

To get started you would need to sign up to Twilio and have the following 3 variable values:

String accountSID = "----------------";
String authToken = "---------------";
String fromPhone = "your Twilio phone number here";
You can open a trial Twilio account and it tags all your SMS’s. Notice you would need to use a You based number if you don’t want to pay

You can now send hello world as an SMS to the end user. Once this is in place sending an SMS through REST is a matter of using the Rest API:

Response<Map> result = Rest.post("https://api.twilio.com/2010-04-01/Accounts/" + accountSID + "/Messages.json").
        queryParam("To", destinationPhone).
        queryParam("From", fromPhone).
        queryParam("Body", "Hello World").
        basicAuth(accountSID, authToken).
        getAsJsonMap();

Notice that this is equivalent of this "curl" command:

curl 'https://api.twilio.com/2010-04-01/Accounts/[accountSID]/Messages.json' -X POST \
--data-urlencode 'To=[destinationPhone]' \
--data-urlencode 'From=[fromPhone]' \
--data-urlencode 'Body=Hello World' \
-u [accountSID]:[AuthToken]

That’s pretty cool as the curl command maps almost directly to the Rest API call!

What you do here is actually pretty trivial, you open a connection the api messages URL. You add arguments to the body of the post request and define the basic authentication data.

The result is in JSON form you ignore it since it isn’t that important but it might be useful for error handling. This is a sample response (redacted keys):

{
    "sid": "[sid value]",
    "date_created": "Sat, 09 Sep 2017 19:47:30 +0000",
    "date_updated": "Sat, 09 Sep 2017 19:47:30 +0000",
    "date_sent": null,
    "account_sid": "[sid value]",
    "to": "[to phone number]",
    "from": "[from phone number]",
    "messaging_service_sid": null,
    "body": "Sent from your Twilio trial account - Hello World",
    "status": "queued",
    "num_segments": "1",
    "num_media": "0",
    "direction": "outbound-api",
    "api_version": "2010-04-01",
    "price": null,
    "price_unit": "USD",
    "error_code": null,
    "error_message": null,
    "uri": "/2010-04-01/Accounts/[sid value]/Messages/SMe802d86b9f2246989c7c66e74b2d84ef.json",
    "subresource_uris": {
        "media": "/2010-04-01/Accounts/[sid value]/Messages/[message value]/Media.json"
    }
}

Notice the error message entry which is null meaning there was no error, if there was an error you’d have a message there or an error code that isn’t in the 200-210 range.

This should display an error message to the user if there was a problem sending the SMS:

if(result.getResponseCode() < 200 || result.getResponseCode() > 299) {
    String error = null;
    if(result.getResponseData() != null) {
        error = (String)result.getResponseData().get("error_message");
    }
    if(error == null) {
        error = "Error sending SMS: " + result.getResponseCode();
    }
    ToastBar.showErrorMessage(error);
}

25.8. Webservice wizard

The right-click option this was driven from belonged to the IDE plugin and is gone. The generator itself survives in one place: Ant projects created from the old template still have a webservice-wizard target, which runs com.codename1.ws.wizard.WSWizard out of CodeNameOneBuildClient.jar. A Maven project has no equivalent. com.codename1.io.WebServiceProxyCall is still in the framework either way, so an app with generated proxies keeps working. For new work use Section 25.7, “Rest API”, which needs no code generation and speaks a format every server already talks.

The protocol it implements is a compact binary one. Method arguments were restricted to a small set of types, extended through object externalization, and every generated method came in two forms: one that blocks and throws IOException, and one that takes a callback and reports through it.

25.9. Connection request caching

Caching server data locally is a huge part of the advantage a native app has over a web app. This is non-trivial as it requires a delicate balance if you want to test the server resource for changes.

HTTP provides two ways to do that the ETag and Last-Modified. While both are great they’re non-trivial to use and by no definition seamless.

Connection request has an experimental feature that allows you to set the caching mode to one of 4 states either globally or per connection request:

  • OFF is the default meaning no caching.

  • SMART means all get requests are cached intelligently and caching is "mostly" seamless

  • MANUAL means that the developer handles the actual caching but the system won’t do a request on a resource that’s already "fresh"

  • OFFLINE will fetch data from the cache and won’t try to go to the server. It will generate a 404 error if data isn’t available

You can toggle these in the specific request by using setCacheMode(CachingMode) and set the global default using setDefaultCacheMode(CachingMode).

Caching applies to GET operations, it won’t work for POST or other methods

There are many methods of interest to keep an eye for:

protected InputStream getCachedData() throws IOException;
protected void cacheUnmodified() throws IOException;
public void purgeCache();
public static void purgeCacheDirectory() throws IOException;

25.9.1. getCachedData()

This returns the cached data. This is invoked to implement readResponse(InputStream) when running offline or when you detect that the local cache isn’t stale.

The smart mode implements this and will fetch the right data. For example, the manual mode doesn’t store the data and relies on you to do so. In that case you need to return the data you stored at this point and must implement this method for manual mode.

25.9.2. Cacheunmodified()

This is a callback that’s invoked to show a cache hit, meaning that you already have the data.

The default implementation still tries to call all the pieces for compatibility (for example: readResponse). For example, if this is unnecessary you can override that method with a custom implementation or even a blank implementation to block such a case.

25.9.3. Purgecache & purgeCacheDirectory

These methods are pretty self-explanatory. Notice one caveat though…​

When you download a file or a storage element you don’t cache them and rely on the file/storage element to be present and serve as "cache." When purging you won’t delete a file or storage element you downloaded and thus these might remain.

For example, you do remove the ETag and Last-Modified data so the files might get refreshed the next time around.

25.10. Cached data service

The CachedDataService allows caching data and updating it if the data changed on the server. The download APIs won’t check for update if there is a local cache of the data (for example: URLImage always uses the local copy). This isn’t a bad thing, it’s pretty efficient.

For example, it might be important to update the image if it changed but you still want caching.

The CachedDataService will fetch data if it isn’t cached locally and cache it. When you "refresh" it will send a special HTTP request that will send back the data if it has been updated since the last refresh:

CachedDataService.register();
CachedData d = (CachedData)Storage.getInstance().readObject("LocallyCachedData");

if(d == null) {
  d = new CachedData();
  d.setUrl("https://....");
}
final CachedData data = d;
// check if there is a new version of this on the server
CachedDataService.updateData(data, new ActionListener() {
    public void actionPerformed(ActionEvent ev) {
        // the fresh copy arrives on the event, updateData leaves ours alone
        CachedData fresh = (CachedData)((NetworkEvent)ev).getMetaData();
        // the service fills in the bytes and validators but not the URL
        fresh.setUrl(data.getUrl());
        Storage.getInstance().writeObject("LocallyCachedData", fresh);
    }
});

25.11. Externalizable objects

Codename One provides the Externalizable interface, which is like the Java SE Externalizable interface. This interface allows an object to declare itself as Externalizable for serialization (so an object can be stored in a file/storage or sent over the network). For example, due to the lack of reflection and use of obfuscation these objects must be registered with the Util class.

Codename One doesn’t support the Java SE Serialization API due to the size issues and complexities related to obfuscation.

The major objects that are supported by default in the Codename One Externalizable are: String, Collection, Map, ArrayList, HashMap, Vector, Hashtable, Integer, Double, Float, Byte, Short, Long, Character, Boolean, Object[], byte[], int[], float[], long[], double[].

Externalizing an object such as h below should work fine:

Map<String, Object> h = new HashMap<>();
h.put("Hi","World");
h.put("data", new byte[] {(byte)1});
Storage.getInstance().writeObject("Test", h);

For example, notice that some things aren’t polymorphic for example: if you will externalize a String[] you will get back an Object[] since String arrays aren’t detected by the implementation.

The externalization process caches objects so the app will seem to work and fail on restart!

Implementing the Externalizable interface is important when you want to store a proprietary object. In this case you must register the object with the com.codename1.io.Util class so the externalization algorithm will be able to recognize it by name by invoking:

Util.register("MyClass", MyClass.class);
You should do this early on in the app for example: in the init(Object) but you shouldn’t do it in a static initializer within the object as that might never be invoked!

An Externalizable object must have a default public constructor and must implement the following 4 methods:

public int getVersion();
public void externalize(DataOutputStream out) throws IOException;
public void internalize(int version, DataInputStream in) throws IOException;
public String getObjectId();

The getVersion() method returns the current version of the object allowing the stored data to change its structure in the future (the version is then passed when internalizing the object). The object ID is a String uniquely representing the object; it corresponds to the class name (in the example above the Unique Name should be MyClass).

It’s a common mistake to use getClass().getName() to implement getObjectId() and it would seem to work in the simulator. This isn’t the case though!
Since devices obfuscate the class names this becomes a problem as data is stored in a random name that changes with every release.

Developers need to write the data of the object in the externalize method using the methods in the data output stream and read the data of the object in the internalize method for example:

public void externalize(DataOutputStream out) throws IOException {
    out.writeUTF(name);
    if(value != null) {
        out.writeBoolean(true);
        out.writeUTF(value);
    } else {
        out.writeBoolean(false);
    }
    if(domain != null) {
        out.writeBoolean(true);
        out.writeUTF(domain);
    } else {
        out.writeBoolean(false);
    }
    out.writeLong(expires);
}

public void internalize(int version, DataInputStream in) throws IOException {
    name = in.readUTF();
    if(in.readBoolean()) {
        value = in.readUTF();
    }
    if(in.readBoolean()) {
        domain = in.readUTF();
    }
    expires = in.readLong();
}

Since strings might be null sometimes you also included convenience methods to implement such externalization. This effectively writes a boolean before writing the UTF to show whether the string is null:

public void externalize(DataOutputStream out) throws IOException {
    Util.writeUTF(name, out);
    Util.writeUTF(value, out);
    Util.writeUTF(domain, out);
    out.writeLong(expires);
}

public void internalize(int version, DataInputStream in) throws IOException {
    name = Util.readUTF(in);
    value = Util.readUTF(in);
    domain = Util.readUTF(in);
    expires = in.readLong();
}

Assuming you added a new date field to the object you can do the following. Notice that a Date is a long value in Java that can be null. For completeness the full class is presented below:

public class MyClass implements Externalizable {
    private static final int VERSION = 2;
    private String name;
    private String value;
    private String domain;
    private Date date;
    private long expires;

    public MyClass() {}

    public int getVersion() {
        return VERSION;
    }

    public String getObjectId() {
        return "MyClass";
    }

    public void externalize(DataOutputStream out) throws IOException {
        Util.writeUTF(name, out);
        Util.writeUTF(value, out);
        Util.writeUTF(domain, out);
        if(date != null) {
            out.writeBoolean(true);
            out.writeLong(date.getTime());
        } else {
            out.writeBoolean(false);
        }
        out.writeLong(expires);
    }

    public void internalize(int version, DataInputStream in) throws IOException {
        name = Util.readUTF(in);
        value = Util.readUTF(in);
        domain = Util.readUTF(in);
        if(version > 1) {
            boolean hasDate = in.readBoolean();
            if(hasDate) {
                date = new Date(in.readLong());
            }
        }
        expires = in.readLong();
    }
}

Notice that you need to check for compatibility during the reading process as the writing process always writes the latest version of the data.

25.12. UI bindings & utilities

Codename One provides many tools to simplify the path between networking/IO & GUI. A common task of showing a wait dialog or progress sign while fetching network data can be simplified by using the InfiniteProgress class for example:

InfiniteProgress ip = new InfiniteProgress();
Dialog dlg = ip.showInifiniteBlocking();
request.setDisposeOnCompletion(dlg);

The process of showing a progress bar for a long IO operation such as downloading is automatically mapped to the IO stream in Codename One using the SliderBridge class.

You can simulate network delays and disconnected network in the Simulator menu

The SliderBridge class can bind a ConnectionRequest to a Slider and effectively show the progress of the download. For example:

Form hi = new Form("Download Progress", new BorderLayout());
Slider progress = new Slider();
Button download = new Button("Download");
download.addActionListener((e) -> {
    ConnectionRequest cr = new ConnectionRequest("https://www.codenameone.com/img/blog/new_icon.png", false);
    SliderBridge.bindProgress(cr, progress);
    NetworkManager.getInstance().addToQueueAndWait(cr);
    if(cr.getResponseCode() == 200) {
        hi.add(BorderLayout.CENTER, new ScaleImageLabel(EncodedImage.create(cr.getResponseData())));
        hi.revalidate();
    }
});
hi.add(BorderLayout.SOUTH, progress).add(BorderLayout.NORTH, download);
hi.show();
SliderBridge progress for downloading the image in the slow network mode
Figure 241. SliderBridge progress for downloading the image in the slow network mode

25.13. Logging & crash protection

Codename One includes a Log API that allows developers to invoke Log.p(String) or Log.e(Throwable) to log information to storage.

As part of the premium cloud features it’s possible to invoke Log.sendLog() to email a log directly to the developer account. Codename One can do that seamlessly based on changes printed into the log or based on exceptions that are uncaught or logged for example:

Log.setReportingLevel(Log.REPORTING_DEBUG);
DefaultCrashReporter.init(true, 2);

This code will send a log every 2 minutes to your email if anything was changed. You can place it within the init(Object) method of your application.

For a production application you can use Log.REPORTING_PRODUCTION which will email the log on exception.

25.14. Sockets

At this moment Codename One supports TCP sockets. Server socket (listen/accept) is available on Android and the simulator but not on iOS.

You can check if Sockets are supported using the Socket.isSupported(). You can test for server socket support using Socket.isServerSocketSupported().

To use sockets you can use the Socket.connect(String host, int port, SocketConnection eventCallback) method.

To listen on sockets you can use the Socket.listen(int port, Class scClass) method which will instantiate a SocketConnection instance (scClass is expected to be a subclass of SocketConnection) for every incoming connection.

This simple example allows you to create a server and a client assuming the device supports both:

public class MyApplication {
    private Form current;

    public void init(Object context) {
        try {
            Resources theme = Resources.openLayered("/theme");
            UIManager.getInstance().setThemeProps(theme.getTheme(theme.getThemeResourceNames()[0]));
        } catch(IOException e){
            e.printStackTrace();
        }
    }

    public void start() {
        if(current != null){
            current.show();
            return;
        }
        final Form soc = new Form("Socket Test");
        Button btn = new Button("Create Server");
        Button connect = new Button("Connect");
        final TextField host = new TextField("127.0.0.1");
        // the handle is the only way to close the listening socket, so a second
        // tap would otherwise leave the first accept thread running for good
        Socket.StopListening[] listening = new Socket.StopListening[1];
        btn.addActionListener((evt) -> {
            if(listening[0] != null) {
                listening[0].stop();
            }
            soc.addComponent(new Label("Listening: " + Socket.getHostOrIP()));
            soc.revalidate();
            listening[0] = Socket.listen(5557, SocketListenerCallback.class);
        });
        connect.addActionListener((evt) -> {
            Socket.connect(host.getText(), 5557, new SocketConnection() {
                @Override
                public void connectionError(int errorCode, String message) {
                    System.out.println("Error");
                }

                @Override
                public void connectionEstablished(InputStream is, OutputStream os) {
                    try {
                        int counter = 1;
                        while(isConnected()) {
                            os.write(("Hi: " + counter).getBytes());
                            counter++;
                            Thread.sleep(2000);
                        }
                    } catch(Exception err) {
                        err.printStackTrace();
                    }
                }
            });
        });
        soc.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
        soc.addComponent(btn);
        soc.addComponent(connect);
        soc.addComponent(host);
        soc.show();
    }

    public static class SocketListenerCallback extends SocketConnection {
        private Label connectionLabel;

        @Override
        public void connectionError(int errorCode, String message) {
            System.out.println("Error");
        }

        private void updateLabel(final String t) {
            Display.getInstance().callSerially(new Runnable() {
                public void run() {
                    if(connectionLabel == null) {
                        connectionLabel = new Label(t);
                        Display.getInstance().getCurrent().addComponent(connectionLabel);
                    } else {
                        connectionLabel.setText(t);
                    }
                    Display.getInstance().getCurrent().revalidate();
                }
            });
        }

        @Override
        public void connectionEstablished(InputStream is, OutputStream os) {
            try {
                byte[] buffer = new byte[8192];
                while(isConnected()) {
                    int size = is.read(buffer, 0, 8192);
                    if(size == -1) {
                        return;
                    }
                    if(size > 0) {
                        updateLabel(new String(buffer, 0, size));
                    }
                }
            } catch(Exception err) {
                err.printStackTrace();
            }
        }
    }

    public void stop() {
        current = Display.getInstance().getCurrent();
    }

    public void destroy() {
    }
}

25.15. Properties

In standard Java you have a POJO (Plain Old Java Object) which has getters/setters for example: you can have a simple Meeting class like this:

public class Meeting {
     private Date when;
     private String subject;
     private int attendance;

     public Date getWhen() {
        return when;
    }

     public String getSubject() {
        return subject;
     }

     public int getAttendance() {
        return attendance;
     }

     public void setWhen(Date when) {
        this.when = when;
    }

     public void setSubject(String subject) {
        this.subject  = subject;
     }

     public void setAttendance(int attendance) {
        this.attendance = attendance;
     }
}

That’s a classic POJO and it’s the force that underlies JavaBeans and a few tools in Java.

The properties are effectively the getters/setters for example: subject, when etc. But properties have many features that are crucial:

  • They can be manipulated in runtime by a tool that had no knowledge of them during compile time

  • They’re observable - a tool can monitor changes to a value of a property

  • They can have meta-data associated with them

These features are crucial since properties allow you all kinds of magic for example: hibernate/ORM uses properties to bind Java objects to a database representation, jaxb does it to parse XML directly into Java objects and GUI builders use them to customize UI’s visually.

POJO’s don’t support most of that so pretty much all Java based tools use a lot of reflection & bytecode manipulation. This works but has a lot of downsides for example: say you want to map an object both to the Database and to XML/JSON.

Would the bytecode manipulation collide?

Would it result in duplicate efforts?

And how do you write custom generic code that uses such abilities? Do you need to manipulate the VM?

25.15.1. Properties in Java

These are all abstract ideas, lets look at how you think properties should look in Java and how you can gain from this moving forward.

This is the same class as the one above written with properties:

public class Meeting implements PropertyBusinessObject {
     public final Property<Date,Meeting> when = new Property<>("when");
     public final Property<String,Meeting> subject = new Property<>("subject");
     public final Property<Integer,Meeting>  attendance = new Property<>("attendance");
     private final PropertyIndex idx = new PropertyIndex(this, "Meeting", when, subject, attendance);

    @Override
    public PropertyIndex getPropertyIndex() {
        return idx;
    }
}

This looks a bit like a handful, so start with usage which might clarify a few things, then dig into the class itself.

With a plain object you would have written this:

Meeting meet = new Meeting();
meet.setSubject("My Subject");
Log.p(meet.getSubject());

With properties you do this:

Meeting meet = new Meeting();
meet.subject.set("My Subject");
Log.p(meet.subject.get());
Encapsulation

At first glance it looks like you created public fields (which you did) but if you will look at the declaration you will notice the final keyword:

public final Property<String,Meeting> subject = new Property<>("subject");

That final is what makes the field safe to expose: meet.subject = otherValue doesn’t compile, because there’s nothing to assign to.

All setting/getting must happen through the set/get methods and they can be replaced. For example: this is valid syntax that prevents setting the property to null and defaults it to an empty string:

public final Property<String,Meeting> subject = new Property<String, Meeting>("subject", "") {
     public Meeting set(String value) {
         if(value == null) {
            return Meeting.this;
         }
         return super.set(value);
     }
};
You will discuss the reason for returning the Meeting instance below
Introspection & observability

Since Property is a common class it’s pretty easy for introspective code to manipulate properties. For example, it can’t detect properties in an object without reflection.

That’s why you have the index object and the PropertyBusinessObject interface (which defines getPropertyIndex).

The PropertyIndex class provides metadata for the surrounding class including the list of the properties within. It allows enumerating the properties and iterating over them making them accessible to all tools.

Furthermore all properties are observable with the property change listener. You can write this to instantly print out any change made to the property:

meet.subject.addChangeListener((p) -> Log.p("New property value is: " + meet.subject.get()));

25.15.2. The cool stuff

That’s the simple stuff that can be done with properties, but they can do much more!

For starters all the common methods of Object can be implemented with almost no code:

public class Meeting implements PropertyBusinessObject {
     public final Property<Date,Meeting> when = new Property<>("when");
     public final Property<String,Meeting> subject = new Property<>("subject");
     public final Property<Integer,Meeting>  attendance = new Property<>("attendance");
     private final PropertyIndex idx = new PropertyIndex(this, "Meeting", when, subject, attendance);

    @Override
    public PropertyIndex getPropertyIndex() {
        return idx;
    }

    public String toString() {
        return idx.toString();
    }

    @Override
    public boolean equals(Object obj) {
        return obj != null && obj.getClass() == getClass() &&
            idx.equals(((Meeting)obj).getPropertyIndex());
    }

    @Override
    public int hashCode() {
        return idx.hashCode();
    }
}

This is easy thanks to introspection…​

You already have some simple code that can convert an object to/from JSON Maps for example: this can fill the property values from parsed JSON:

meet.getPropertyIndex().populateFromMap(jsonParsedData);

And vice versa:

String jsonString = meet.getPropertyIndex().toJSON();

You also have a simple ORM solution that maps values to table columns and can create tables. It’s no hibernate but sqlite isn’t big iron so it might be good enough.

Constructors

One of the problematic issues with constructors is that any change starts propagating everywhere. If you have fields in the constructor and you add a new field later you need to keep the old constructor for compatibility.

Codename One added a new syntax:

Meeting meet = new Meeting().
        subject.set("My Subject").
        when.set(new Date());

That’s why every property in the definition needed the Meeting generic and the set method returns the Meeting instance…​

You’re pretty conflicted on this feature and are thinking about removing it.

Without this feature the code would look like this:

Meeting meet = new Meeting();
meet.subject.set("My Subject");
meet.when.set(new Date());
Seamless serialization

Suppose you have an object called Contacts which includes contact information for example:

public class Contact implements PropertyBusinessObject {
    public final IntProperty<Contact> id  = new IntProperty<>("id");
    public final Property<String, Contact> name = new Property<>("name");
    public final Property<String, Contact> email = new Property<>("email");
    public final Property<String, Contact> phone = new Property<>("phone");
    public final Property<Date, Contact> dateOfBirth = new Property<>("dateOfBirth", Date.class);
    public final Property<String, Contact> gender  = new Property<>("gender");
    public final IntProperty<Contact> rank  = new IntProperty<>("rank");
    public final PropertyIndex idx = new PropertyIndex(this, "Contact", id, name, email, phone, dateOfBirth, gender, rank);

    @Override
    public PropertyIndex getPropertyIndex() {
        return idx;
    }

    public Contact() {
        name.setLabel("Name");
        email.setLabel("E-Mail");
        phone.setLabel("Phone");
        dateOfBirth.setLabel("Date Of Birth");
        gender.setLabel("Gender");
        rank.setLabel("Rank");
    }
}

Standard Java Objects can be serialized in Codename One by implementing the Codename One Externalizable interface. You also need to register the Externalizable object so the implementation will be aware of it. Codename One business objects are seamlessly Externalizable and you need to register them.

For example: you can do something like this in your init(Object) method:

new Contact().getPropertyIndex().registerExternalizable();

After you do that once you can write/read contacts from storage if you so want:

Storage.getInstance().writeObject("MyContact", contact);

Contact readContact = (Contact)Storage.getInstance().readObject("MyContact");

This will obviously also work for things like List<Contact> etc.

Seamless SQL storage

Writing SQL code can be tedious. Which is why SQLMap is such an important API for some of you. SQLMap allows CRUD (Create, Read, Update, Delete) operations on the built-in SQLite database using property objects.

If you continue the example from above to show persistence to the SQL database you can do something like this:

private Database db;
private SQLMap sm;
public void init(Object context) {
    theme = UIManager.initFirstTheme("/theme");
    Toolbar.setGlobalToolbar(true);
    Log.bindCrashProtection(true);

    try {
        Contact c = new Contact();
        db = Display.getInstance().openOrCreate("propertiesdemo.db"); (1)
        sm = SQLMap.create(db); (2)
        sm.setPrimaryKeyAutoIncrement(c, c.id); (3)
        sm.createTable(c); (4)
    } catch(IOException err) {
        Log.e(err);
    }
}

In the above code you do the following:

1Open or create the SQLite database. The name is an identifier rather than a path.
2Wrap it in a SQLMap, which is what maps properties to columns.
3Declare id the primary key and let the database assign it.
4Create the table if it isn’t there yet.
Notice that now altering a created table isn’t possible so if you add a new property you might need to detect that and do an alter call manually

You can then add entries to the contact table using:

sm.insert(myContact);

You can update an entry using:

sm.update(myContact);

And delete an entry using:

sm.delete(myContact);

Listing the entries is more interesting:

List<PropertyBusinessObject> contacts = sm.select(c, c.name, true, 1000, 0);

for(PropertyBusinessObject cc : contacts) {
    Contact currentContact = (Contact)cc;

   // ...
}

The arguments for the select method are:

  • The object type

  • The attribute by which you want to sort the result (can be null)

  • Whether sort is ascending

  • Number of elements to fetch

  • Page to start with - in this case if you have more than 1000 elements you can fetch the next page using sm.select(c, c.name, true, 1000, 1)

There are many more configurations where you can fine tune how a specific property maps to a column etc.

What’s still missing

The SQLMap API is simplistic and doesn’t try to be Hibernate/JPA for mobile. Basic things aren’t available now and won’t work. This isn’t necessarily a problem as mobile databases don’t need to be as powerful as server databases.

Relational Mappings/JOIN

There’s no way to map an object to another object in the database with the one-many or one-one relationships JPA offers. The SQLMap API isn’t suited to that level of mapping.

Threading

SQLite is sensitive to threading issues on iOS, so SQLMap issues its calls in process rather than moving them off the caller’s thread. That can be a problem for larger data sets, because the calls then run on the EDT.

Alter

Altering a table to match a schema that changed after the table was created isn’t supported. Migrating such a schema means issuing that SQL directly.

Complex SQL/Transactions

Functions, joins, transactions and a good deal of other SQL sit outside the mapping.

SQL can be used directly for any of that. A transaction begun before an insert, update or delete works as advertised, but the mapping is unaware of a rollback, so the data has to be re-fetched afterward.

The mapping covers autoincrement and the cases that map cleanly onto a table; a use case that needs more than that subset is better served by dropping to SQL directly.

Caching/Collision

Nothing is cached, so selecting the same row twice produces two separate instances. Update both and one of them wins, with no indication that the other was discarded.

That means the application has to keep track of the objects it holds, so a modified version isn’t left sitting beside an older one.

Preferences binding

Some objects make sense as global objects, you can use the Preferences API to store that data directly but then you don’t have the type safety that property objects bring to the table. That’s where the binding of property objects to preferences makes sense. For example: say you have a global Settings property object you can bind it to preferences using:

PreferencesObject.create(settingsInstance).bind();

If settings has a property called companyName it would bind into Preferences under the Settings.companyName entry.

You can do some more elaborate bindings such as:

PreferencesObject.create(settingsInstance).
    setPrefix("MySettings-").
    setName(settingsInstance.companyName, "company").
    bind();

This would customize all entry keys to start with MySettings- instead of Settings.. This would also set the company name entry to company so in this case instead of Settings.companyName you’d have MySettings-company.

UI binding

One of the bigger features of properties are their ability to bind UI to a property. For example: if you continue the sample above with the Contact class, say you have a text field on the form and you want the property (which you mapped to the database) to have the value of the text field. You could do something like this:

myNameTextField.setText(myContact.name.get());
myNameTextField.addActionListener(e -> myContact.name.set(myNameTextField.getText()));

That would work but what if you changed the property value, that wouldn’t be reflected in the text field?

Also that works for text field but what about other types for example: numbers, check boxes, pickers etc. This becomes a bit more tedious with those.

Binding makes this all seamless. For example: the code above can be written as:

UiBinding uib = new UiBinding();
uib.bind(myContact.name, myNameTextField);

The cool thing is that this works with many component types and property types almost magically. Binding works by using an adapter class to convert the data to/from the component. The adapter itself works with a generic converter for example: this code:

uib.bind(myContact.rank, myRankTextField);

Seems like the one above but it takes a String that’s returned by the text field and seamlessly converts it to the integer needed by rank. This also works in the other direction…​

You can build a UI that would allow you to edit the Contact property in memory:

Container resp = new Container(BoxLayout.y());
UiBinding uib = new UiBinding();

TextField nameTf = new TextField();
uib.bind(c.name, nameTf);
resp.add(c.name.getLabel()). (1)
        add(nameTf);

TextField emailTf = new TextField();
emailTf.setConstraint(TextField.EMAILADDR);
uib.bind(c.email, emailTf);
resp.add(c.email.getLabel()).
        add(emailTf);

TextField phoneTf = new TextField();
phoneTf.setConstraint(TextField.PHONENUMBER);
uib.bind(c.phone, phoneTf);
resp.add(c.phone.getLabel()).
        add(phoneTf);

Picker dateOfBirth = new Picker();
dateOfBirth.setType(Display.PICKER_TYPE_DATE); (2)
uib.bind(c.dateOfBirth, dateOfBirth);
resp.add(c.dateOfBirth.getLabel()).
        add(dateOfBirth);

ButtonGroup genderGroup = new ButtonGroup();
RadioButton male = RadioButton.createToggle("Male", genderGroup);
RadioButton female = RadioButton.createToggle("Female", genderGroup);
RadioButton undefined = RadioButton.createToggle("Undefined", genderGroup);
uib.bindGroup(c.gender, new String[] {"M", "F", "U"}, male, female, undefined); (3)
resp.add(c.gender.getLabel()).
        add(GridLayout.encloseIn(3, male, female, undefined));

TextField rankTf = new TextField();
rankTf.setConstraint(TextField.NUMERIC);
uib.bind(c.rank, rankTf); (4)
resp.add(c.rank.getLabel()).
        add(rankTf);
1Notice the use of the property’s label, which allows better encapsulation
2You can bind picker seamlessly
3You can bind many radio buttons to a single property to allow the user to select the gender, notice that labels and values can be different for example: "Male" selection will translate to "M" as the value
4Numeric bindings "work"
Properties form for the contact
Figure 242. Properties form for the contact
Binding object & auto commit

You skipped a couple of fact about the bind() method. It has an additional version that accepts a ComponentAdapter which allows you to adapt the binding to any custom 3rd party component. That’s a bit advanced for now but I might discuss this later.

For example, the big thing "skipped" earlier was the return value…​ bind returns a UiBinding.Binding object when performing the bind. This object allows you to manipulate aspects of the binding specifically unbind a component and also manipulate auto commit for a specific binding.

Auto commit determines if a property is changed instantly or on commit. This is useful for a case where you have an "OK" button and want the changes to the UI to update the properties when "OK" is pressed (this might not matter if you keep different instances of the object). When autocommit is on (the default which you can change through setAutoCommit in the UiBinding) changes reflect instantly, when it’s off you need to explicitly call commit() or rollback() on the Binding class.

commit() applies the changes in the UI to the properties, rollback() restores the UI to the values from the properties object (useful for a "reset changes" button).

Binding also includes the ability to "unbind" this is important if you have a global object that’s bound to a UI that’s discarded. Binding might hold a hard reference to the UI and the property object might create a memory leak.

By using the disconnect() method in Binding you can separate the UI from the object and allow the GC to clean up.

UI generation

Up until now this was pretty cool but if you looked at the UI construction code above you would see that it’s pretty full of boilerplate code. The thing about boilerplate is that it shows where automation can be applied, that’s the exact idea behind the magical "InstantUI" class. This means that the UI above can be generated using this code:

InstantUI iui = new InstantUI();
iui.excludeProperty(myContact.id); (1)
iui.setMultiChoiceLabels(myContact.gender, "Male", "Female", "Undefined"); (2)
iui.setMultiChoiceValues(myContact.gender, "M", "F", "U");
Container cnt = iui.createEditUI(myContact, true); (3)
1The id property is useful for database storage but you want to exclude it from the UI
2This implements the gender toggle button selection, you provide a hint to the UI so labels and values differ
3You create the UI from the screenshot above with one line and it’s seamlessly bound to the properties of myContact. The second argument indicates the "auto commit" status.

This still carries most of the flexibilities of the regular binding for example: you can still get a binding object using:

UiBinding.Binding b = iui.getBindings(cnt);

You might not have noticed this but in the previous verbose code you had lines like:

emailTf.setConstraint(TextField.EMAILADDR);

You might be surprised to know that this will still work seamlessly without doing anything, as would the picker component used to pick a date…​

The picker component implicitly works for date type properties, numeric constraints and numbers are implicitly used for number properties and check boxes are used for booleans.

However, how do you know to use an email constraint for the email property?

You’ve some special case defaults for some common property names, so if your property is named email it will use an email constraint by default. If it’s named url or password etc. It will do the "right thing" unless you explicitly state otherwise. You can customize the constraint for a specific property using something like:

iui.setTextFieldConstraint(myContact.email, TextArea.ANY);

This will override the defaults you’ve in place. The goal of this tool is to have sensible "magical" defaults that "work."

26. Desktop and Backend Processes

com.codename1.io.ProcessBuilder launches operating-system programs from shared application code. It returns com.codename1.io.Process, with stdin, stdout, stderr, exit status, timed waits, and termination. Neither class needs a running Display or backend server. Import Process explicitly: java.lang.Process has the same simple name.

TargetImplementation

JavaSE desktop and simulator on Windows, macOS, Linux

Host JDK process API

Native Windows desktop

Win32 CreateProcessW, Unicode arguments, asynchronous pipes

Native macOS and Linux desktop

POSIX child processes and nonblocking pipes

JVM backend

The same adapter as JavaSE desktop

Packaged ParparVM backend on Linux

The same native adapter as desktop

Android, iOS, browser and ports without an adapter

Unsupported; shared code still compiles

Call ProcessBuilder.isSupported() before offering process-dependent features. On unsupported ports, start() and environment() throw UnsupportedOperationException. A supported port can still deny a launch due to permissions, sandbox rules, or a missing executable. Those failures surface as IOException (or a host-JDK SecurityException), not a dummy process. Mobile ports don’t promise execution even where an OS exposes limited process facilities.

26.1. Compatibility with JavaSE

OperationCodename One behavior

Command

ProcessBuilder(String…​), ProcessBuilder(List<String>), and mutable command() follow the JavaSE shape. Each argument is passed literally. No shell is inserted, including for executable scripts without an interpreter header on POSIX.

Working directory

directory(String) accepts a native OS path, not java.io.File, com.codename1.io.File, or a file: URL. Null inherits the parent directory.

Environment

environment() returns a mutable copy on first access. Until accessed, the child inherits the environment at launch. Invalid names/values (null, NUL, empty names, or = in names) are rejected at start(), including mutations through map entries. This validation timing and lazy snapshot differ from JavaSE.

Pipes

getOutputStream() writes child stdin; getInputStream() reads stdout; getErrorStream() reads stderr. redirectErrorStream(true) merges stderr into stdout and makes the stderr stream return EOF.

Redirection

File redirection, inheritIO(), pipelines, and ProcessHandle are outside this subset. Copy through the streams instead.

Waiting

waitFor(), waitFor(long, TimeUnit), and the extra waitFor(long timeoutMillis) wait for the direct child. A timeout returns false and leaves it running. Interrupting a wait throws InterruptedException and also leaves it running.

Termination

destroy() requests SIGTERM on POSIX and terminates forcibly on Windows. destroyForcibly() requests SIGKILL on POSIX or Windows termination. Both return before termination completes; use a wait to observe completion. Neither terminates descendants.

Exit codes

Nonzero exit is a normal result. exitValue() throws IllegalThreadStateException while alive. POSIX signal termination yields 128 + signal; Windows preserves the exit-code bits in a Java int.

Cleanup

Process implements AutoCloseable. close() requests forcible termination and closes all three streams, even if one close fails. It doesn’t wait. The runtime independently reaps children, including when callers never wait. Closing streams after exit releases their resources; unread output is retained until read or closed.

Concurrency

Use one reader per output stream and one writer for stdin. The native adapter rejects overlapping reads or writes on the same stream. Closing a stream from another thread cancels native pipe I/O. Native interrupted pipe I/O throws InterruptedIOException and closes that pipe; JVM stream interruption follows the host JDK.

Executable lookup follows the host OS. Prefer an absolute executable path for consistent behavior across operating systems. POSIX uses the child environment’s PATH (or /usr/bin:/bin if absent); Windows uses CreateProcessW lookup rules, which don’t use a replacement child PATH. Windows argument quoting targets the standard C runtime argument parser; programs with custom command-line parsers can interpret their command line differently. Use the existing capitalization of Windows environment names when editing the map, and avoid duplicate names that differ only in case.

26.2. A Desktop Example

Run process I/O and waits off the EDT. This example invokes a small version command, drains merged output concurrently, and enforces a wait timeout. Replace my-tool with an installed executable or its absolute path. Import java.io.ByteArrayOutputStream and java.io.IOException.

public void readToolVersion() {
    // Check isSupported() before enabling this action in your UI.
    new Thread(() -> {
        try (com.codename1.io.Process child = new com.codename1.io.ProcessBuilder("my-tool", "--version")
                .redirectErrorStream(true).start()) {
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            Thread reader = new Thread(() -> {
                try {
                    byte[] buffer = new byte[4096];
                    int count;
                    while ((count = child.getInputStream().read(buffer)) != -1) {
                        output.write(buffer, 0, count);
                    }
                } catch (IOException error) {
                    // Closing the process also cancels an outstanding native read.
                    com.codename1.io.Log.e(error);
                }
            });
            reader.start();
            child.getOutputStream().close(); // No input; send EOF to the tool.
            if (!child.waitFor(30, java.util.concurrent.TimeUnit.SECONDS)) {
                child.destroyForcibly();
            }
            child.waitFor();
            reader.join();
            String version = new String(output.toByteArray(), "UTF-8");
            // Use Display.callSerially(...) for any UI update using version.
        } catch (Exception error) {
            com.codename1.io.Log.e(error);
        }
    }).start();
}

For commands with substantial output, stream to a consumer or file rather than retaining everything in memory. Without stderr merging, start independent stdout and stderr readers. Waiting before draining can deadlock when a pipe fills. A child can also spawn descendants that keep pipes open after it exits; manage such tools explicitly rather than assuming child exit implies pipe EOF.

26.3. Backend Ownership and Blocking

A request owns the children it starts. Close them in finally or a try-with-resources block, including on cancellation and timeout. Server-wide children should belong to a managed bean whose @PreDestroy method closes them. The process API doesn’t attach arbitrary children to a request or server, and server shutdown doesn’t implicitly kill unrelated processes. Abrupt termination of the parent can leave children running, as with JavaSE.

Native pipe reads/writes and exit checks are nonblocking OS operations. Between polls, unpinned backend virtual threads park through the backend scheduler; platform threads sleep. Don’t hold application monitors around these operations: a virtual thread holding a monitor is pinned to its host. Launch itself crosses the OS process-creation boundary synchronously and can occupy the calling host; use a platform task if executable lookup or launch can be slow.

26.4. Local Validation

scripts/process/check-process.sh jvm runs real-child tests against the shared JavaSE adapter and OS layer. scripts/process/check-process.sh native builds and executes the same Java conformance program with ParparVM. Set JDK_8_HOME to a Java 8 installation. Native tests are local-only; the script rejects native execution when CI is set.

The portable scripts/process/process_os_test.c also builds on Windows alongside process_child.c. Pass the child executable and an existing absolute working directory to the test. With MinGW, compile both fixtures with -municode to use their Unicode entry points. Tests cover literal/Unicode arguments, environment, working directory, large simultaneous stdout/stderr, binary stdin round trips, merged stderr, launch errors, termination, and repeated launches. The Java suite additionally covers waits, interrupts, and close(). Native mode also runs a backend with one virtual-thread host and verifies that a pending process read or wait permits another task to run. The OS test checks descriptor/handle counts across repeated launches, child reaping, and closed-stdin failure.

To test Windows environment decoding independently of the active code page, run python3 scripts/process/build-windows-environment-test.py OUTPUT.exe with CC set to a Windows C compiler. Run the executable on Windows or Wine with a non-UTF-8 active code page. It exercises the native environment binding and string decoder with Unicode names and values, including a supplementary character.

27. Deeper Network Connectivity

Codename One ships a set of APIs under com.codename1.io.wifi, com.codename1.io.bonjour, com.codename1.io.usb and an extension of com.codename1.io.NetworkManager that lets apps inspect and manage the device’s local network beyond plain HTTP.

A quick connectivity check is NetworkManager.getInstance().isConnected() — it reads the cached platform network state and returns immediately without an HTTP probe, so it’s safe to call from the EDT before deciding whether to fire a ConnectionRequest.

These APIs share three guarantees:

  • Every callback runs on the EDT so you can update UI directly from the result.

  • The build pipeline injects the matching Android permissions, iOS entitlements, and NSXxxUsageDescription / NSBonjourServices Info.plist entries automatically by scanning the classpath. Apps that never reference these classes see no manifest or entitlement changes.

  • The simulator implements best-effort versions of each API so you can wire and test your UI without a device. The simulator also prints the list of permissions/entitlements each API will need in a real build the first time you call it.

The simulator’s "API usage report" prints to stdout on JVM shutdown so you can spot anything you pulled in via a transitive cn1lib.

27.1. WiFi information

The fastest way to know whether the user is on WiFi, what SSID they joined, and what their local IP is:

if (WiFi.isInfoSupported()) {
    String ssid = WiFi.getCurrentSSID();   // e.g. "Codename One"
    String bssid = WiFi.getBSSID();        // "aa:bb:cc:11:22:33"
    String gw = WiFi.getGateway();         // "192.168.1.1"
    String ip = WiFi.getIp();              // "192.168.1.42"
}

Any of these calls may return null if the device isn’t on WiFi, if the user denied a runtime permission, or if the platform never exposed the value to apps. The framework normalizes the wrapping that Android adds to the SSID and treats <unknown ssid> and the obfuscated BSSID 02:00:00:00:00:00 as null.

27.1.1. Required permissions and entitlements

The build pipeline injects the following automatically the first time it sees com.codename1.io.wifi.WiFi on the classpath:

PlatformInjectedNotes

Android

ACCESS_WIFI_STATE, ACCESS_NETWORK_STATE

"normal" permissions; no runtime prompt

Android API 26+

ACCESS_FINE_LOCATION (maxSdkVersion=32)

Required by the OS to return a real SSID

Android API 33+

NEARBY_WIFI_DEVICES with neverForLocation

Replaces fine-location for scan flows

iOS

com.apple.developer.networking.wifi-info entitlement

Required since iOS 13

iOS

NSLocationWhenInUseUsageDescription

iOS still checks CoreLocation behind the scenes

You can override any injected automatically value via the standard build hints:

ios.locationUsageDescription=Allow access to read your Wi-Fi network name to discover printers on your network.
android.xpermissions=<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

27.2. WiFi scan

Scanning returns an array of `WiFiNetwork`s sorted by signal strength. The callback fires once.

iOS doesn’t expose a public WiFi scan API. On iOS WiFi.scan(…​) always reports an UnsupportedOperationException. Plan for a graceful fallback if your UI exposes a scan button.

Android throttles scans to 4 per 2 minutes per foreground app on API 28+; throttled scans return cached results, not an error.

27.3. WiFi connect

To associate the device with a specific SSID:

WiFi.connect("MyAccessPoint", "s3cret!", WiFiSecurity.WPA_PSK,
        new WiFiConnectCallback() {
    @Override
    public void onConnectResult(boolean connected, Throwable error) {
        if (!connected) {
            Log.e(error);
            return;
        }
        // ssid is now joined
    }
});
  • On Android 10+ the OS shows a system confirmation dialog with the SSID before joining; this dialog can’t be bypassed.

  • On Android 9 and below the framework falls back to the legacy WifiConfiguration API and joins without an in-app prompt.

  • On iOS 11+ this uses NEHotspotConfiguration. The user is shown a system prompt the first time the app tries to join the SSID; subsequent attempts reuse the cached configuration.

  • WiFiSecurity must match the AP’s actual security mode (OPEN, WEP, WPA_PSK, WPA3_SAE). Passing the wrong mode causes the join to fail.

WiFi.disconnect(ssid) releases the request on Android 10+ and removes the hotspot configuration on iOS.

On iOS the build pipeline also enables the NetworkExtension.framework and the HotspotConfiguration entitlement only when it sees a call to WiFi.connect(…​) or WiFi.disconnect(…​). Apps that only read SSID/BSSID won’t pull in the framework, which keeps App Store API-usage scans clean.

27.4. Bonjour / mDNS discovery

BonjourBrowser watches the local network for services of a given mDNS type. BonjourPublisher advertises a service.

BonjourBrowser browser = BonjourBrowser.browse("_http._tcp.",
        new BonjourServiceListener() {
    @Override
    public void onServiceResolved(BonjourService s) {
        Log.p("Found " + s.getName() + " at " + s.getHost() + ":" + s.getPort());
    }
    @Override
    public void onServiceLost(BonjourService s) { /* null */ }
    @Override
    public void onBrowseError(Throwable t) { Log.e(t); }
});

// when done:
browser.stop();

To advertise an HTTP server you wrote on port 8080:

BonjourPublisher pub = BonjourPublisher.publish(
        "My Server", "_http._tcp.", 8080, null);

// later:
pub.unpublish();

27.4.1. iOS requirements

Bonjour on iOS 14+ returns no results unless:

  • The Info.plist NSLocalNetworkUsageDescription key explains why the app needs local-network access.

  • The Info.plist NSBonjourServices array lists each service type the app expects to find.

The build pipeline injects both keys automatically when com.codename1.io.bonjour is on the classpath, with _http._tcp. as the seed type. To publish or browse a custom type, set the build hint:

ios.NSBonjourServices=_myapp._tcp.,_http._tcp.
ios.NSLocalNetworkUsageDescription=Discover other instances of MyApp on this Wi-Fi network.

The comma-separated values are expanded into the Info.plist array at build time.

27.4.2. Linux and embedded devices

The Linux desktop and embedded targets answer and browse on their own UDP socket and need no Avahi or other system service. A headless device running the backend uses com.codename1.backend.Discovery, which speaks the same protocol, so a phone application finds it with BonjourBrowser.

27.4.3. Android requirements

The pipeline adds CHANGE_WIFI_MULTICAST_STATE automatically. NsdManager does the rest; there is no runtime permission prompt.

27.4.4. Simulator behaviour

If javax.jmdns.JmDNS is on the simulator classpath, browse calls dispatch through it. Otherwise the listener receives a single UnsupportedOperationException and the simulator prints a hint. Add JmDNS to your application’s executable-jar / simulator profile (typically the <profile id="executable-jar"> block in your cn1app’s common/pom.xml or your javase/pom.xml) to exercise real discovery in the simulator:

<!-- in YOUR app's pom, NOT in the framework / common pom that gets shipped
     to the device. The cn1app archetype's executable-jar profile is the
     right place because it only applies when launching the simulator. -->
<dependency>
    <groupId>org.jmdns</groupId>
    <artifactId>jmdns</artifactId>
    <version>3.5.9</version>
    <scope>runtime</scope>
</dependency>

Don’t add JmDNS to the cn1app common/pom.xml outside a simulator-scoped profile — it would then ship with your Android / iOS binaries even though both platforms supply native mDNS implementations.

27.5. Network type change events

Subscribe to network type transitions (WiFi <→ Cellular <→ Ethernet <→ None):

NetworkManager.getInstance().addNetworkTypeListener(new NetworkTypeListener() {
    @Override
    public void onNetworkTypeChanged(int oldType, int newType, boolean vpnActive) {
        if (newType == NetworkManager.NETWORK_TYPE_NONE) {
            // offline -- queue uploads for later
        }
        if (vpnActive) {
            // refuse to roam to corporate-only resources
        }
    }
});

The current snapshot is available without subscribing:

int type = NetworkManager.getInstance().getCurrentNetworkType();
boolean vpn = NetworkManager.getInstance().isVPNActive();

The platform implementations are:

  • Android: ConnectivityManager.registerNetworkCallback on API 21+, falling back to the legacy CONNECTIVITY_ACTION broadcast on older devices.

  • iOS: SCNetworkReachability with a kernel callback scheduled on the main run loop.

  • Simulator: derives the type from NetworkInterface.getDisplayName; transitions aren’t synthesized.

VPN detection is best-effort and intentionally heuristic. On Android it uses NetworkCapabilities.TRANSPORT_VPN plus an interface-name probe; on iOS it inspects utun*, tun*, ppp* and ipsec* interfaces. Use it as a hint, not as a security boundary.

27.6. WiFi Direct (Wi-Fi P2P)

WiFi Direct lets two devices form a peer-to-peer link without an access point. The API is Android-only — iOS uses MultipeerConnectivity for similar scenarios and is intentionally out of scope.

The build pipeline injects CHANGE_WIFI_STATE, ACCESS_WIFI_STATE, ACCESS_NETWORK_STATE, ACCESS_FINE_LOCATION and NEARBY_WIFI_DEVICES automatically when WiFiDirect is on the classpath, plus a <uses-feature android:name="android.hardware.wifi.direct"/> declaration so devices without the radio can still install the app via Play Store filtering.

27.7. USB host

The USB API in com.codename1.io.usb lets the device act as a USB host and talk to attached peripherals — a barcode scanner, a serial converter, a microcontroller. It’s Android-only; iOS has no third-party USB host access and the simulator stubs everything out.

if (!Usb.isSupported()) { return; }

Usb.addDeviceListener(new UsbDeviceListener() {
    @Override
    public void onDeviceAttached(UsbDevice d) {
        if (d.getVendorId() == 0x0403 && d.getProductId() == 0x6001) {
            Usb.requestPermission(d);
        }
    }
    @Override
    public void onDeviceDetached(UsbDevice d) { }
    @Override
    public void onPermissionResult(UsbDevice d, boolean granted) {
        if (granted) {
            try (InputStream in = Usb.openInputStream(d, 0x81);
                 OutputStream out = Usb.openOutputStream(d, 0x02)) {
                out.write("AT\r\n".getBytes());
                byte[] buf = new byte[64];
                int n = in.read(buf);
                // null
            } catch (IOException e) { Log.e(e); }
        }
    }
});

The build pipeline injects:

  • <uses-feature android:name="android.hardware.usb.host" android:required="false"/>.

If you want the OS to launch your app when a matching device is plugged in, ship a device_filter.xml resource and declare an <intent-filter> via the android.xintent_filter build hint:

<!-- native/android/res/xml/device_filter.xml -->
<resources>
    <usb-device vendor-id="1027" product-id="24577" />
</resources>
android.xintent_filter=<intent-filter><action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" /></intent-filter><meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" android:resource="@xml/device_filter" />

27.8. Releasing platform resources

Most of these APIs hold background resources (broadcast receivers, network callbacks, NSNetService delegates) that you must release explicitly:

  • BonjourBrowser — call .stop().

  • BonjourPublisher — call .unpublish().

  • WiFiDirect — call .stopDiscovery() and .disconnect().

  • WiFi.connect(…​) — call WiFi.disconnect(ssid) when the user navigates away.

  • Usb.addDeviceListener(…​) — call removeDeviceListener(…​).

  • NetworkManager.addNetworkTypeListener(…​) — call removeNetworkTypeListener(…​).

Each of these keeps a radio or system service awake. Bonjour browsers and WiFi scans in particular drain battery noticeably — they’re fine during a few user-facing screens but shouldn’t stay armed for the lifetime of the app. Release them as soon as the screen that needs them is no longer visible.

28. JSON / XML Object Mapping

Codename One includes a build-time POJO mapping framework that turns a plain Java class — or a PropertyBusinessObject — into JSON or XML without any runtime reflection. The Maven plugin scans the project’s compiled bytecode at build time, generates a typed Mapper next to each @Mapped class, and ships it alongside the source. The runtime entry point is two methods on com.codename1.mapping.Mappers.

The framework sits next to the existing JSONParser, XMLParser and PropertyIndex.toJSON / fromJSON helpers — it doesn’t replace them. Use the imperative APIs when you want to read a foreign JSON shape without modelling it; use the annotation framework when you have a model class and want a one-liner round-trip.

28.1. Annotate the model

Apply @Mapped to the class. The processor accepts POJOs with public fields, PropertyBusinessObject-style classes with Property fields, or any mix:

@Mapped
@XmlRoot("user")
public class User {

    @JsonProperty("first_name")
    @XmlElement("first")
    public String firstName;

    public int age;

    // Renders as <user role="admin"/> in XML; omitted from JSON.
    @XmlAttribute
    @JsonIgnore
    public String role;

    public User() { }                                  (1)
}
1Every @Mapped class must declare a public no-arg constructor — the generated mapper calls it from fromJson / fromXml.

For PropertyBusinessObject-style classes the same annotations work on Property<T> fields. The processor reads through Property#get / Property#set so subscribers (addChangeListener) still see the mutation:

@Mapped
public class Item implements PropertyBusinessObject {
    public final Property<String, Item>  name = new Property<>("name");
    public final Property<Integer, Item> qty  = new Property<>("qty");

    private final PropertyIndex idx =
            new PropertyIndex(this, "Item", name, qty);

    public PropertyIndex getPropertyIndex() { return idx; }

    public Item() { }
}

28.1.1. Field-level annotations

AnnotationPurpose

@JsonProperty("k")

Rename the JSON key. Default: the field name. aliases lists other keys it’s read from, and required = true refuses JSON that leaves it out.

@JsonIgnore

Omit the field from JSON.

@JsonOmitNull

Leave the field out of JSON while it’s null. On the class, for every field.

@JsonFormat(STRING)

Write a number in quotes, or a Date as an ISO-8601 instant. Either form is read back.

@JsonAdapter(A.class)

Convert the value with your own JsonTypeAdapter. On a class, wherever the class appears.

@JsonStrict

On the class: refuse JSON with a member it doesn’t declare.

@JsonCreator

On a constructor or static factory: build an immutable class from JSON through it, each parameter named with @JsonProperty.

@XmlElement("name")

Rename the XML element. Default: the field name.

@XmlAttribute("name")

Lift the field into an XML attribute rather than a nested child element. Only valid for scalar or Property<scalar> fields.

@XmlTransient

Omit the field from XML.

28.1.2. Supported field types

KindDetail

Scalars

String, all primitives, boxed primitives, java.util.Date, byte[] (base64 in JSON / XML).

Property<T, ?>

T must be a scalar or another @Mapped type.

ListProperty<T, ?>

Same rules as Property.

java.util.List<T>

Read from the field’s generic signature.

Arrays

One dimension, of any type above; a JSON array. XML leaves them out.

Generic classes

A field Page<User> of a @Mapped class Page<T> maps its T members as User.

Nested @Mapped ref.

Recursive serialization through the registered nested mapper.

The server’s generated JSON codecs read the same annotations, so a class shared by the app and its backend has one JSON contract on both sides. JSON that breaks it, such as a missing required member or a value of the wrong type, is refused with an IllegalArgumentException that names where it was: $.items[2].id: required member is missing. A member that’s absent leaves the field as the constructor set it. An explicit null sets the field to null in a @JsonStrict class, on a required member and through an adapter, which is handed the null, as the server does in every class. Elsewhere the app keeps reading an explicit null as it always has, like an absent member, so a class that uses none of these options maps exactly as before.

28.2. Round-trip

Mappers.fromJson and Mappers.fromXml both accept either a String or a java.io.Reader, so streamed responses (network, file, resource) don’t need to be fully buffered first.

28.3. How the plumbing works

At build time:

  1. cn1:process-annotations (PROCESS_CLASSES phase) scans target/classes for every class carrying @Mapped.

  2. The processor validates each one (concrete, public no-arg constructor, supported field types) and fails the build on the first offender — every offending class shows up in the same error report.

  3. A <SimpleName>Cn1Mapper class is generated for every @Mapped type in the same package as the source class (e.g. com.example.UserCn1Mapper next to com.example.User). Each generated mapper exposes a public static register() hook.

  4. A single cn1app.MapperBootstrap is generated whose constructor calls UserCn1Mapper.register(), ItemCn1Mapper.register(), …​ for every accepted @Mapped class.

At app start:

  • On iOS / Android, the build server probes the project zip for cn1app/MapperBootstrap.class. When found it splices new cn1app.MapperBootstrap(); into the per-build application stub right before Display.init. ParparVM rename and R8 obfuscation rewrite the call site and the generated class together, so the direct symbol reference stays valid after the pass.

  • On the JavaSE simulator and desktop run, JavaSEPort#postInit loads the bootstrap via Class.forName("cn1app.MapperBootstrap"). The classloader is the legitimate path here — JavaSE runs unobfuscated and the same Class.forName pattern is used by the @Route dispatcher.

Projects that ship no @Mapped classes produce no bootstrap, the build server probe falls through, and JavaSEPort catches the ClassNotFoundException — the registry stays empty and Mappers.toJson throws a clear "no mapper registered" error.

The runtime registry is keyed on Class#getName(). The map keys survive obfuscation because both the registration site and the lookup site see the same renamed name within a single execution — the keys are never persisted across builds.

28.4. Custom mappers

Sometimes a class lives in a third-party JAR the build can’t annotate. Hand-write a Mapper<T> and register it at startup:

// A type from a third-party jar the build cannot annotate.
static class LatLon {
    double lat;
    double lon;
}

static class LatLonMapper implements Mapper<LatLon> {
    @Override
    public Class<LatLon> type() {
        return LatLon.class;
    }

    @Override
    public Map<String, Object> toMap(LatLon instance) {
        Map<String, Object> m = new LinkedHashMap<String, Object>();
        m.put("lat", Double.valueOf(instance.lat));
        m.put("lon", Double.valueOf(instance.lon));
        return m;
    }

    @Override
    public LatLon fromMap(Map<String, Object> map) {
        LatLon out = new LatLon();
        out.lat = readDouble(map.get("lat"));
        out.lon = readDouble(map.get("lon"));
        return out;
    }

    @Override
    public String xmlRootName() {
        return "latLon";
    }

    @Override
    public void writeXml(LatLon instance, Element root) {
        root.setAttribute("lat", String.valueOf(instance.lat));
        root.setAttribute("lon", String.valueOf(instance.lon));
    }

    @Override
    public LatLon readXml(Element root) {
        LatLon out = new LatLon();
        out.lat = Double.parseDouble(root.getAttribute("lat"));
        out.lon = Double.parseDouble(root.getAttribute("lon"));
        return out;
    }

    // JSONParser hands back a Double for every number, but a map that came
    // from somewhere else may hold any Number. Read through the interface
    // rather than casting to Double: a failed cast does not throw on iOS,
    // so the catch you would write for it never runs.
    private double readDouble(Object value) {
        return value instanceof Number ? ((Number) value).doubleValue() : 0;
    }
}

void registerMappers() {
    Mappers.register(new LatLonMapper());
}

Hand-written mappers take precedence over generated ones for the same class.

29. Component Binding

The component binding framework wires a model field to the matching component in a Form or Container by name. The Maven plugin generates a <SimpleName>Cn1Binder per @Bindable class at build time, so the wiring happens through direct symbol references — no reflection, no listener bookkeeping in application code.

It’s a thin alternative to the imperative UiBinding API (com.codename1.properties.UiBinding). Both can be used together.

29.1. Annotate the model

@Bindable
public class LoginModel {

    @Bind(name = "userField", attr = BindAttr.TEXT)
    @Required
    private String user;
    public String getUser()              { return user; }
    public void   setUser(String u)      { this.user = u; }                  (1)

    @Bind(name = "rememberMe", attr = BindAttr.SELECTED)
    public boolean remember;                                                   (2)

    @Bind(name = "banner", attr = BindAttr.UIID, twoWay = false)
    public String bannerStyle;

    @Bind(name = "fullName",
          attr = BindAttr.TEXT,
          getter = "computeFullName",
          setter = "applyFullName")                                           (3)
    private String fullName;
    // both run during the initial bind, against a model that may still be
    // empty, so neither can assume a value is present
    public String computeFullName()      { return fullName == null ? "" : fullName.toUpperCase(); }
    public void   applyFullName(String f){ this.fullName = f == null ? null : f.trim(); }
}
1JavaBeans getUser / setUser are detected automatically when the field is private. The processor instruments setUser to fire a change notification for two-way bindings.
2Public field still works — direct field access falls back when no accessor matches the JavaBeans convention.
3Explicit getter / setter override the JavaBeans search. Use when the convention doesn’t apply (renamed accessors, transforms, fluent setters).

Every @Bind(name=…​) is looked up against Component#getName(), walking the container’s children recursively until a match is found. The default lookup matches GUI-builder names exactly.

29.1.1. Attribute kinds

BindAttrMirrors

TEXT

getText / setText on Label, Button, TextField, TextArea, SpanLabel, SpanButton. Two-way for TextArea / TextField.

UIID

getUIID / setUIID. One-way.

VISIBLE

isVisible / setVisible. One-way.

HIDDEN

isHidden / setHidden. One-way.

ENABLED

isEnabled / setEnabled. One-way.

SELECTED

isSelected / setSelected on CheckBox, RadioButton. Two-way.

ICON_NAME

Calls Resources.getGlobalResources().getImage(name) and writes the result via Label#setIcon. One-way.

NAME

setName. One-way.

29.2. Bind at runtime

Binding is the handle the binder returns:

MethodPurpose

refresh()

Push the current model values into every bound component. Use after mutating the model outside the form, or to re-sync after commit().

commit()

Pull current component values back into the model. Useful before validating / submitting when none of the bindings is two-way.

disconnect()

Remove every listener the binder installed and unregister the binding from the change-notification fan-out.

29.3. Two-way bindings and the change-notification contract

A binding declared twoWay = true flows in both directions:

How the update region breaks the two-way loop
  1. Component → model. The generated binder installs a listener on the editable component (TextField, CheckBox, etc.). When the user mutates the component, the binder calls the model’s setter (or assigns the public field). The setter’s instrumented exit calls Binders.notifyChanged(this).

  2. Model → component. Application code that mutates the model through a setter causes Binders.notifyChanged(this) to fire, which walks every live binding for that model and pushes the new value into the matching component.

The two paths together would loop forever if left alone — the model setter fires a change event, which refreshes the component, which fires its own change event, which calls the model setter again, …​ To break the loop, every framework-initiated mutation runs inside an update region guarded by a thread-local depth counter. While the counter is positive, notifyChanged is a no-op and component listeners short-circuit.

Concretely:

  • Binders.bind(model, container) enters an update region for the initial model → component push.

  • Binding#refresh() enters an update region for every subsequent model → component push.

  • Binding#commit() enters an update region for the component → model pull.

  • The generated component listener enters an update region before calling the setter.

29.3.1. Setter instrumentation

For every two-way @Bind field whose write accessor is a method (whether you wrote @Bind(setter="setName") or the processor detected setName(String) via the JavaBeans convention), the cn1:process-annotations Mojo reads the original .class file with ASM and inserts the equivalent of:

public void setName(String name) {
    this.name = name;
    com.codename1.binding.Binders.notifyChanged(this);   // injected
}

The injection lands before every return point of the setter. The instrumented setter is written back to target/classes, replacing the original. Application code that calls model.setName(…​) — from any thread, any code path — now triggers the binding fan-out automatically.

29.3.2. Limitation — cross-field setter chains

When a setter synchronously mutates a second bound field (setFirstName also calls setFullName, for example), whether the second field’s notifyChanged is suppressed depends on who called the first. An application calling setFirstName directly isn’t inside an update region, so the nested setFullName notifies at depth zero and its component refreshes normally. Reached from the generated component listener or from commit(), the chain runs inside a region that’s already open, the second field’s notifyChanged lands in it and is suppressed, and the bound component for fullName won’t catch up until something exits the region and a separate event drives the refresh. If you need the cross-field update to propagate, call binding.refresh() explicitly after the setter chain completes, or restructure the model so the cross-field mutation happens outside the setter’s call frame — for example via a Display.callSerially.

commit() is worse than suppression, and only one of the two remedies survives it. When both fields are bound two-way and fullName is emitted after firstName, the generated _commit carries on to the fullName component, reads the value still sitting in it, and calls setFullName — overwriting what setFirstName just derived. An immediate binding.refresh() afterward publishes the overwritten value rather than the derived one, so that remedy doesn’t help here.

The deferred write still does. Display.callSerially() queues the write and returns, so _commit finishes and leaves its update region before the deferred setFullName runs and notifies at depth zero.

Binding the derived field one way stops that write but doesn’t finish the job: one-way fields aren’t instrumented, and the setFirstName notification is still suppressed by the commit’s region, so the model holds the derived value while the screen keeps the old one. If you go that way, call binding.refresh() after the commit to publish it.

29.4. POJOs versus Property objects

A String, int, or boolean field is read and written through the resolved accessors. A Property<T, ?> field is read through get() and written through set() — so existing PropertyChangeListener subscribers fire as expected. Both styles can sit on the same class.

29.5. Validation annotations

The same @Bind field can carry validation annotations that are wired into a com.codename1.ui.validation.Validator. The validator is built by the generated binder at the moment you call Binders.bind(…​) and is reachable via Binding#getValidator() — so the same generated plumbing that pushes model values into components also installs the constraints that gate them.

AnnotationMaps toNotes

@Required

LengthConstraint(1)

"Field must be non-empty."

@Length(min = N)

LengthConstraint(N, message)

Minimum string length.

@Regex(pattern = …​, message = …​)

RegexConstraint(pattern, message)

Same dialect as com.codename1.util.regex.RE.

@Email

RegexConstraint.validEmail(message)

The standard email regex (also accepts empty — stack with @Required).

@Url

RegexConstraint.validURL(message)

http / https / ftp / file schemes.

@Numeric(decimal = …​, min = …​, max = …​, message = …​)

NumericConstraint(…​)

Bounds are inclusive; default range is unbounded.

@ExistIn({…​})

ExistInConstraint(values, caseSensitive, message)

Whitelist of allowed string values.

@Validate(MyConstraint.class)

new MyConstraint()

Escape hatch — the class must have a public no-arg constructor and implement Constraint.

Multiple annotations on the same field are combined into a GroupConstraint (first failure wins), matching the behaviour of Validator.addConstraint(Component, Constraint…​).

After binding, drive validation through the returned handle:

// set this first: bind() attaches the constraints, and each one picks a
// data-change or an action listener from this flag as it attaches
Validator.setValidateOnEveryKey(true);

LoginModel model = new LoginModel();
Binding b = Binders.bind(model, form);

// Auto-disable a submit button until everything is valid. Pass the
// button you built the form with: Container has no lookup by name.
b.getValidator().addSubmitButtons(submitButton);

// Programmatic gate before saving:
if (b.getValidator().isValid()) {
    repository.save(model);
}

Binding#getValidator() never returns null — when the model has no validation annotations the validator is empty and isValid() returns true. The validator owns the listener and emblem plumbing on the matching components; calling addSubmitButtons after bind is the typical pattern.

29.6. Build-time validation

In addition to the runtime constraints above, the annotation processor itself fails the build when:

  • @Bind is applied to a field with no accessible read path — the field must be public, declare a JavaBeans getX / isX getter, or the annotation must name an explicit getter.

  • A two-way @Bind field on a TEXT or SELECTED attr has no writable accessor. Set twoWay=false to keep the binding one-way, or add a setter / explicit setter=.

  • @Bind(name=…​) is empty.

  • The field’s static type isn’t supported (raw collections, opaque references that aren’t @Bindable themselves, …​).

  • @Regex is missing a pattern, or @ExistIn is missing values.

Errors are accumulated so a single build run reports every offending field at once.

29.7. How the plumbing works

cn1:process-annotations writes one <SimpleName>Cn1Binder per @Bindable class in the source class’s package, plus a single cn1app.BinderBootstrap whose constructor calls UserCn1Binder.register(), LoginModelCn1Binder.register(), …​ for every accepted @Bindable class. At app start:

  • On iOS / Android the build server probes the project zip for cn1app/BinderBootstrap.class and splices new cn1app.BinderBootstrap(); into the per-build application stub before Display.init. ParparVM rename and R8 obfuscation rewrite the direct symbol reference together with the generated class so the binding still resolves after the pass.

  • On JavaSE JavaSEPort#postInit loads the bootstrap via Class.forName("cn1app.BinderBootstrap") — the unobfuscated classloader path.

Projects with no @Bindable classes produce no bootstrap; the build server probe falls through and the registry stays empty.

The runtime registry is keyed on Class#getName(); obfuscation renames the call sites and the registered keys together within a single execution.

30. SQLite ORM

The SQLite ORM framework turns a plain Java class into a typed data access object at build time. The Maven plugin reads @Entity / @Id / @Column annotations from the project’s compiled bytecode, generates one <SimpleName>Cn1Dao per entity in the source class’s package, and hands the dao to com.codename1.orm.EntityManager for typed retrieval. The dao issues prepared statements through com.codename1.db.Database, the same surface every cn1 SQLite port exposes.

The framework is a JPA-inspired, simplified alternative to the existing imperative SQLMap. It doesn’t replace SQLMap; both can be used side by side.

30.1. Annotate the entity

@Entity(table = "users")
public class User {

    @Id(autoIncrement = true)
    public long id;

    @Column(name = "full_name", nullable = false)
    public String name;

    public int age;

    public java.util.Date createdAt;

    @DbTransient
    public String cacheKey;                            (1)

    public User() { }
}
1Excluded from the generated table.

Property fields work the same way; the dao calls Property#get and Property#set for read and write.

Every field that isn’t static or transient is stored, whatever its access: a private field with a getter and a setter is mapped the same way a public one is. The build weaves a static accessor into the class that declares each non-public field and the generated code calls it, so no reflection is involved on any platform. A field is left out of the table when it’s static, marked with the Java transient modifier, annotated @DbTransient, or is a non-public final field without a mapping annotation, such as a PropertyIndex. A final field that does carry a mapping annotation fails the build, since nothing could write a loaded value into it.

30.1.1. Field-level annotations

AnnotationPurpose

@Id

Marks a primary-key field. The legacy DAO uses one key; managed sessions also support composite assigned keys. autoIncrement=true (the default) emits INTEGER PRIMARY KEY AUTOINCREMENT and back-fills the field after insert.

@Column(name)

Rename the column. Default: the field name in the app; on the backend the field name in snake case (fareCents → fare_cents), as Spring Boot names it.

@Column(type)

Override the SQL type. Default: inferred from the Java type (String → TEXT, int/long → INTEGER, float/double → REAL, boolean → INTEGER, java.util.Date → INTEGER (epoch millis), Instant, LocalDateTime → INTEGER (epoch millis), LocalDate → INTEGER (epoch day), byte[] → BLOB).

@Temporal

Stores a date or time field in a native date or time column instead of epoch milliseconds. See Section 30.3.7, “Native date and time columns”.

@Column(nullable=false)

Adds NOT NULL to the column declaration.

@DbTransient

Excludes the field from the table.

30.2. Use the dao

EntityManager is a thin façade over Database. The underlying connection is reachable through em.database() for raw SQL when the dao surface isn’t enough. Transactions:

em.beginTransaction();
try {
    users.insert(u1);
    users.insert(u2);
} catch (IOException e) {
    em.rollbackTransaction();
    throw e;
}
// outside the catch on purpose: a commit that fails has already ended
// the transaction, so rolling back here would throw "No transaction is
// in progress" over the top of the real failure
em.commitTransaction();

30.3. Managed sessions and relationships

The managed ORM layer uses the same entity annotations on the client and the backend. New mappings, including relationships, @Version, and @GeneratedValue, live in com.codename1.annotations.db. The existing @Entity, @Id, @Column, and @DbTransient annotations remain in com.codename1.annotations. Open a com.codename1.orm.session.Session with EntityManager.openSession(). Keep one session per unit of work. A session is not thread-safe; a backend pooled entity manager can still be shared between requests, with a separate session for each request.

The existing scalar Dao API keeps its immediate-write behavior. Entities using relationships, @Version, composite IDs, generated strategies, inheritance, converters, indexes, or embedded values use sessions; asking for a legacy DAO for these mappings throws an error rather than dropping managed behavior. That holds for record entities too: a record works with the Dao only while it has none of these.

A managed session maintains one instance per entity identity, detects changes at flush time, and flushes before commit and before queries in a transaction. persist, merge, and remove require an active transaction. merge returns the managed copy; it doesn’t attach the supplied detached instance. Merging an entity already scheduled for removal is rejected.

Session session = em.openSession();
try {
    session.beginTransaction();
    Customer customer = session.find(Customer.class, customerId);
    customer.name = "Updated name";
    session.commitTransaction();
} finally {
    session.close();
}

The public Session, Query, and JpqlQuery interfaces describe application operations. Generated metadata, field-access hooks, and SQL adapters live under com.codename1.impl.orm; application code shouldn’t depend on those classes.

Closing a session rolls back any active transaction. It never commits. A rollback clears the persistence context. An optimistic-lock or database failure requires rollback before the session can continue writing if the database still has an active transaction. When a failed client commit has already ended the underlying transaction, the session detaches its entities and becomes inactive. Check isTransactionActive() before rolling back; an inactive session can start a new transaction. Closing the session doesn’t close its entity manager’s database or pool. Backend Database.beginTransaction() reserves the connection to the initiating thread until commit, rollback, or close. Other threads wait; the initiating thread must finish the transaction.

30.3.1. Association mappings

Use @ManyToOne, @OneToOne, @OneToMany, and @ManyToMany on public entity fields. To-many fields use List<T>, Set<T>, or Map<K,T>. @JoinColumn names an owning foreign-key column. mappedBy identifies the owning field on the other entity. An owning to-many relationship uses a join table; @JoinTable customizes its name and key columns.

To-one relationships default to FetchType.EAGER; to-many relationships default to FetchType.LAZY. Override these defaults with the annotation’s fetch member. CascadeType selects the persistence operations to propagate. orphanRemoval=true removes children dropped from an initialized relationship. Application code maintains both sides of bidirectional object relationships. Removal cascades on inverse to-one and to-many relationships account for pending owning-side moves, including join-table changes, before choosing which children to remove.

The build enhances entity classes and field-access callers so a normal public field read can initialize a lazy relationship. No runtime proxy generator or reflection is needed. session.isLoaded(entity, "relationship") inspects load state without fetching; session.initialize(entity, "relationship") fetches explicitly. An unloaded relationship can’t be read after detaching its entity or closing its session: this throws LazyInitializationException. Generated @Mapped serialization code rejects unloaded associations rather than fetching them during serialization; initialize the relationships needed for the output first.

Fetching is synchronous. On the client, perform database work off the EDT and initialize the data needed by the UI before closing the session. Already-loaded data remains readable after the session closes.

30.3.2. Queries and counters

The session query builder uses Java field paths, including relationship paths:

List<Order> orders = session.query(Order.class)
    .eq("customer.name", "Alice")
    .orderBy("id", true)
    .limit(20)
    .fetch("customer")
    .list();

fetch overrides laziness for a direct relationship. To-one and inverse foreign-key collection fetches with single-column keys are batched. Ordered, map, composite-key, and join-table collections currently use individual loaders. Root pagination happens before loading fetched collections. query.count() counts matching entities without loading them and ignores pagination, ordering, and joins needed only by ordering. session.count(entity, "relationship") counts a relationship without materializing it.

createQuery accepts an explicit JPQL subset: entity or scalar selects, relationship joins, named parameters, comparisons and boolean predicates, aggregates, grouping/having, ordering, nested queries in scalar predicates, and bulk update/delete. String and numeric literals and named values become bound SQL parameters. IN :values and IN (:values) accept an Iterable or object array, including an empty collection. Unsupported syntax is rejected. Multiple scalar projections return Object[]. Entity names, field names, aliases, and named parameters accept Java identifier characters, including supplementary Unicode letters. Comparisons require at least one operand with a known storage type; two untyped parameters can’t be compared directly. IS NULL and IS NOT NULL also require a known operand type; a standalone untyped parameter is rejected. A scalar nested query requires an aggregate without GROUP BY, so it returns at most one row. IN and EXISTS may use queries that return multiple rows. Searched CASE WHEN predicate THEN value …​ ELSE value END and simple CASE expression WHEN value THEN value …​ ELSE value END work in scalar expressions, including SUM(CASE WHEN …​ THEN …​ ELSE …​ END). The first matching branch wins. An omitted ELSE yields SQL NULL; a NULL condition is not true, and simple CASE uses SQL equality (NULL doesn’t match NULL). Aggregates ignore NULL inputs; SUM over no non-null inputs yields NULL, while COUNT yields zero. Use a boxed scalar return type when NULL is possible.

Result branches must have compatible scalar storage types. Integral branches promote to Long when combined with Long literals; any real branch promotes the result to Double. At least one branch must have a known type; CASE with only untyped parameters or NULL branches is rejected. Entity and predicate result branches are unsupported; Boolean values and literals are supported. Converter mappings must agree across mapped result branches. Parameters in WHEN conditions and result branches remain bound parameters.

A DISTINCT query can order only by selected expressions. Text range comparisons and LIKE patterns are case-sensitive across supported databases. An explicit LIKE …​ ESCAPE uses a literal or named parameter for both the pattern and the escape character.

List<Order> orders = session.createQuery(
    "select o from Order o where o.customer.name = :name order by o.id",
    Order.class).setParameter("name", "Alice").list();

Bulk mutations use executeUpdate() inside a transaction. Repeated assignment targets are rejected during query creation. Aggregate functions are allowed inside scalar nested queries, but not directly in assignments or bulk predicates. On MySQL and MariaDB, nested queries that read the bulk mutation target table are rejected during query creation. They flush pending managed changes and bypass per-entity callbacks and cascades. As in JPA, they don’t clear the session: an entity it already manages stays managed and keeps the values it had before the statement, and a change made to it afterward is still written. Call refresh(entity) to read what the statement wrote, or clear() and read again. Bulk UPDATE doesn’t increment @Version either; increment the version field in the statement when concurrent edits must still conflict with it. An entity whose row a bulk DELETE removed fails with an OptimisticLockException if it’s changed or removed afterward. Bulk assignments to required subtype fields need a non-null literal or named parameter. Other assignment expressions are rejected for those fields. Literal and bound null assignments to primitive Java fields are rejected on both runtimes. Primitive assignments also reject expressions that may return null. Use COALESCE(expression, 0) to supply a non-null fallback for nullable numeric fields, division by a variable or zero, and nullable aggregate results. A scalar aggregate without GROUP BY or HAVING can be assigned directly when its result is non-null, such as COUNT or COALESCE(SUM(…​), 0). Parameters needed to keep an expression non-null are checked before execution. Field-to-field assignments require matching enum types and converter mappings, including fields inside expressions. Integral attributes reject real-valued assignment expressions and floating-point parameter values. Assignments also check the mapped integer range, including computed results and the narrower ranges of byte, short, and char fields. Builder predicates and JPQL parameters also check the mapped integer range. Assignments to float and Float reject finite overflow and nonzero results that would round to zero, including arithmetic expressions and nested query results. Floating-point literals that overflow or underflow double precision are rejected when the query is created.

An int or long field annotated @Version is maintained by the session. Updates and deletes compare its previous value and throw OptimisticLockException when another writer changed or deleted the row. session.increment(Entity.class, id, "counter", delta) performs database arithmetic, advances the version when present, and refreshes an already-managed instance. It returns false for a missing row or an increment outside the counter/version range. It requires a transaction and an int, Integer, long, or Long attribute without a converter, including properties holding those numeric types. Other values stored as integers, such as booleans and dates, aren’t counters. Invalid entity types, fields, or identifiers are rejected before pending changes are flushed.

Scalar field projections return the mapped Java values, including enums, dates, booleans, property values, and converter-backed objects. Integral SUM results use Long on every database, and AVG returns Double. Joined paths may end in embedded fields. LOWER, UPPER, TRIM, and ABS transform stored values. Their results and comparison operands use SQL storage values. These results can’t be assigned directly to a field with a converter. MIN, MAX, COALESCE, and NULLIF preserve compatible converter mappings. COALESCE field operands must share an enum type or converter mapping so the result can be decoded consistently. Field-to-field comparisons also require matching enum types and converter mappings. Scalar projections need a known storage type when the query is created. Bare parameters and expressions such as coalesce(:a,:b) are rejected. Association projections are also rejected; select an explicit field such as order.customer.id or select the relationship target as a root entity. Queries accept at most 999 bound parameters in total, including expanded IN lists. Larger lists are rejected before query execution. Generated key columns also have a combined limit of 3,072 bytes per key, counting up to four bytes per text character. This applies to primary keys, indexes, and collection keys, and is checked before schema creation. Explicit column type declarations remain the application’s schema contract. MySQL and MariaDB reject default binary primary keys and secondary indexes before schema creation; these keys need an explicit bounded column type declaration.

JPQL arithmetic requires numeric operands. Parameters in integral expressions must be integer values; use a real operand such as 1.0 for fractional arithmetic. Division of integral operands truncates toward zero on every database. Division and remainder by zero return null. Remainder accepts integral operands only. Integral addition, subtraction, multiplication, division, and negation fail if the result exceeds the signed 64-bit range, including in bulk assignments. Aggregate queries require each non-aggregate field to be covered by GROUP BY, including fields in HAVING and ORDER BY and outer fields referenced inside correlated nested queries. LENGTH counts characters on every backend.

30.3.3. Values and callbacks

@MappedSuperclass contributes its inherited fields to a concrete entity. @Embedded flattens an @Embeddable value into columns prefixed with the embedding field name. An all-null embedded value reads as null. Embedded fields can be used in query paths. Enums are stored by name. Mapped query parameters and literals accept the declared enum type, a valid constant name, or null. Invalid names and constants from other enum types are rejected before execution. Fluent and JPQL predicates require Boolean inputs for ordinary Boolean fields; fields with converters accept their declared domain values. Boolean values use numeric storage; native BOOL and BOOLEAN column declarations are rejected.

No-argument void instance methods can receive @PrePersist, @PostPersist, @PreUpdate, @PostUpdate, @PreRemove, @PostRemove, and @PostLoad callbacks, whatever their access: a private, protected, or package-private callback works, including one inherited from a mapped superclass in another package. The build weaves a static accessor for a non-public callback into the class that declares it, as it does for fields, so no reflection is involved. Static and abstract callback methods fail the build. Entities with lifecycle callbacks require openSession(), even without relationships or version fields. Relationships added by @PrePersist, @PostPersist, or @PreUpdate follow PERSIST cascades in the current flush, including newly created collections. Flush rechecks entries changed by later callbacks, including newly inserted rows, until the managed state matches the database. If callbacks keep changing state for 1,000 passes, flush fails and the transaction requires rollback.

Inherited callbacks run before subclass callbacks; overriding a callback method replaces the inherited declaration. Client scalar Property fields participate in dirty checking and counters. Backend entities use plain fields because the backend runtime doesn’t contain the client properties package.

@Convert(converter=CodeConverter.class, storageType=String.class) maps a custom basic value to a SQL scalar. The converter implements com.codename1.orm.session.AttributeConverter<Code,String> and has a public no-argument constructor. It receives null values too, including mapped JPQL NULL literals. Query-builder predicates and JPQL comparison parameters and literals apply the field’s converter. The builder converts values before choosing equality or SQL null predicates. JPQL and builder IS NULL tests also apply the mapped null conversion. A converter that stores null as a non-null sentinel uses a comparison with that sentinel. Values must match the converter’s input type; use a named parameter for custom objects. Identifiers and versions can’t use converters. This includes every component of an embedded identifier.

30.3.4. Identity and inheritance

Keep @Id for identity-column generation. Managed mappings require int, long, Integer, or Long identity fields; client IntProperty and LongProperty fields are supported too. Use @Id(autoIncrement=false) for assigned keys. @GeneratedValue selects UUID (for String IDs), SEQUENCE, or TABLE (for int/long IDs). PostgreSQL uses native sequences; other engines use a transactional generator table. UUIDs are version 4. Identity IDs become available on flush; the other strategies allocate on persist. Production migrations must provision the selected generators. Mappings with a cycle of required owning to-one links and identity-generated keys are rejected during processing: the first insert can’t supply every required key. SQLite and PostgreSQL support required cycles with keys assigned before insertion because their foreign keys are deferred until commit. MySQL and MariaDB enforce foreign keys immediately, so sessions reject required cycles before creating tables or writing data, even when the keys are known.

Identifier components are normalized and checked against their storage types before a cache lookup or SQL query, including the mapped integer range. Incompatible values raise IllegalArgumentException.

For composite IDs, use several @Id(autoIncrement=false) fields or one @EmbeddedId whose type is @Embeddable. Lookup accepts Identifier.of(component1, component2) in declared-field order; an embedded-ID mapping also accepts its key object. Relationships and join tables include all key components. Generated composite IDs are rejected.

@Inheritance on an entity root enables single-table inheritance, including abstract roots and polymorphic queries. @DiscriminatorValue("customer") assigns a stable discriminator to a concrete subtype. A base-class lookup and a subclass lookup return the same managed instance for the same row. A subtype query can’t address fields or relationships declared only by a sibling subtype. The physical table still includes the complete hierarchy for row loading. Use explicit discriminator values when class names may change. Every hierarchy member uses the root’s identifier generator, including its default generator name.

30.3.5. Lists, maps, and owned values

Owning Lists store positions in a list_position join-table column by default, so repeated many-to-many links and reordering survive reload. @OrderColumn can name that column explicitly. @OrderBy("name ASC, id DESC") orders an entity collection by target fields at load time; the position column still keeps repeated links distinct. An inverse mappedBy collection can use @OrderBy.

For an entity map, @MapKey(name="code") derives keys from a basic field on the target entity. The map key type must match that field’s Java type before conversion, using the boxed type for a primitive field. Keys must be non-null and unique in that collection. When changing the target key field, update the Java map keys as well.

@ElementCollection stores owned scalar values in a separate table. It supports List, Set, and Map with String keys. Values may be String, boxed primitive types, or java.util.Date. Lists preserve order and duplicate values. Map columns can be named with @MapKeyColumn; @JoinTable names the collection table and its owner column, and @ElementCollection(column=…​) names the value column. @ElementCollection(joinColumn=…​) names the owner column without a @JoinTable, and type=…​ sets the value column’s SQL type, such as LONGTEXT, the way @Column(type=…​) does. Names are quoted for you, so a name such as signal needs no backticks, and a name wrapped in backticks or double quotes has them removed. A List or Set table has an element_position column by default. @ElementCollection(positionColumn="") maps a Set to a table with no position column, keyed by owner and value, which is the usual shape of an existing tag table. Such a Set rejects null values, and its text values accept at most 255 Unicode code points. A Set of Double or Float keeps its position column: SQL treats 0.0 and -0.0 as one key, while a Java Set holds both. Element-map keys accept at most 255 Unicode code points on every database. query.containsElement("tags", "important") tests membership without loading the collection. Changing a mutable Date value is detected during flush.

30.3.6. Schema and locking

Run session.createTables() outside application transactions for development schemas. It creates missing entity/collection tables, primary and foreign keys, one-to-one uniqueness, and relationship indexes. @Column(unique=true) and @Entity(indexes=@Index(name="by_name", fields={"name"})) declare additional indexes. Generated text keys, indexed fields, and foreign keys accept at most 255 Unicode code points during managed inserts, updates, and bulk assignments on every database. Specify @Column(type=…​) to control the SQL type and its value limits yourself.

session.schemaReport() compares the mappings with the tables that exist and returns a SchemaReport. It reads the database and never changes it. Each issue has one of three kinds:

KindMeaning

MIGRATION_REQUIRED

A table or column the mapping needs is missing. A migration that adds it fixes the issue.

UNSUPPORTED

The column exists, but the mapping can’t use it as it is: a storage type that would need a conversion, such as a plain Date field over a TIMESTAMP column, or a primary key that differs from the mapping. Change the mapping, or convert the column.

CONSTRAINT_MISMATCH

The column’s NOT NULL differs from the mapping, or a NOT NULL column the mapping doesn’t write has no default. A column stricter than its mapping is a legitimate design. A missing NOT NULL lets a row hold a null that a primitive field can’t load.

session.validateSchema() runs the same checks and throws a PersistenceException whose message is the report. These calls don’t migrate schemas or check every database-specific constraint. Existing tables are left to migrations, which EntityManager.open(name) applies before it returns. In particular, a legacy client DAO’s text char columns need migration to the managed layer’s numeric UTF-16 storage when moving to a managed schema.

A backend server validates the schema at startup, after migrations and cn1.orm.createTables, and refuses to start on a MIGRATION_REQUIRED or UNSUPPORTED issue, so a mapping the database can’t serve fails before the first request rather than on the requests that touch it. It also refuses a CONSTRAINT_MISMATCH that would fail at runtime: a missing NOT NULL, or a required column the mapping doesn’t fill. A column stricter than its mapping is only logged. Set cn1.orm.validateSchema=false to start anyway.

30.3.7. Native date and time columns

A java.util.Date field is stored as epoch milliseconds in an integer column by default, and that mapping doesn’t change. @Temporal opts a field into a native column instead:

AnnotationPostgreSQLMySQL/MariaDBSQLite

@Temporal(TemporalType.TIMESTAMP)

TIMESTAMP(3)

DATETIME(3)

TIMESTAMP, stored as text

@Temporal(TemporalType.DATE)

DATE

DATE

DATE, stored as text

A Date is an instant, and a temporal column holds it in UTC: the backend connects with its session time zone set to UTC on both PostgreSQL and MySQL, so the server’s own time zone never shifts a value. Precision is milliseconds, which is all a Date carries; digits beyond that read from an existing column are dropped toward the earlier instant. A DATE column holds the UTC day, and reads back as midnight UTC. SQLite has no date type, so it stores 2024-02-29 13:45:06.789 and 2024-02-29 as text, which sorts in time order. Writes outside the years 1000 to 9999 (MySQL’s range), zero dates, and other values the column can’t represent exactly are rejected rather than converted. A value whose text carries a time-zone offset, such as one read from a PostgreSQL timestamptz column, reads as the instant it names.

java.time.Instant, LocalDate, and LocalDateTime fields map without an annotation, to the same portable integer columns:

Field typeDefault columnWith @Temporal

Instant

epoch milliseconds, the same value a Date or a long of System.currentTimeMillis() holds

TIMESTAMP

LocalDateTime

milliseconds since 1970-01-01T00:00 of the wall clock, with no zone applied

TIMESTAMP, the wall clock as written

LocalDate

days since 1970-01-01

DATE

Because an Instant stores the same number, changing a long or Date field of epoch milliseconds to an Instant reads the rows already in the table. Pass an Instant, LocalDate, or LocalDateTime as the query parameter for one of these fields, not a number. Precision is milliseconds, as for a Date; finer digits are dropped on write. A LocalDate takes only @Temporal(TemporalType.DATE) and the other two only TIMESTAMP. LocalTime, OffsetDateTime, and ZonedDateTime aren’t mapped; store an Instant and keep the zone in its own field when it matters.

@Temporal applies to entity fields of type java.util.Date, Instant, LocalDate, and LocalDateTime. It can’t be combined with @Convert, used on an identifier or version, or applied to element-collection values. A field with @Temporal requires openSession(). An explicit @Column(type) on one must name a matching date type, such as TIMESTAMP(3) or DATE, or TEXT. Queries order and compare the field as a date, so LIKE and the text functions don’t apply to it. The schema report marks a DATE column under a TIMESTAMP mapping, or the reverse, as UNSUPPORTED, because one of them drops the time of day.

30.3.8. Adopting an existing schema

Explicit names map an entity onto tables that existed before the application. This entity uses a key the database generates, native timestamp and date columns, a legacy epoch-milliseconds column, and a tag table:

@Entity(table = "legacy_customer")
public class LegacyCustomer {
    @Id @Column(name = "customer_no")
    private long id; (1)

    @Column(name = "full_name", nullable = false)
    private String name;

    @Temporal(TemporalType.TIMESTAMP) @Column(name = "signed_up")
    private Date signedUp; (2)

    @Temporal(TemporalType.DATE)
    private Date birthday;

    @Column(name = "last_seen")
    private Date lastSeen; (3)

    @ElementCollection(column = "tag", positionColumn = "")
    @JoinTable(name = "legacy_customer_tag", joinColumn = "customer_no")
    private Set<String> tags = new HashSet<String>(); (4)

    @PrePersist
    private void defaults() { (5)
        if (signedUp == null) {
            signedUp = new Date();
        }
    }

    public long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getSignedUp() {
        return signedUp;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public Date getLastSeen() {
        return lastSeen;
    }

    public void setLastSeen(Date lastSeen) {
        this.lastSeen = lastSeen;
    }

    public Set<String> getTags() {
        return tags;
    }
}
1@Id defaults to autoIncrement=true, so the existing BIGSERIAL, AUTO_INCREMENT, or INTEGER PRIMARY KEY column assigns the key, and @Column keeps its name.
2A native TIMESTAMP(3) or DATETIME(3) column.
3An existing BIGINT column of epoch milliseconds keeps the default mapping.
4A legacy_customer_tag (customer_no, tag) table keyed by both columns.
5Callbacks and fields can stay private.

Leave cn1.orm.createTables off for adopted tables, and check session.schemaReport() against the real database before the first deployment.

Backend sessions support find(type, id, LockMode.PESSIMISTIC_READ) and PESSIMISTIC_WRITE, or lock(entity, mode), inside a transaction. PostgreSQL and MySQL/MariaDB use their row-lock clauses. SQLite rejects these modes explicitly; it can’t provide row-level pessimistic locks. Invalid or unsupported lock modes are rejected before pending changes are flushed.

30.3.9. Supported boundary

This API provides managed persistence through CN1 annotations; it’s not a JPA provider or a Hibernate binary replacement. Entity access is by field, whether the field is public or private; a record entity is read through its accessors and built through its canonical constructor. Getter/setter access mappings aren’t supported: a private field already keeps the entity encapsulated, and reading a field directly is what lets the build generate the access code without reflection. Property-backed associations, joined/table-per-class inheritance, embeddable element collections, and independently stored entity-map keys aren’t supported. Nested fetch graphs and mixed entity/scalar JPQL projections are also outside the current query subset. Use the builder’s count() for distinct composite identities. Native device execution and each backend database version still require application integration testing.

30.4. Record entities

An @Entity can be a Java record. A record can’t change after it’s built, so you never edit a managed record in place: you build a changed copy and save it, and the session answers the copy that it now manages. That copy carries what the database assigned, such as a generated key or a new version. The same mappings work on the client and the backend, and nothing is woven into a record: the build reads it through its accessors and builds it through its canonical constructor.

@Entity
public record Note(@Id long id, String title, int score,
        @Version long version, @DbTransient String scratch) {
    public Note {
        if (score < 0) {
            throw new IllegalArgumentException("score");
        }
    }
}

Every component is persistent unless it’s @DbTransient, and @Column, @Id, @Version, @Convert, @Temporal and the other field annotations go on the component. A compact constructor runs for every instance the ORM builds, including the rows it reads, so it can validate them. A record entity can’t declare a Property component: a property is a mutable holder, which is what a record avoids. Declare the value’s own type instead.

30.4.1. Builders

For every record entity the build generates a builder named after it, in the same package: NoteBuilder for Note. create() starts from default component values, of(note) copies every component of an existing record, each setter replaces one component, and build() calls the canonical constructor. The builder is plain Java over the record’s public API, so you can also write your own withScore-style methods on the record and never use it.

Your own code calls the builder, so it has to exist while that code compiles. The codenameone-annotation-processor artifact writes it from inside javac. New projects run it already, and a Gradle build gets it from the Codename One plugin. A Maven project created before it existed needs it added to the compiler’s annotationProcessorPaths, at the plugin’s version: com.codenameone:codenameone-annotation-processor:${cn1.plugin.version}.

Notes notes = Repositories.create(Notes.class, session);
session.beginTransaction();
Note draft = NoteBuilder.create().title("Groceries").score(3).build();
Note saved = notes.save(draft);       // saved.id() is the generated key
Note changed = notes.save(NoteBuilder.of(saved).score(5).build());
session.commitTransaction();

30.4.2. Saving a record

Use merge, or a repository’s save, which calls it, and keep working with the record it returns:

  • The record you pass in is never changed or managed. After the save above, draft.id() is still 0, session.contains(draft) is false and session.contains(saved) is true.

  • The returned copy is what the session’s identity map holds: session.find(Note.class, saved.id()) answers saved, and after the second save it answers changed.

  • Saving a copy is an update of the components that differ from the managed record’s, and it increments the @Version. A copy built from a record that a later save has replaced is stale: saving it again fails with OptimisticLockException, exactly like a stale detached object.

  • @DbTransient components travel with every copy the session builds, so the managed copy keeps the value you set; a record read from the database has the component’s default.

persist works too, but it returns nothing: the session manages the record you pass in until it inserts the row, and then replaces it with the copy that holds the key. Use merge or save when you need that copy, or find the record again by its key. refresh, remove, detach and queries work as they do for any entity; refresh replaces the managed record with a copy that holds the row’s current values, so read the result through find afterward.

The plain Dao API answers the copy too: dao.save(draft) returns the record with its generated key. Like any other entity, a record works with the Dao only while it has no @Version, relationship, embedded value or other mapping that needs a session; Note above needs one.

30.4.3. Relationships

A record can’t be given a relationship after it’s built, so each kind of relationship is a component whose type holds it:

RelationshipComponent typeBehavior

Lazy to-one

Ref<T> (com.codename1.orm.Ref)

Read on first get(). id() and isPresent() never run a query.

Eager to-one

Optional<T>

Read together with the row.

To-many

List<T> or Set<T>

A session collection, read on first use and changed in place.

Element collection

List<V> or Set<V> with @ElementCollection

The same, holding values.

@Entity
public record Customer(@Id long id, String name) {}
@Entity
public record Purchase(@Id long id, String code,
        @ManyToOne(cascade = CascadeType.PERSIST) Ref<Customer> customer,
        @ManyToOne Optional<Customer> reviewer,
        @OneToMany(mappedBy = "purchase") List<Line> lines,
        @ElementCollection Set<String> tags,
        @Version long version) {}
@Entity
public record Line(@Id long id, String label,
        @ManyToOne Ref<Purchase> purchase) {}

A Ref is lazy unless the annotation says fetch = FetchType.EAGER, even though @ManyToOne and @OneToOne default to eager: reading on first use is what a Ref is for. An Optional is always read with the row, so a lazy Optional fails the build. A record holding the entity type itself, a Map relationship, and a Ref in a class entity fail the build too, each with a message naming the component.

Reading:

Purchase p = session.find(Purchase.class, id);
Object customerKey = p.customer().id();          // no query
boolean hasOne = p.customer().isPresent();       // no query
String name = p.customer().get().name();         // reads the customer now
String reviewer = p.reviewer().map(Customer::name).orElse("nobody");
int lines = p.lines().size();                    // reads the lines now

The inverse side of a one-to-one, @OneToOne(mappedBy = "user") Ref<Profile> profile, is the exception: the record’s own row stores no key for it, so its id() and isPresent() read the target too.

isLoaded() says whether a Ref was read already. A Ref or a collection that was never read can’t be read once its session is closed or the record is detached: get() throws LazyInitializationException, while id() keeps answering. Two refs are equal when they point at the same entity type and key, so p.customer().equals(Ref.of(customer)) compares targets without reading either.

Changing a to-one relationship is a copy with another Ref or Optional, and saving it updates the foreign key and the version:

Customer ada = session.find(Customer.class, adaId);
Purchase moved = session.merge(PurchaseBuilder.of(p)
        .customer(Ref.of(ada))
        .reviewer(Optional.empty())
        .build());

Ref.empty() and Optional.empty() hold no target. A to-many collection, or an element collection, is changed in place on the managed record, as on a class entity: p.tags().add("gift") is saved at flush. When you build a new record, give it a collection you create, such as new ArrayList<>(), and the session puts its own collection in the managed copy. A copy saved over an existing row replaces each collection it carries: build changes with PurchaseBuilder.of(managed), which keeps the managed collections. A collection left null in the copy is saved as empty, as a merged class entity’s is: its join rows are removed and, under orphanRemoval, its children are deleted.

A cascade reaches through a Ref or an Optional. A purchase built with Ref.of(newCustomer) and saved under CascadeType.PERSIST inserts the customer once, and the managed purchase’s Ref holds the customer’s managed copy, which carries its generated key. Point a Ref at a managed record, a find result or a merge result, unless a cascade is meant to save the target: a detached record without a cascade is rejected at flush, the same as for a class entity.

30.4.4. Embedded values

A record entity embeds values that are records too, annotated @Embeddable. Their components become columns named after the path, as for class entities, and an embedded record can embed another one:

@Embeddable
public record Geo(double lat, double lng) {}
@Embeddable
public record Address(String street, String city, @Embedded Geo geo) {}
@Entity
public record Venue(@Id long id, String name,
        @Embedded Address home, @Embedded Address billing,
        @Version long version) {}

The Venue table has home_street, home_city, home_geo_lat, home_geo_lng, and the same four billing_ columns. A value whose columns are all null reads back as null, at any depth: a billing address saved as new Address("PO 7", null, null) reads back with a null geo. Query an embedded component by its path:

List<Venue> local = session.query(Venue.class)
        .eq("home.city", "Springfield").list();

Venue moved = session.merge(VenueBuilder.of(venue)
        .home(new Address("2 Elm", "Springfield", new Geo(1.5, 2.5)))
        .build());

Changing an embedded value is a copy with a new value, and it bumps the version like any other change; the old copy keeps its old value. Setting the component to null clears its columns.

An embedded value in a record entity must be a record, and a record embeddable can only be embedded in a record entity. A class embeddable is writable, and the copies of a record would share it: changing it through one copy would change every other copy too, and the session’s snapshot of it with them. Both mistakes fail the build with a message naming the component.

30.4.5. What records require

Records need the application’s sources compiled at Java 17, the bytecode level Codename One builds. The build translates a record’s generated equals, hashCode and toString for every target, so records also run on iOS and the other translated targets. Relationships inside an embedded record aren’t supported, for records or classes.

30.5. Validation

The annotation processor fails the build when:

  • @Entity lands on an interface, or an abstract entity has no @Inheritance root.

  • A concrete entity has no public no-arg constructor.

  • No identifier is mapped, or a composite identifier requests generated values.

  • Persistent column/table/index names conflict, or mappedBy doesn’t resolve.

  • A field’s static type or relationship mapping is unsupported.

Errors are accumulated so the first build run reports every offending entity at once.

30.6. How the plumbing works

cn1:process-annotations writes one <SimpleName>Cn1Dao per @Entity in the source class’s package (com.example.UserCn1Dao next to com.example.User), plus a single cn1app.DaoBootstrap whose constructor calls UserCn1Dao.register(), OrderCn1Dao.register(), …​ for every accepted @Entity class. At app start:

  • On iOS / Android the build server probes the project zip for cn1app/DaoBootstrap.class and splices new cn1app.DaoBootstrap(); into the per-build application stub before Display.init. ParparVM rename and R8 obfuscation rewrite the call site and the generated dao together, so the direct symbol reference stays valid after the pass.

  • On the JavaSE simulator and desktop run JavaSEPort#postInit loads the bootstrap via Class.forName("cn1app.DaoBootstrap"). Class-loading is the legitimate path here — JavaSE runs unobfuscated.

Projects with no @Entity classes produce no bootstrap; the build server probe falls through and the registry stays empty.

The runtime registry is keyed on Class#getName(); obfuscation renames the call sites and the registered keys together within a single execution. The keys are never persisted across builds, so the renaming has no observable effect on behavior.

30.7. Generated repositories

A public top-level interface annotated with com.codename1.orm.repository.Repository and extending CrudRepository<Entity, Key> directly gets an InterfaceNameCn1Repository implementation during cn1:process-annotations. Both class literals are explicit; the key must match the mapped identifier’s boxed type (the embedded key class or Identifier for composite keys). Use Repositories.create(Records.class, session) to obtain an implementation. This factory references the interface, so application sources compile on a clean build before process-classes generates the implementation. The generated DAO bootstrap registers direct factories alongside the entity mappings. The implementation makes direct session calls. There is no runtime classpath scan, proxy generation, or Hibernate dependency.

@Repository(entity=RepositoryRecord.class, key=Long.class)
public interface Records extends CrudRepository<RepositoryRecord, Long> {
    List<RepositoryRecord> findByNameAndScoreGreaterThanOrderByScoreDescIdAsc(String name, long score, PageRequest page);
    boolean existsByName(String name);
    long countByName(String name);
    int deleteByName(String name);
    @Lock(LockMode.PESSIMISTIC_WRITE)
    RepositoryRecord findById(Long id);
    @Query("select sum(case when r.score>=:floor then 1 else 0 end) from com.codenameone.developerguide.snippets.repository.RepositoryRecord r")
    Long qualified(@Param("floor") long floor);
    @Query(value="SELECT COUNT(*) FROM repository_records WHERE name=:name OR name=:name", nativeSql=true)
    Long nativeCount(@Param("name") String name);
    @Modifying
    @Query("update com.codenameone.developerguide.snippets.repository.RepositoryRecord r set r.score=:score where r.name=:name")
    int revise(@Param("name") String name, @Param("score") long score);
}

The example’s RepositoryRecord entity has @Id public long id, public String name, and public long score. This operation opens a session, creates its repository, commits the insert, and closes the session:

    public void insertRecord(EntityManager entityManager) {
        Session session = entityManager.openSession();
        Records records = Repositories.create(Records.class, session);
        session.beginTransaction();
        try {
            RepositoryRecord record = new RepositoryRecord();
            record.name = "open";
            records.insert(record);
            session.commitTransaction();
        } catch (RuntimeException error) {
            session.rollbackTransaction();
            throw error;
        } finally {
            session.close();
        }
    }

The inherited CRUD methods are insert, save, findById, findAll, count, existsById, and deleteById. insert calls persist; save calls merge and returns the managed instance, which may differ from the argument. findById returns null for a missing row. deleteById removes a managed entity and observes its cascades and callbacks; deleting a missing key is a no-op in an active transaction.

Derived methods support the following bounded grammar:

  • findBy, findFirstBy, findTopBy, findFirstNBy, and findTopNBy return the entity, Optional<Entity> or List<Entity>. A single result means the first row, not a uniqueness assertion; an entity return answers null when there is no row, and an Optional answers Optional.empty(). A declared @Query select can return Optional of its scalar the same way.

  • countBy returns long; existsBy returns boolean; deleteBy returns int (affected rows) or void.

  • Direct scalar property names combine with And and Or; AND has higher precedence than OR. Comparison suffixes are Not, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual, Before, After, Between, Like, and In. Between takes two parameters. IgnoreCase after a text property compares both sides in lower case. No suffix means equality. IsNull, IsNotNull, True, and False consume no parameter. In takes an Iterable or object array whose concrete element type matches the property. Raw and wildcard collections are rejected at build time. Like requires String properties with text storage. True and False require Boolean properties with Boolean storage. Use IsNull to match NULL; equality retains SQL NULL semantics.

  • Find methods can end with OrderByScoreDescIdAsc; every field needs an explicit Asc or Desc. Relationship paths and ambiguous property names containing grammar keywords should use @Query instead.

  • A list select can take one final PageRequest(offset, size). Offset must be nonnegative and size positive. It returns the requested list without a separate total-count query. Use explicit ordering with a unique tie-breaker for stable pages. Top/First and PageRequest aren’t combined.

@Query declares the existing JPQL subset. Every value argument requires a unique @Param("name") matching the query exactly. SQL values are bound, never interpolated. @Modifying is required for declared UPDATE/DELETE and forbidden for SELECT. Such methods return int or void. They behave like executeUpdate(): pending changes are flushed first, and the session is left unchanged, so an entity the caller read before the call is still managed and a change made to it afterward is written. @Modifying(clearAutomatically = true) empties the session after the statement instead, so what’s read next comes from the database; an entity read before the call is then detached, and nothing written to it later reaches the database. flushAutomatically is accepted for compatibility with Spring Data and changes nothing, because the flush always happens. A derived deleteBy method is a bulk DELETE too and leaves the session the same way. Native SQL uses @Query(value="…​", nativeSql=true) with the same named parameters, including repeated occurrences. Native parameters accept primitive and boxed scalar types, String, Date, BigInteger, BigDecimal, and byte[] BLOBs. Date values bind as epoch milliseconds and Character values as numeric code units on both client and backend. Collections and other array types are rejected during generation. Native repository selects return one scalar column of String, Long, Integer, Double, or Boolean, or a List of that type. They don’t hydrate entities. Scalar conversion rejects fractional values requested as integers and integer values requested as String; it preserves SQL NULL. Native SQL is database-specific: use portable SQL or validate each engine. Only SELECT, UPDATE, and DELETE are accepted; comments, multiple statements, positional parameters, dollar quoting, and backtick quoting are unsupported. Use standard quotes and bind values containing backslashes.

Unsupported signatures, unmapped derived fields, and missing or surplus declared parameter names produce build errors naming the repository and method. JPQL syntax and mapped names are validated when the method creates its query, before SQL execution. Native SQL syntax beyond the supported envelope is checked by the database. Generic methods, additional parent interfaces, default methods, dynamic sort arguments, and arbitrary DTO projections aren’t supported.

Repositories never open, commit, roll back, or close transactions or sessions. The caller owns those boundaries, including when the supplied Session is injected into a backend @Transactional service. Writes require an active usable transaction. Reads follow Session’s automatic flush rules. Put @Lock on findById(Key), a derived find or a declared @Query select to request a lock; counts, existence checks, deletes and modifications refuse it at build time; pessimistic locks need an active transaction and an engine supporting row locks. SQLite rejects them explicitly.

Derived deletes and declared JPQL/native modifications flush pending changes and execute bulk SQL. They don’t clear the session unless the method is annotated @Modifying(clearAutomatically = true). Derived deletes can’t take @Modifying, so call clear() yourself after one when you need it. Objects read before the call keep their old Java values: refresh them, or clear() and read again, to see what an UPDATE wrote, and don’t change an entity whose row a DELETE removed. Bulk modifications bypass entity callbacks, cascades, and automatic optimistic-version updates. As in JPA, a bulk UPDATE doesn’t increment @Version, so another session holding the old version can overwrite the bulk UPDATE’s change without an OptimisticLockException. When that matters, increment the @Version field in the statement itself, for example SET …​, e.version = e.version + 1 (in native SQL, the version column). Validation failures remain IllegalArgumentException; database failures remain PersistenceException, and optimistic conflicts remain OptimisticLockException. Repository code neither swallows nor retries them. Roll back after a failed database write; Session marks the transaction rollback-only. Rollback detaches entities without reverting Java field values.

31. Media and Audio

31.1. MediaManager and MediaPlayer

MediaPlayer is a peer component, understanding this is crucial if your application depends on such a component. You can learn about peer components and their issues here.

The MediaPlayer allows you to control video playback. To use the MediaPlayer you need to first load the Media object from the MediaManager.

The MediaManager is the core class responsible for media interaction in Codename One.

You should also check out the Capture class for things that aren’t covered by the MediaManager.

In the demo code below you use the gallery functionality to pick a video from the device’s video gallery:

final Form hi = new Form("MediaPlayer", new BorderLayout());
hi.setToolbar(new Toolbar());
Style s = UIManager.getInstance().getComponentStyle("Title");
FontImage icon = FontImage.createMaterial(FontImage.MATERIAL_VIDEO_LIBRARY, s);
hi.getToolbar().addCommandToRightBar("", icon, (evt) -> {
    Display.getInstance().openGallery((e) -> {
        if(e != null && e.getSource() != null) {
            String file = (String)e.getSource();
            try {
                Media video = MediaManager.createMedia(file, true);
                hi.removeAll();
                hi.add(BorderLayout.CENTER, new MediaPlayer(video));
                hi.revalidate();
            } catch(IOException err) {
                Log.e(err);
            }
        }
    }, Display.GALLERY_VIDEO);
});
hi.show();
Video playback running on the simulator
Figure 243. Video playback running on the simulator
Video playback running on an Android device. Notice the native playback controls that appear when the video is tapped
Figure 244. Video playback running on an Android device. Notice the native playback controls that appear when the video is tapped
Video playback in the simulator will work with JavaFX enabled. This is the default for Java 8 or newer so recommend using that.

31.2. PCM Audio Buffers, Mixing, and Effects

AudioBuffer stores raw interleaved float PCM samples in the [-1, 1] range, and WAVWriter writes those samples to a WAV file.

The portable live PCM source in Codename One is microphone capture: create an AudioBuffer with MediaManager.getAudioBuffer(…​), then create a recorder with MediaRecorderBuilder.redirectToAudioBuffer(true). The builder’s path value is the buffer key in this mode; it isn’t a file path.

String bufferKey = "voice-buffer";
AudioBuffer livePcm = MediaManager.getAudioBuffer(bufferKey, true, 8192);
livePcm.addCallback(buffer -> {
    float[] frame = new float[buffer.getSize()];
    buffer.copyTo(frame);
    // Process or copy this frame before the next callback arrives.
});

Media recorder = MediaManager.createMediaRecorder(
        new MediaRecorderBuilder()
                .path(bufferKey)
                .samplingRate(44100)
                .audioChannels(1)
                .redirectToAudioBuffer(true));
recorder.play();

// Later:
recorder.cleanup();
MediaManager.releaseAudioBuffer(bufferKey);

When the VideoIO API is available, it can also produce PCM from a prerecorded video file. VideoIO.getVideoIO().openReader(path).readAudio() returns the decoded audio track as an AudioBuffer, so video audio can be mixed or processed with the same APIs shown below. VideoIO support is platform-gated with VideoIO.isSupported(), and JavaScript currently reports no decoded audio track even though frame decoding and encoding are supported.

Codename One still doesn’t expose a standalone portable decoder that converts an arbitrary prerecorded audio-only file, such as MP3 or AAC, into an AudioBuffer without going through a video container API. Use the normal Media APIs to play those files. If you need offline PCM editing for audio-only formats, decode them before passing samples to Codename One, or add a platform decoder API for that format.

When you need to combine PCM clips before writing or playing them, use AudioMixer. It creates a sample-accurate timeline on one sample clock. Each track must use the same sample rate and channel count as the mixer. Track offsets are supplied in milliseconds and are rounded to the nearest sample frame on the mixer clock; if you already know the exact frame position, use addTrackAtFrame(…​).

The mixed buffer is clipped to the normalized PCM range [-1, 1], so it can be passed directly to WAVWriter. The mixer doesn’t resample or convert channel layouts; downsample or otherwise convert source buffers before adding them if they’re not already on the target clock.

AudioEffects provides small platform-neutral PCM transforms that compose with the mixer:

AudioBuffer voice = AudioEffects.normalize(livePcm, 0.9f);
AudioBuffer brighter = AudioEffects.equalize(voice,
        0.8f,  // low band gain
        1.0f,  // mid band gain
        1.25f  // high band gain
);

AudioBuffer karaoke = AudioEffects.removeCenter(stereoMusic);
AudioBuffer centeredSpeech = AudioEffects.isolateCenter(stereoInterview);
AudioBuffer voiceEnhanced = AudioEffects.midSide(stereoInterview, 1.4f, 0.6f);

equalize(…​) is a simple three-band tone shaper for lightweight cleanup and demos. removeCenter(…​), isolateCenter(…​), and midSide(…​) use classic stereo mid/side processing. They can reduce, isolate, or enhance centered dialog only when the source is stereo and the voice is actually centered. These methods aren’t source-separation, speech-isolation, or noise-reduction APIs.

AudioMixer and the simple buffer-wide AudioEffects operations use the com.codename1.util.Simd float-array API internally when the current platform supports it. Stateful filters, such as the equalizer, stay scalar because each sample depends on the previous filter state. You can force scalar behavior for diagnostics with AudioMixer.setSimdOptimizationsEnabled(false) or AudioEffects.setSimdOptimizationsEnabled(false).

32. Video encoding & decoding (VideoIO)

The VideoIO API is to video what the ImageIO API is to still images, but it goes deeper. It uses the platform’s native codecs to:

  1. Encode application rendered frames and audio into a standard video file, with deep control over dimensions, frame rate, codec, bitrate, key frame interval and the audio track.

  2. Decode an existing clip into frame accurate RGBA frames and PCM audio.

The decode side is something the Media player API doesn’t provide. Media is a player: its setTime() snaps to key frames and gives no exact frame guarantee. VideoReader, by contrast, decodes the precise frame at a requested time, which is what you need when you want to read an imported clip (for example a screen recording) frame by frame.

VideoIO is supported on iOS, macOS, Android, Windows, Linux, JavaScript and the desktop simulator. It’s not available on the TV, Watch or Car targets.

32.1. Checking for support

As with other optional platform features, always gate usage with isSupported():

if (!VideoIO.isSupported()) {
    // Video encoding / decoding is not available on this platform
    // (for example TV, Watch or Car), so fall back gracefully.
    return;
}
VideoIO io = VideoIO.getVideoIO();
On the desktop simulator VideoIO is backed by an ffmpeg/ffprobe binary. The simulator bundles one automatically; if isSupported() returns false on the desktop, make sure ffmpeg is on your PATH or set the ffmpeg.dir system property.

32.2. Encoding a video

Build a VideoWriter with a VideoWriterBuilder, then push frames and (optionally) audio. Because every frame is an ordinary Image that you draw into, you have complete control over the pixels - render charts, overlays, transformed camera frames, generated animation, anything.

String out = FileSystemStorage.getInstance().getAppHomePath() + "/generated.mp4";
int w = 640, h = 480;
float fps = 30;

VideoWriter writer = new VideoWriterBuilder()
        .path(out)
        .width(w).height(h).frameRate(fps)
        .videoCodec(VideoIO.CODEC_H264).videoBitRate(4_000_000)
        .build();

// Each frame is just an Image you fully control: draw whatever you like.
for (int i = 0; i < 90; i++) {                 // 3 seconds at 30fps
    Image frame = Image.createImage(w, h, 0xff000000);
    Graphics g = frame.getGraphics();
    g.setColor(0xffffff);
    g.fillRect((i * 8) % w, h / 2 - 20, 60, 40);
    writer.writeFrame(frame, Math.round(i * 1000f / fps));
}
writer.close();

To add an audio track, enable it on the builder (.hasAudio(true)) and push interleaved 16 bit PCM with VideoWriter.writeAudio(…​), or hand it an AudioBuffer.

32.3. Decoding a video frame by frame

VideoReader exposes the clip’s duration, dimensions and frame rate, a frame accurate frameAt(long) and a variable-to-constant frame rate resampler readFrames(fps, callback) that walks the whole clip emitting evenly spaced frames:

VideoReader reader = VideoIO.getVideoIO().openReader(videoPath);
System.out.println(reader.getWidth() + "x" + reader.getHeight()
        + " " + reader.getFrameRate() + "fps, "
        + reader.getDurationMillis() + "ms");

List<Image> thumbnails = new ArrayList<>();

// Frame accurate single frame (unlike Media.setTime which snaps to key frames):
VideoFrame oneSecond = reader.frameAt(1000);
if (oneSecond != null) {
    thumbnails.add(oneSecond.toImage());
}

// Resample the (possibly variable frame rate) clip to a constant 10fps stream:
reader.readFrames(10, f -> {
    // f.getARGB() / f.toImage() give you the decoded RGBA pixels
    thumbnails.add(f.toImage());
    return thumbnails.size() < 50;   // stop after 50 frames
});
reader.close();

The audio track, when present, is decoded to interleaved PCM:

VideoReader reader = VideoIO.getVideoIO().openReader(videoPath);
if (reader.hasAudio()) {
    AudioBuffer pcm = reader.readAudio();
    System.out.println("Decoded " + pcm.getSize() + " PCM samples at "
            + reader.getAudioSampleRate() + "Hz, "
            + reader.getAudioChannels() + " channels");
}
reader.close();

32.4. Discovering available codecs

The set of codecs is device dependent. Enumerate it to pick the best one (and to detect hardware accelerated encoders):

VideoIO io = VideoIO.getVideoIO();
for (VideoCodec codec : io.getAvailableEncoders()) {
    System.out.println(codec.getId()
            + " (" + codec.getName() + ")"
            + (codec.isHardwareAccelerated() ? " [hardware]" : ""));
}
boolean canEncodeH264 = io.isEncoderSupported(VideoIO.CODEC_H264);

32.5. Platform support

PlatformBackend

iOS / macOS

AVFoundation (AVAssetReader / AVAssetWriter, hardware H.264/HEVC)

Android

MediaCodec + MediaMuxer / MediaExtractor + MediaMetadataRetriever

JavaScript

HTML5 <video> + <canvas> decode + WebCodecs encode

Windows

Media Foundation (IMFSourceReader / IMFSinkWriter)

Linux

GStreamer (appsrc / appsink)

Simulator

ffmpeg / ffprobe

TV / Watch / Car

Not supported (isSupported() returns false)

33. Video capture constraints API

The new video capture constraints API allows you to specify "constraints" when capturing videos. Constraints include:

  1. Video Quality (High or Low)

  2. Maximum duration

  3. Most file size

  4. Video Resolution (that is, width and height).

Support for these constraints vary by platform and device, but the API allows you to check if your constraints are supported at runtime. Essentially, you set your "preferred" constraints, and the API will give you its best try at meeting those constraints. This is like setting a visual Component’s preferred width and height. The layout manager takes these preferred dimensions under advisement, but sets the size on its own.

33.1. Example 1: Capturing a Low-Quality 5-Second clip

Suppose you want to allow the user to capture a short (5 second) clip, in a low resolution, appropriate for sharing on a social media platform. You create your VideoCaptureConstraints object as follows:

// The original wrote "new VideoCaptureConstraint()" -- a class that does
// not exist. Corrected while restoring it: a snippet that cannot compile is
// worse than no snippet.
VideoCaptureConstraints cnst = new VideoCaptureConstraints()
    .preferredQuality(VideoCaptureConstraints.QUALITY_LOW)
    .preferredMaxLength(5);

This constraint can then be passed to Capture.captureVideo() to get the captured file:

String videoPath = Capture.captureVideo(cnst);

33.2. Not all platforms support all constraints

How do you know whether your constraints will be honored? When the platform doesn’t support the maximum length, you may want to take a different path. Ask the constraint object whether it’s supported.

For example:

if (cnst.isMaxLengthSupported()) {
    // The max length constraint we specified is supported on this platform.
} else {
    // It is not. Check the effective value to see whether it is partially
    // supported.
    int effectiveMaxLength = cnst.getMaxLength();
    if (effectiveMaxLength == 0) {
        // Not supported at all: the user can capture without a duration limit.
    } else {
        // Set to a different value than preferredMaxLength asked for, so the
        // platform is at least trying to accommodate us.
    }
}

You can probe a constraint to see whether the entire constraint is supported (that is, whether it will be obeyed), or whether any particular aspect of it will be supported using the following methods:

  • isSupported() - True if all preferred constraints are supported.

  • isQualitySupported() - True if the preferred quality setting is supported.

  • isMaxLengthSupported() - True if the max length setting is supported.

  • isMaxFileSizeSupported() - True if the max file size setting is supported.

  • isSizeSupported() - True if the specified preferred width and height constraints are supported.

33.3. Example 2: Specifying explicit width and height

Suppose you want to capture a video with resolution 320×240. You would begin with this constraint:

VideoCaptureConstraints cnst = new VideoCaptureConstraints()
    .preferredWidth(320)
    .preferredHeight(240);

Explicit width and height constraints aren’t well-supported across platforms. Android doesn’t support them at all. iOS supports 3 specific sizes. JavaScript supports it when running on a desktop browser or on Android - but not on iOS. Etc.

Find out if this constraint will be obeyed:

if (cnst.isSizeSupported()) {
    // This platform supports the constraint, so the captured video will be
    // exactly 320x240.
} else {
    // Not supported -- see whether the platform will get close.
    int effectiveWidth = cnst.getWidth();
    int effectiveHeight = cnst.getHeight();
    int quality = cnst.getQuality();
    if (effectiveWidth == 0 && effectiveHeight == 0) {
        // No control over width and height. In many cases the platform will
        // approximate with the quality setting instead.
        if (quality != 0) {
            // Quality was set for us. Since 320x240 is small, it would
            // probably be QUALITY_LOW.
        }
    } else {
        // Could not capture at 320x240, but supplied the closest size it can.
    }
}

33.4. Constraint support by platform

PlatformSizeQualityMax LengthMax File Size

iOS

Limited

Yes

Yes

No

Android

No*

Yes

Yes

Yes

Simulator/Java SE

No

No

No

No

JavaScript (Desktop)

Yes

Yes

Yes

No

JavaScript (Android)

Yes

Yes

Yes

No

JavaScript (iOS)

No

No

No

No

* If size is specified, the platform will try to translate to the appropriate quality constraint.

Server side

34. Server-side backend

The backend compiles a Java HTTP handler into a native executable. It uses the same ParparVM pipeline as the iOS, Windows and Linux ports: javac produces bytecode, ParparVM turns that into C, and clang compiles the C together with the runtime into one binary. Nothing interprets anything at run time, and there is no JVM underneath.

The measurements in this chapter come from vm/backend/benchmarks on two pinned cores against 64 connections, and the harness is in the repository so you can disagree with them.

Java compiled to C to a native binary, and a request travelling through a host thread and a virtual thread to the handler
Figure 245. The build pipeline and the request path

34.1. What this doesn’t replace

Spring Boot, Quarkus, Micronaut and Jakarta EE aren’t the competition here. They carry a security stack, a starter for every service a company runs, a container that discovers beans in any jar on the class path, and two decades of operational knowledge. If you are running a Spring service today and it works, these chapters aren’t asking you to move it.

What this runtime borrows from them is the programming model. Controllers, services, dependency injection, declarative transactions, scheduled jobs and managed beans use Spring’s annotation names and mean what they mean there, so a Spring developer can read a Codename One backend without learning it first. What it doesn’t borrow is the container: every one of those annotations is resolved while the project builds, into ordinary code, and there is nothing left to interpret when the server runs.

What those frameworks assume is a JVM, and that paying for one is reasonable. For most server work that assumption holds. This exists for the work where it fails.

34.2. Why it exists

A JVM charges you twice. It charges start-up on every cold process, and it charges a baseline heap for as long as the process lives. Both are fine when a service runs for weeks and handles millions of requests. Neither is fine when the process exits after 200 milliseconds, when you are billed per invocation, or when the instance is capped at 128 MB.

That describes a specific and growing slice of server work: serverless functions, sidecars, edge workers, webhook receivers, small always-on services. Java is thin on the ground there, and the reason is arithmetic rather than taste. Teams therefore reach for Go or Node, and a Java shop that does this ends up with two languages, two toolchains, and two definitions of every object that crosses the wire.

The point of the backend is to remove the reason to leave Java for that slice. It doesn’t try to take work the JVM already does well.

34.3. How the backend chapters fit together

This chapter covers what every server needs: the module, the build, the concurrency model and configuration. The chapters after it each take one part of a server and go into depth:

34.4. A first server

The archetype (with -DprojectType=app-with-backend) and the initializr (with the App with backend project type) both generate a backend module beside the app:

myapp/
  common/    shared app code
  backend/   the server
    pom.xml
    src/main/java/com/example/myapp/Notes.java

A server-only project, generated with -DprojectType=backend-only or the initializr’s Backend only type, has no common module: the server is the whole project, at the root (see Section A.1.2, “Backend-only projects”).

A server is a class with routes on it. The annotations are Spring’s, under Codename One’s package names, so this reads the same way to anyone who has written a Spring controller:

@RestController
@RequestMapping("/notes")
public class Notes {
    private final Map<Long, Map> store =
            Collections.synchronizedMap(new LinkedHashMap<Long, Map>());
    private final AtomicLong nextId = new AtomicLong(1);

    @GetMapping("/healthz")
    public String health() {
        return "ok";
    }

    @GetMapping("/{id}")
    public Map read(@PathVariable("id") long id) {
        return store.get(Long.valueOf(id));      // null becomes a 404
    }

    @GetMapping
    public List list(@RequestParam(value = "limit", defaultValue = "20") int limit) {
        List page = new ArrayList();
        synchronized (store) {                   // iterating needs the map's own lock
            for (Map note : store.values()) {
                if (page.size() >= limit) {
                    break;
                }
                page.add(note);
            }
        }
        return page;
    }

    @PostMapping
    @ResponseStatus(201)
    public Map create(@RequestBody Map note) {
        long id = nextId.getAndIncrement();
        Map stored = new LinkedHashMap(note);
        stored.put("id", Long.valueOf(id));
        store.put(Long.valueOf(id), stored);
        return stored;
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(204)
    public void delete(@PathVariable("id") long id) {
        store.remove(Long.valueOf(id));
    }
}

There is no main here, and that’s the point. Every server opens with the same twenty lines — start a listener, install a shutdown handler, wait on it — and getting any of them wrong produces one that leaks connections on SIGTERM, or one that ends the moment main returns and says nothing about why. The build writes those lines, from the controllers it finds.

It also writes the router. The obvious hand-written form, if ("/healthz".equals(request.getTarget())), builds a String for the target, hashes it and compares it — for every route it tries before the one that matches, on every request — and breaks as soon as a client appends ?probe=1. The generated router holds each route as a byte[] and asks the request whether its path bytes are those bytes, so a route with no path variables allocates nothing at all and a query string can’t break it.

The return value decides the response. A String is sent as text, anything else as JSON, null is a 404, and @ResponseStatus sets the code for the cases where 200 isn’t it. A handler that needs something this doesn’t model takes the HttpServer.Request itself and answers exactly as it would have before.

Two commands matter:

# the property is not optional: the backend module lives in a profile, and
# without it Maven cannot see it in the reactor at all
mvn -pl backend -Dcodename1.platform=backend cn1:backend           # run it on this JVM
mvn -pl backend -Dcodename1.platform=backend cn1:backend-package   # build the native binary

In a backend-only Maven project, run ./mvnw cn1:backend and ./mvnw cn1:backend-package from the root, with no module or property.

In a Gradle project the backend is the backend subproject (or the whole project, for a backend-only application), and the same two steps are tasks:

./gradlew :backend:runBackend       # run it on this JVM
./gradlew :backend:backendPackage   # build the native binary

Drop the :backend: prefix in a backend-only project. Section 3.8, “The backend” covers adding a backend to an existing Gradle application.

The first is the development loop. Both run the same protocol code — there is one copy of HttpServer, and only the layer underneath it differs — so behaviour can’t drift between the loop you develop in and the binary you ship. The local run doesn’t terminate TLS, by design, and therefore doesn’t serve HTTP/2: both refuse with a message that says so, because a second TLS implementation would have its own bugs rather than production’s.

34.5. What the build writes

Every annotation in these chapters is read from the compiled classes, after javac and before the translator, during the process-classes phase. The build works out everything the annotations ask for and writes it down as plain Java, so the translator and the dead-code pass see an ordinary program:

Annotated sources compiled by javac, resolved by the build into generated wiring, routers and aspect classes, then translated
Figure 246. What the build does with a backend module
  • BackendApplication is the main. It builds the configuration, opens the database, starts the server and installs the shutdown handler.

  • BackendWiring is the whole of dependency injection: a new for each bean in dependency order, the calls that set its injected fields, and its @PostConstruct method. Chapter 37, Backend beans and dependency injection describes what goes into it.

  • A Router per controller holds each route as a byte[] and binds each parameter with code written for its type.

  • A Cn1Aspects class per annotated class carries what @Transactional, @Async, @Timed and @Counted add around a method. The method keeps its name and signature, its body moves to a method of its own, and the method calls the aspect around that body.

That has three consequences worth knowing from the start. A dependency that can’t be satisfied, a route claimed twice and a cron expression with a typo are build errors, each naming the class and member at fault, rather than failures the first request finds. Starting a server with fifty beans costs what the fifty constructors cost, because there is no scan and no lookup. And a feature the application skips isn’t in the binary at all: the translator drops every class nothing references, and the generated code references only what the annotations asked for.

The generated classes land in target/classes beside the module’s own. To see what the build decided about the beans without reading bytecode, ask a running development server: the backend_beans tool described in Chapter 46, Backend MCP and the agent loop lists every bean, its scope and what was injected into it.

A process runs one backend. Starting a second while the first is running fails with an error; starting again after it has stopped is fine. To scale out, run more processes: keep sessions in the database store and give scheduled jobs a lock, so the instances share them.

34.6. Virtual threads and the request loop

The concurrency model is the part most worth understanding, because it’s what makes a handler that blocks acceptable.

Every connection gets a virtual thread. Not a pooled worker that a connection borrows for one request — a stack that belongs to that connection until it closes. The handler can block on a socket read, a database round trip or a file, and it costs a parked stack rather than an OS thread.

Host threads run those virtual threads, and there is one host per core. A descriptor is registered in exactly one host’s epoll set, so it can only ever be reported to that host, and only that host ever touches its virtual thread. That affinity is why the scheduler needs no locks on the hot path.

The loop is: the host polls, a descriptor becomes readable, the host resumes that connection’s virtual thread, the handler runs until it needs bytes that haven’t arrived, and it parks. Parking returns control to the host, which polls again. When the handler finishes a response the descriptor stays armed, so the next request on that connection costs no system call to set up.

These are ParparVM’s own virtual threads, a feature of the translated runtime, and they aren’t the virtual threads of Java 21 and later. The two share a name and little else. A Java virtual thread unmounts whenever the JDK blocks on its behalf. One of these switches stacks in the translated C code and parks only where the runtime has made parking possible: waiting on a socket. That covers the connection it serves and every outbound one — a PostgreSQL or MySQL query, a Web call, a TLS handshake — so a handler waiting on another service costs a parked stack, and the host serves other connections meanwhile. Anything else that blocks holds the host thread under it and every virtual thread that host runs: SQLite and file access, which are local calls rather than sockets, resolving a host name, and Object.wait(). They’re also pinned: a virtual thread stays on one host for its whole life.

That’s why the development run on the JVM doesn’t use Java’s virtual threads to stand in for them, even for debugging. It serves connections on a pool of platform threads and runs VIRTUAL work on platform threads too. Code that’s correct there can still stall a host on the native build, so test anything that depends on how threads interleave — a handler that waits, a task that blocks — on the native server.

Host count follows cores rather than the workers argument. On two pinned cores, 16 hosts served 117 requests where 2 hosts served 257,297: past one host per core they compete for the cores the server needs. In this mode workers stops meaning "requests in flight," because the virtual threads supply that.

34.7. The life of a request

A server’s handlers are arranged in a chain, and each one either answers a request or passes it on by answering null. The order is fixed, so which handler wins never depends on registration order or on what happens to be in a directory:

A request passing through the MCP endpoint, trace relay, management endpoints, the application’s routes and static files, inside a wrapper that records metrics and saves the session
Figure 247. The life of one request
  1. A WebSocket upgrade is matched first, against the @WebSocketMapping routes, and never reaches the chain.

  2. The server’s own endpoints come next, each only when it’s turned on: MCP at /mcp, the trace relay at /otel/v1/traces, and the management endpoints under /manage. They come before the application’s routes so a catch-all route can’t answer a health check.

  3. Then the application’s routes.

  4. Static files from cn1.static.root are always last, so a file can’t shadow a route by being named like one. The app’s browser build comes after those, when the server hosts one; see Section 35.1.16, “Hosting the app in the browser”.

  5. A request nothing answered is a 404.

Around the chain sits one wrapper, and it’s where the per-request features live. It starts the clock for the request duration metric, makes the request available to request-scoped beans, and records the request for the development tools. After the chain answers it saves the session and adds its cookie, destroys the request’s request-scoped beans, and records the duration under the route that matched. A handler that throws is answered with a 500 whose body says only internal error, and the exception goes to the log rather than to the client.

34.8. Configuration and profiles

A server runs against a file on a laptop and a managed database in production, and the difference between those two can’t live in the source. It lives in properties files beside the binary and in the environment:

application.properties, committed:

cn1.datasource.url=${DATABASE_URL}
cn1.server.port=8080

application-dev.properties, also committed:

cn1.datasource.url=:memory:
CN1_PROFILE=dev ./server                         # SQLite, nothing installed
DATABASE_URL=postgres://app:secret@db/app ./server   # production

A key is resolved in one order, and the first layer that has it wins: a system property of that exact name, then the environment variable it maps to (cn1.datasource.url becomes CN1_DATASOURCE_URL), then the environment variable a platform already sets for it, then application-<profile>.properties, then application.properties.

The third layer is worth spelling out. PORT and DATABASE_URL are set for you by every platform-as-a-service worth the name, and a server that ignored them would need a wrapper script to start at all, so they’re read where those two keys are read.

A value may name an environment variable as ${NAME} or ${NAME:fallback}, and that reference resolves when the value is READ rather than when the file loads. That’s what lets the committed application.properties above name a variable only production sets: the development profile overrides the key, so the unset variable is never read. A reference that’s read and can’t be resolved fails with a message naming it, because the alternative is a server that opens a SQLite file called ${DATABASE_URL} and finds it empty.

Nothing here is required. A binary with no properties file beside it reads its whole configuration from the environment, which is the normal shape for a container built FROM scratch: there is no file next to the binary because there is nothing next to the binary.

KeyWhat it sets

cn1.profile

The active profile. dev, development, test and local are development profiles, which changes two defaults and nothing else.

cn1.datasource.url

A SQLite path, or a postgres:// or mysql:// URL. Also read from DATABASE_URL. On a development profile an unset value means an in-memory SQLite database; on any other profile it’s an error, because a service that writes into a database inside its own process, with nothing saying so, loses everything at the next deploy. PostgreSQL and MySQL connections set their session time zone to UTC, so NOW() and TIMESTAMP columns read and write UTC whatever the server’s own zone is.

cn1.datasource.pool.size

How many connections to hold. The default is eight for a server engine, four for a SQLite file and one for an in-memory database.

cn1.server.port

The port. Also read from PORT.

cn1.server.address

The address to listen on. Every interface by default; 127.0.0.1 keeps the server reachable only from the machine it runs on.

cn1.server.workers

The size of the request thread pool, 16 by default. Under virtual threads it no longer bounds the requests in flight; see Section 34.6, “Virtual threads and the request loop”.

cn1.server.tls.certificate, cn1.server.tls.key

A PEM certificate and key to terminate TLS with. One without the other is refused rather than serving plaintext under a name that promises otherwise.

cn1.static.root

A directory to serve files from, after every route.

cn1.webapp.root

The directory holding the app’s browser build, served at / after every route. webapp in the working directory by default; see Section 35.1.16, “Hosting the app in the browser”.

cn1.orm.createTables

Whether the generated daos create their tables at start-up. True on a development profile, false everywhere else.

cn1.orm.validateSchema

Whether start-up compares the entity mappings with the existing tables, after migrations and table creation, and refuses to serve when a table or column is missing or a column can’t hold what its field stores. A nullable column under a field the mapping requires is fatal too, because the database would accept rows the mapping can’t read; only an extra NOT NULL on a column the mapping leaves optional is logged and tolerated. True unless set.

cn1.flyway.enabled

Whether pending schema migrations run at start-up. True whenever the project has migrations; the rest of the cn1.flyway settings are listed under Section 39.3, “Schema migrations”.

cn1.config.location

The directory the properties files are read from; the working directory by default. Read only from a system property or the environment, since it decides where the files are.

cn1.server.backlog

The listen backlog, 512 by default.

cn1.server.shutdownTimeoutMillis

How long a stop waits for the requests in flight, 10 seconds by default. Zero means don’t wait.

cn1.server.tls.http2

Whether a TLS server offers HTTP/2 through ALPN. True by default.

cn1.server.forwardHeaders, cn1.server.trustedProxies

Whether X-Forwarded-For and X-Forwarded-Proto are believed, and from which proxies. Off by default; see Section 41.9.2, “Client addresses behind a proxy”.

cn1.static.prefix, cn1.static.index, cn1.static.cacheControl

Where static files are served (/static), the file a directory answers with (index.html), and their Cache-Control header (public, max-age=3600).

cn1.webapp.path, cn1.webapp.cacheControl, cn1.webapp.enabled

Where the app’s browser build is served (/), its Cache-Control header (no-cache), and whether it’s served at all (true).

cn1.datasource.pool.borrowTimeoutMillis

How long a request waits for a free connection before it fails, 10 seconds by default.

cn1.datasource.busyTimeoutMillis

How long SQLite waits on a locked database file, 5 seconds by default.

cn1.management.enabled

Build-time. true links the management endpoints into the server; see Chapter 45, Backend tracing, metrics and management and Section 34.8.2, “Build-time settings”.

cn1.mcp.enabled

Build-time. true links the MCP endpoint into the server; see Chapter 46, Backend MCP and the agent loop and Section 34.8.2, “Build-time settings”.

cn1.otel.enabled

Build-time. true links the OpenTelemetry exporters into the server; see Chapter 45, Backend tracing, metrics and management and Section 34.8.2, “Build-time settings”.

cn1.security.schema.enabled

Build-time. true links the security tables into the server; see Section 41.18, “Keeping it in the database” and Section 34.8.2, “Build-time settings”.

One limit is read only from the environment, because it’s fixed when the server class loads: CN1_HTTP_MAX_UPLOAD_MB, 64 by default, bounds the request bodies being received at once across all HTTP/1.1 connections. A request that would pass the limit gets a 503 rather than being buffered.

The chapters that follow add their own keys — cn1.session., cn1.security., cn1.task.executor., cn1.management., cn1.mcp. and cn1.otel. — and list each one where it’s described.

34.8.1. Settings compiled in

A server that ships as one executable often has no properties file beside it, so the build compiles the module’s application.properties into the server as the bottom layer of its configuration. The binary starts with the committed settings and nothing next to it, and a properties file or the environment present at run time still changes any key without a rebuild.

Only the base file is compiled in. A profile’s file describes a different deployment, so application-dev.properties stays a file the dev profile reads rather than becoming a production binary’s defaults.

Secrets — a token, a password inside a database URL — don’t belong in a committed file. Name them as ${NAME}, which is resolved from the environment when the value is read, or leave the key to the environment entirely.

34.8.2. Build-time settings

Four keys are read by the build, because each decides whether a part of the runtime is linked into the server at all. A server that doesn’t ask for a part has none of its code.

KeyWhat true links

cn1.security.schema.enabled

The tables of the security layer’s database stores.

cn1.management.enabled

The management endpoints.

cn1.mcp.enabled

The MCP endpoint. A class with an @McpTool method links it too, and so does cn1.mcp.path or cn1.mcp.allowedOrigins in a properties file.

cn1.otel.enabled

The OpenTelemetry exporters. The @OpenTelemetry annotation links them too.

The build reads these from the module’s application.properties and the application-<profile>.properties files beside it. It doesn’t read the environment, a system property or a properties file beside the finished server. The same two rules hold for all four:

  • true at run time in a server built without the part stops the start. The error names the key, says that it’s a build-time setting, and says to put it in the module’s application.properties and build again. The part isn’t in the server, so the setting can’t be honored.

  • false at run time in a server built with the part leaves the part out. The endpoints aren’t served, nothing is exported, and the tables aren’t created.

Every other key is read when the server starts, from wherever its configuration comes from.

Handlers that need any of this get it from the entry point the build writes.

35. Backend controllers, contracts and WebSockets

A controller turns HTTP into method calls. This chapter covers how requests are mapped to methods and how their parts are bound to parameters, how a return value becomes a response, how the app and the server share one declaration of their API, how a server holds WebSocket connections open, and how it sends push notifications. Section 34.4, “A first server” introduced the shape; this is the detail.

35.1. Mapping requests

A @RestController is a class whose methods answer requests. It’s also a bean, so its constructor receives whatever it depends on, as Chapter 37, Backend beans and dependency injection describes. Each mapped method names a verb and a path:

@RestController
@RequestMapping("/api/products")
public class Products {
    private final Map<Long, Map<String, Object>> products =
            new LinkedHashMap<Long, Map<String, Object>>();

    @GetMapping("/{id}")                                       // GET /api/products/42
    public synchronized Map<String, Object> get(@PathVariable("id") long id) {
        return products.get(Long.valueOf(id));                 // null answers 404
    }

    @GetMapping("/search")                                     // GET /api/products/search?q=mug
    public synchronized List<Map<String, Object>> search(
            @RequestParam(value = "q", required = false) String query,
            @RequestParam(value = "limit", defaultValue = "20") int limit) {
        List<Map<String, Object>> out = new ArrayList<Map<String, Object>>();
        for (Map<String, Object> p : products.values()) {
            if (out.size() < limit
                    && (query == null || String.valueOf(p.get("name")).contains(query))) {
                out.add(p);
            }
        }
        return out;
    }

    @PostMapping                                               // POST /api/products
    @ResponseStatus(201)
    public synchronized Map<String, Object> create(
            @RequestBody Map<String, Object> body,
            @RequestHeader(value = "Idempotency-Key", required = false) String key) {
        Long id = Long.valueOf(products.size() + 1);
        Map<String, Object> product = new LinkedHashMap<String, Object>(body);
        product.put("id", id);
        products.put(id, product);
        return product;
    }

    @DeleteMapping("/{id}")                                    // void answers 204
    public synchronized void delete(@PathVariable("id") long id) {
        products.remove(Long.valueOf(id));
    }

    @GetMapping("/{id}/label")
    public HttpServer.Response label(HttpServer.Request request, @PathVariable("id") long id) {
        byte[] text = ("product " + id).getBytes();
        return request.respond(200, "text/plain; charset=utf-8", text);
    }
}

@GetMapping, @PostMapping, @PutMapping, @PatchMapping and @DeleteMapping cover the usual verbs, and @RequestMapping(value = "/x", method = "OPTIONS") covers the rest. On the class, @RequestMapping is a prefix for every mapping inside it, and a mapping with no path answers on the prefix itself, as create does above. A mapping may list several paths, which is how a route keeps an old URL working.

A {name} segment matches one path segment and is bound with @PathVariable. Within one controller a literal route is tried before a route with variables that would also match it, so /api/products/search above reaches search rather than get with an id of search.

What the build refuses is a route nothing could ever reach. Two methods answering the same verb and path shape are an error, even when their variables are named differently, because a variable’s name isn’t part of what a request carries. The same is true across controllers: a variable route in one controller that would answer a literal route of another is reported, since the routers are tried in turn and the literal one would never run.

A path variable written {name:.+}, {name:.*} or {*name} is a catch-all: it takes the rest of the path, slashes included, so @GetMapping("/files/{*path}") answers /files/a/b/c.txt with path set to a/b/c.txt. It must be the last segment. Any other pattern after the colon is refused at build time, since the router matches segments and runs no regular expressions.

Mappings are inherited. A controller extending a base class, or implementing an interface, picks up the @RequestMapping prefix and the mapped methods those declare.

35.1.1. Binding the parts of a request

Every parameter of a mapped method says where its value comes from, with exactly one annotation:

AnnotationReadsBinds to

@PathVariable("id")

a {id} segment of the path

String, or a numeric or boolean primitive

@RequestParam("q")

a query parameter, or a field of a form body

String, or a numeric or boolean primitive

@RequestPart("file")

one part of a multipart/form-data body

HttpServer.Part, byte[], or String for a text field

@RequestHeader("Idempotency-Key")

a request header

String, or a numeric or boolean primitive

@RequestBody

the body

String, a Map or a List, or a class of your own and collections of it

none, typed HttpServer.Request

the request itself

anything the request exposes

The name is required. Java drops parameter names when it compiles unless it’s told to keep them, and a router that guessed would bind the wrong value in silence, so @RequestParam("q") names the parameter the client sends rather than the variable in the method. A parameter with no annotation, or with two, is a build error: one parameter reads from one place, which matters most for an input like a credential that could otherwise arrive from a query string when the code meant a header.

@RequestParam, @RequestHeader and @RequestBody are required unless they say otherwise. A request that leaves out a required value is answered 400, with the value’s name in the body, before the method runs. defaultValue supplies a value for one that’s missing. Two combinations are refused at build time, because each would hand the method a value nobody sent: required = false on a primitive with no defaultValue, since an int can’t hold "absent" and would arrive as 0; and a defaultValue that isn’t a value of the parameter’s type.

A body is parsed as JSON. A String, Map or List parameter gets it as parsed; a class of your own — an entity, a DTO — or a List<Order> of them is filled in by a codec the build writes for that class, as Jackson fills one in for a Spring controller. Section 35.1.3, “Your own classes as JSON” describes the form.

A request target with a malformed escape sequence, or one that isn’t valid UTF-8, is answered 400 before any route is tried, rather than as a 404 the client couldn’t explain.

A request parameter that repeats, ?tag=a&tag=b, binds to a List<String> or a String[]; form fields of a multipart request bind the same way. A boxed type, Integer or Long for example, is null when the parameter is absent instead of needing a defaultValue.

35.1.2. What a method returns

Return typeResponse

void

204 with no body, or the @ResponseStatus code.

String

The text, as text/plain; charset=utf-8, with 200 or the @ResponseStatus code.

A Map, List, Set, primitive or box, or a class of your own and collections of it

JSON, with 200 or the @ResponseStatus code.

HttpServer.Response

Exactly what the method built. @ResponseStatus on such a method is a build error, since the response already carries its own status.

null, from any of the above

404.

Any other return type is a build error: a JDK class with no JSON form, such as java.io.File, would otherwise come out as the JSON string of its toString(), with the build and the request both reporting success. @ResponseStatus takes a final status between 200 and 599.

A method that returns its own type can’t return a refusal, because its return type is the body of a success. It throws one:

if (taken(email)) {
    throw new ResponseStatusException(409, "That e-mail already has an account");
}

The reason is sent as the body, in plain text, so keep out of it anything the caller shouldn’t learn. A status below 500 is an answer: it isn’t logged and isn’t counted as a failed request. A status of 500 or above is reported the way any other failure of the handler is, and answered with the status given. The exception is unchecked, so inside a @Transactional method it rolls the transaction back.

35.1.3. Your own classes as JSON

A method can return an entity or any class of your own, or take one as its body, and the build writes the JSON codec for that class and for every class its fields reach. There is no reflection at run time: the codec is ordinary code that reads and writes each field by name, so it costs what the hand-written version would.

public class Order {
    public long id;
    public String customer;
    @JsonProperty("placed_at")
    public Date placedAt;
    public List<OrderLine> lines = new ArrayList<OrderLine>();
}
public class OrderLine {
    public String sku;
    public int quantity;
}
@RestController
@RequestMapping("/orders")
public class OrdersApi {
    private final Map<Long, Order> orders =
            Collections.synchronizedMap(new LinkedHashMap<Long, Order>());
    private final AtomicLong ids = new AtomicLong();

    @PostMapping
    public Order place(@RequestBody Order order) {
        order.id = ids.incrementAndGet();
        order.placedAt = new Date();
        orders.put(Long.valueOf(order.id), order);
        return order;
    }

    @GetMapping("/{id}")
    public Order find(@PathVariable("id") long id) {
        return orders.get(Long.valueOf(id));    // null is a 404
    }
}

A POST /orders with {"customer":"Ada","lines":[{"sku":"A-1","quantity":2}]} answers with the stored order:

{"id":1,"customer":"Ada","placed_at":1740821400000,"lines":[{"sku":"A-1","quantity":2}]}

The JSON form is the one the app’s @Mapped mapper uses, so a class shared by the app and the server reads the same on both sides:

  • The fields are the class’s own and its superclasses', except static and transient ones. A public field is used directly; any other through its getX (or isX) and setX methods, and is left out when it has neither.

  • @JsonProperty("due_at") renames a field and @JsonIgnore leaves one out, both from com.codename1.annotations. The options in Section 35.1.4, “Shaping the JSON contract” shape the rest.

  • A record is written from its accessors and read through its canonical constructor, so it needs no constructor without arguments. A component the body leaves out, or one marked @JsonIgnore, is passed its default: null, 0 or false.

  • A Date is written as milliseconds since the epoch, which is Jackson’s default and what the app’s mapper reads, and is read from that or from an ISO-8601 date such as 2025-03-01T09:30:00Z. A byte[] is base64, an enum is its name.

  • A subclass is written with its own fields, even where a method declares the superclass.

  • A field declared Object, or a raw Map or List, is written by what it holds when the server runs. A value of a class the build writes a codec for goes through that codec; a value of any other class of yours is answered 500 rather than written as its toString(), so declare the field with its type.

  • A body’s unknown members are ignored and absent ones leave the field as the constructor set it, as a Spring Boot application does. An explicit null sets a field to null, and leaves a primitive at its default.

  • A generic class is written and read through the type arguments it’s used with: a method returning Page<Order> gets a codec that knows Page’s `List<T> holds orders.

  • An array is a JSON array, of any element type a field may have.

A body the codec can’t read — a string where a number belongs, an enum name that doesn’t exist — is answered 400 with where it was and what was expected:

$.items[2].due: expected a number or an ISO-8601 date, got true

Two objects that refer to each other, such as an order whose lines point back at it, would be written forever, so a response that nests more than 64 objects deep is answered 500 with a message naming the class; mark the field that points back @JsonIgnore. The same limit refuses a body nested deeper than that with 400. cn1.json.maxDepth in application.properties moves it. The build refuses what it can’t write a codec for, and says why: a generic class used without its type arguments, such as a raw Page; a body class other than a record with neither a constructor without arguments nor a @JsonCreator; an interface; and an array of more than one dimension, which a List of arrays replaces.

35.1.4. Shaping the JSON contract

An API that outlives one release needs more say over its JSON than a field name. These annotations, from com.codename1.annotations, are read at build time by the server’s codecs and by the app’s @Mapped mappers alike, so a class shared by both keeps one contract:

AnnotationEffect

@JsonProperty(value = "order_id", aliases = {"orderId"})

Writes the field as order_id and reads it from any of the names. An alias is the way to rename a member without breaking clients that still send the old name.

@JsonProperty(required = true)

A body that leaves the member out is answered 400: $.order_id: required member is missing. An explicit null is present, so it’s accepted for an object and refused for a primitive, which can’t hold it.

@JsonStrict on a class

A member the class doesn’t declare is answered 400 with its path, $.lines[0].colour: unknown member, where the default ignores it.

@JsonOmitNull on a class or a field

A null member is left out of the JSON instead of written as null.

@JsonFormat(JsonFormat.Shape.STRING) on a field

A number is written in quotes, which a JavaScript client needs for a long past 2^53. A Date is written as an ISO-8601 instant in UTC, 2025-03-01T09:30:00.000Z. Reading accepts either form, so a field can change format without breaking its old clients.

@JsonAdapter(MoneyAdapter.class) on a field or a class

Hands the value to your own JsonTypeAdapter. On a class, it applies wherever the class appears.

@JsonCreator on a constructor or a static factory

Reads an immutable class through it. Each parameter names its member with @JsonProperty, because a compiled class doesn’t keep parameter names.

An immutable class keeps its fields final and is read through its creator:

@JsonStrict
public final class Point {
    private final int x;
    private final int y;

    @JsonCreator
    public Point(@JsonProperty(value = "x", required = true) int x,
                 @JsonProperty("y") int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() { return x; }
    public int getY() { return y; }
}

An adapter converts between a type and the parsed form of JSON: null, a String, a Boolean, a Number, a Map for an object and a List for an array. It’s for the types the codecs don’t map themselves, such as an amount kept in cents and sent as a decimal string:

public final class MoneyAdapter implements JsonTypeAdapter<Money> {
    public Object toJson(Money m) {
        return m == null ? null : m.toDecimalString();
    }

    public Money fromJson(Object json) {
        if (json == null) {
            return null;
        }
        if (!(json instanceof String)) {
            throw new IllegalArgumentException("expected an amount");
        }
        return Money.parse((String) json);
    }
}

The adapter needs a public constructor without arguments. The build creates one instance of it and calls it directly, so nothing is looked up by name at run time and a native build keeps the class. An IllegalArgumentException it throws is answered 400, with the member’s path in front of its message.

35.1.5. Coming from Jackson

A Spring controller maps JSON through Jackson’s ObjectMapper at run time. The backend does the same work at build time, so most of what an ObjectMapper call did becomes a declaration:

JacksonCodename One backend

mapper.readValue(body, Order.class) in a handler

Declare the parameter @RequestBody Order order.

mapper.writeValueAsString(order) for a response

Return the Order.

@JsonProperty, @JsonIgnore, @JsonCreator

The annotations of the same names in com.codename1.annotations.

@JsonAlias

@JsonProperty(aliases = …​).

@JsonInclude(Include.NON_NULL)

@JsonOmitNull.

FAIL_ON_UNKNOWN_PROPERTIES

@JsonStrict on the classes that want it. Unknown members are ignored by default, as Spring Boot configures Jackson.

@JsonFormat(shape = STRING)

@JsonFormat(JsonFormat.Shape.STRING). Dates are ISO-8601, never a pattern.

@JsonSerialize and @JsonDeserialize with custom serializers

@JsonAdapter and a JsonTypeAdapter.

JsonNode, mapper.readTree(text)

Json.parse(text), which answers a Map, a List, a String, a Long, a Double, a Boolean or null, nested to whatever depth the document has.

ObjectNode built by hand for a response

A Map or List returned from the method, or written with Json.write(value).

@JsonTypeInfo and @JsonSubTypes

No equivalent. A subclass is written with its own fields, but a body is read as the declared class. Read a polymorphic body as a Map and choose the class yourself.

A field whose type has no codec, such as a JDK class the server doesn’t map, fails the build and names the field. Give it a @JsonAdapter, or declare it as the value it travels as.

A method that throws is answered 500 with the body internal error, and the exception is logged. The message isn’t sent to the client, because an exception message is the most common way a server leaks its internals. To answer a failure with a status and a body of your choosing, return an HttpServer.Response, built with request.respond(status, contentType, bytes) or request.respondJson(status, value).

35.1.6. Taking the request itself

A parameter typed HttpServer.Request receives the request, which is the way to anything the binding annotations don’t model: every header, the raw body, the session, or a response with headers of its own. The label method in the example above takes it for that reason.

A request’s byte arrays belong to the connection and are reused by the next request on it, so a handler that keeps the body beyond its own call copies what it needs. That’s the price of a router that allocates nothing for a route without path variables.

35.1.7. Forms and file uploads

A browser form posts its fields as application/x-www-form-urlencoded, or as multipart/form-data when it carries a file. @RequestParam reads a field of either kind of form the way it reads a query parameter, so a handler doesn’t care how the client encoded it. The query string wins when both have the name, as it does in a servlet container. @RequestPart binds one part of a multipart body, which is the way to a file:

@PostMapping("/avatars")
public Map<String, Object> upload(@RequestPart("image") HttpServer.Part image,
                                  @RequestParam("caption") String caption) {
    Map<String, Object> out = new LinkedHashMap<>();
    out.put("file", image.getFilename());
    out.put("type", image.getContentType());
    out.put("bytes", image.getSize());
    out.put("caption", caption);
    return out;
}

An HttpServer.Part has the part’s name, its file name when it’s a file, its content type, its own headers and its bytes. A body that isn’t well-formed multipart is answered 400 before the method runs, and so is a request without a required part. A handler that takes the request itself reads the same parts with getParts() and getPart(name), and reads a field with param(name).

The body limit applies to the whole multipart request, files included: 8 MB, as for any other body. A body that isn’t text — an upload, an image, application/octet-stream — reaches the handler as bytes through getBodyBytes(). getBody() returns text only for a text type, JSON, XML or a form, after checking that it’s valid UTF-8, and refuses a binary body rather than hand the handler garbled characters.

35.1.8. Large uploads and downloads

A binary body can be larger than 8 MB when CN1_HTTP_MAX_SPOOLED_BODY_MB raises its limit. Such a body is never held in memory whole. Up to CN1_HTTP_SPOOL_THRESHOLD_KB (1024 by default) it stays on the heap, and past that the server writes it to a temporary file as it arrives. The file is deleted from the directory as soon as it’s created, so a crash leaves nothing behind. CN1_HTTP_SPOOL_DIR chooses the directory, the system temporary directory otherwise. A body over the limit is answered 413, over HTTP/1.1 and HTTP/2 alike. JSON, forms, XML and compressed bodies keep the 8 MB limit, because a handler reads those whole anyway.

Read such a body with getBodyStream(), which reads the file or the memory without the handler knowing which. getBodyLength() gives its size without reading it. A multipart upload is spooled the same way, and each HttpServer.Part has getInputStream() and getLength() for it:

@PostMapping("/archive")
public Map<String, Long> archive(HttpServer.Request request) throws IOException {
    long total = 0;
    byte[] buffer = new byte[64 * 1024];
    InputStream in = request.getBodyStream();
    try {
        for (int n = in.read(buffer); n > 0; n = in.read(buffer)) {
            total += n;                 // store, hash or forward each block
        }
    } finally {
        in.close();
    }
    return Collections.singletonMap("bytes", total);
}

The body is valid until the request ends. A handler that needs it later copies it somewhere of its own.

A response is streamed with HttpServer.Response.stream. The writer runs after the headers are sent and writes as much as it likes: chunked on HTTP/1.1, DATA frames on HTTP/2. A write blocks while the client is slow, so a slow client slows the writer rather than filling memory, and a client that goes away makes the next write throw.

@GetMapping("/report.csv")
public HttpServer.Response report() {
    return HttpServer.Response.stream(200, "text/csv", new HttpServer.BodyWriter() {
        public void writeTo(OutputStream out) throws IOException {
            for (int row = 0; row < 1000000; row++) {
                out.write((row + "," + row * row + "\n").getBytes("UTF-8"));
            }
        }
    });
}

The server doesn’t run the writer for a HEAD request, a status without a body, or a client that left before the headers went out. A writer that holds something open until it runs, such as a connection or a file, should also implement java.io.Closeable. In those cases the server calls close() instead.

35.1.9. Compression

cn1.server.compression.enabled=true turns on gzip for responses, with the two other settings Spring Boot has for it. A response is compressed when the client sends Accept-Encoding: gzip, its type is in cn1.server.compression.mimeTypes (text, JSON, JavaScript and XML by default), and its body is at least cn1.server.compression.minResponseSize bytes (2048 by default). A static file is left unchanged, because it’s sent straight from the page cache, and so is a response whose handler set a Content-Encoding of its own. A range answer (206 or any response with Content-Range) is never compressed either, because its offsets describe the uncompressed bytes, and neither is a response with a strong ETag, which names its exact bytes, as Tomcat leaves one by default. Compression is off by default because it trades processor time for bytes, and a server behind a proxy that already compresses would pay for it twice.

A request body sent with Content-Encoding: gzip is decompressed before the handler sees it, whether responses are compressed or not. It’s held to the same 8 MB limit after decompression, so a small compressed body can’t expand past it. A request in any other encoding is answered 415.

35.1.10. Cross-origin requests

A browser refuses to let a page read a response from another origin — another scheme, host or port — unless the server says it may. A web app served from one host that calls an API on another needs the API to say so, and the cn1.cors settings do:

cn1.cors.allowedOrigins=https://app.example.com
cn1.cors.allowCredentials=true
cn1.cors.exposedHeaders=X-Request-Id
KeyWhat it sets

cn1.cors.allowedOrigins

The origins that may call the server, separated by commas, or * for any. Each is scheme://host[:port] with no path, as a browser sends it in Origin; the server refuses to start with anything else. Cross-origin requests are refused while this is unset.

cn1.cors.allowedMethods

The methods a cross-origin request may use, preflighted or not. All the common ones by default.

cn1.cors.allowedHeaders

The request headers a preflight allows, * by default.

cn1.cors.exposedHeaders

Response headers beyond the basic ones that the page may read.

cn1.cors.allowCredentials

Whether the browser sends cookies and the page may read the answer. A browser refuses this with a * origin, so the server refuses that combination when it starts.

cn1.cors.maxAgeSeconds

How long a browser may cache a preflight answer, 1800 seconds by default.

The server answers a preflight OPTIONS request itself, and adds the headers to every response to an allowed origin. A cross-origin request from an origin not on the list, or with a method not on it, is refused with a 403 before any handler runs, as Spring refuses it; a request whose Origin is the server itself isn’t a cross-origin request. A handler that maps OPTIONS or sets Access-Control-Allow-Origin itself keeps its own policy, which is how the MCP endpoint keeps the stricter one it has.

35.1.11. Serving static files

cn1.static.root names a directory, and the server answers requests under cn1.static.prefix (/static by default) with its files, after every route has had its chance. A directory is answered with its cn1.static.index file, and every file carries cn1.static.cacheControl. The resolved path must be inside the root, checked by resolving it on disk rather than by inspecting the request, so ../, an encoded escape sequence and a symbolic link out of the tree are all refused. Conditional requests and ranges are honoured, and where the platform supports it the file is sent from the page cache to the socket without passing through the process.

StaticFiles.firstOf(a, b, …​) serves from the first of several roots that has the file, so an application can overlay its own assets on a library’s.

35.1.12. When a method throws

A method that throws answers 500 with a body that reveals nothing about the failure, unless something handles the exception first. A ResponseStatusException chooses its own status. For anything else, write a handler:

@RestController
public class NotesWithHandler {
    private final Map<Long, NoteView> notes = new HashMap<Long, NoteView>();

    @GetMapping("/notes/{id}")
    public NoteView note(@PathVariable("id") long id) {
        NoteView note = notes.get(id);
        if (note == null) {
            throw new NoteMissing(id);
        }
        return note;
    }

    @ExceptionHandler(NoteMissing.class)
    @ResponseStatus(404)
    public Map<String, String> missing(NoteMissing e) {
        return Collections.singletonMap("error", e.getMessage());
    }
}

A handler on a controller answers for that controller’s routes. A @ControllerAdvice (or @RestControllerAdvice) bean holds handlers for every controller, and basePackages narrows it to some:

@RestControllerAdvice
public class ApiErrors {
    @ExceptionHandler(IllegalArgumentException.class)
    public HttpServer.Response badInput(IllegalArgumentException e, HttpServer.Request request) {
        return HttpServer.Response.text(400, e.getMessage()).header("X-Error", "input");
    }
}

A handler takes, in any order, the exception, the HttpServer.Request and the HandlerMethod that failed. It returns an HttpServer.Response for full control of status, headers and body; or a String, a Map, a List, a Json.Writable or nothing, sent with its @ResponseStatus, or 200 without one, as Spring does. A handler returning a null Response declines, and the next one is asked.

The build decides which handler answers, in this order:

  1. The controller’s own handlers. Among those that apply, the one naming the closest superclass of the thrown exception.

  2. Each advice, in @Order order and then by bean name, choosing its own closest match the same way.

  3. A ValidationException that nothing handled answers 400 with its field errors, as the next section shows.

  4. Anything else answers as before: the status of a ResponseStatusException, otherwise a plain 500.

Two kinds of failure skip every handler. An Error is never handled. A failure that belongs to security, AccessDeniedException or AuthenticationException and their subclasses (CSRF failures among them), goes straight back to the security chain, so a handler for Exception can’t turn a 403 into a 200 by accident.

Two handlers in one class for the same exception, a handler that takes an argument it can’t be given, or one returning a type it can’t send all fail the build, naming the method.

35.1.13. Validating input

Constraints from com.codename1.backend.validation declare what valid input looks like. Put @Valid on a @RequestBody or @ModelAttribute parameter to check the object’s fields, and put a constraint directly on a @RequestParam, @PathVariable or @RequestHeader:

public class NewNote {
    @NotBlank @Size(max = 200) public String title;
    @Min(1) @Max(5) public int priority;
    @Valid public Address address;
    @Valid public List<Tag> tags;
}

The controller asks for the checks on its parameters:

@PostMapping("/notes")
public NoteView create(@Valid @RequestBody NewNote note) {
    NoteView saved = new NoteView();
    saved.id = notes.size() + 1;
    saved.title = note.title;
    notes.add(saved);
    return saved;
}

@GetMapping("/notes")
public List<NoteView> page(@RequestParam("page") @Min(1) int page) {
    int from = Math.min((page - 1) * 20, notes.size());
    return new ArrayList<NoteView>(notes.subList(from, Math.min(from + 20, notes.size())));
}

The constraints are @NotNull, @NotBlank, @NotEmpty, @Size, @Min and @Max. @Valid on a field descends into its value, or into each element of a collection or array. The build writes every check as code, so a constraint on a type that can’t carry it, such as @Min on a String, fails the build.

The checks run after binding and before the method, so invalid input never reaches it. They throw a ValidationException, which a handler from the previous section may answer. Unhandled, it answers 400:

{"status":400,"error":"Bad Request","errors":[
  {"field":"title","code":"NotBlank","message":"must not be blank"},
  {"field":"tags[1].name","code":"Size","message":"size must be between 1 and 20"}]}

Field paths are stable: they use the JSON property names, [n] for an element, and the annotation’s name for a parameter. A @Valid @ModelAttribute form followed by a BindingResult parameter records the errors there instead, and the method decides what to render.

There is no @Pattern: the backend’s class library has no regular expressions. Check such a value in the method and throw a ValidationException of your own; it’s answered the same way.

35.1.14. Around every request

A bean implementing HandlerInterceptor runs around every controller method, for work that’s not security: auditing, metrics, cleaning up after a request.

@Component
@Order(1)
public class Audit implements HandlerInterceptor {
    private final AuditTrail audit = new AuditTrail();

    public HttpServer.Response preHandle(HttpServer.Request request, HandlerMethod handler) {
        return null;                       // null proceeds; a Response answers instead
    }

    public void afterCompletion(HttpServer.Request request, HandlerMethod handler,
                                HttpServer.Response response, Throwable failure) {
        audit.record(handler.getPattern(), failure == null ? "ok" : failure.toString());
    }
}

A request passes through these stages in order:

  1. The security filter chain: authentication, CSRF and the URL rules. A request it refuses never reaches an interceptor.

  2. Route selection. A request that matches no route isn’t intercepted.

  3. Each interceptor’s preHandle, in @Order order. One that returns a response answers with it, and the controller method doesn’t run.

  4. Binding, validation, and the method with its method security.

  5. The exception handlers, when the stage before threw.

  6. Each postHandle, in reverse order, when the method returned normally.

  7. Each afterCompletion, in reverse order, for every interceptor whose preHandle let the request through. It runs on success, after a later interceptor refused, after a binding or validation failure, and after a failure nothing handled, which it receives as failure.

Because interceptors run inside the security chain and never see the failures security owns, an interceptor can’t let through a request security refused.

MappedInterceptor limits an interceptor to some paths, as Spring’s addPathPatterns and excludePathPatterns do: matches within one segment and /* matches any number of them.

ViewControllers declares answers that need no controller: a redirect from one path to another, or a bare status for a path. A backend renders no server-side views, so there is no view-name form.

35.1.15. Coming from Servlets and Spring MVC

The backend has no Servlet container. The usual extension points map as follows:

Servlet or Spring MVCBackend

Filter doing authentication, CSRF or access rules

A SecurityFilterChain bean, or a SecurityFilter added to it

Filter or HandlerInterceptor doing anything else

A HandlerInterceptor bean

@ExceptionHandler, @ControllerAdvice, @RestControllerAdvice

The same annotations, resolved at build time

HandlerExceptionResolver

An ExceptionResolver bean

@Valid with Bean Validation

@Valid and the constraints in com.codename1.backend.validation

HttpServletResponse headers and status

Return an HttpServer.Response

35.1.16. Hosting the app in the browser

A project with an app and a server can have the server host the app’s browser build. One address is then both the API and the app: somebody opens it and is using the app, with nothing to install.

mvn -pl backend -Dcodename1.platform=backend cn1:backend-webapp (1)
mvn -pl backend -am -Dcodename1.platform=backend cn1:backend (2)
1Builds the app for the browser and stages it in backend/target/webapp.
2Runs the server, which now answers / with the app.

cn1:backend-webapp runs the project’s own JavaScript build on this machine, the one mvn package -Dcodename1.platform=javascript -Dcodename1.buildTarget=local-javascript runs, then unpacks the bundle into the server module’s target/webapp. It’s a goal of its own because that build takes about a minute. Run it when the app changed, not every time the server restarts; what it staged stays until mvn clean.

The server looks for the app in a directory named webapp in its working directory, beside application.properties, and serves it when the directory holds an index.html. There’s no setting to turn on. cn1:backend points the server at target/webapp for you, and cn1:backend-package leaves the directory beside the binary, so a deployment is the binary with webapp next to it:

/srv/myapp/
  myapp-server            the binary
  application.properties
  webapp/
    index.html
    ...

The files aren’t linked into the binary. They’re sent from the page cache, which needs them to be files.

Routes still come first. A request reaches the app’s files only when no route answered it, so /api/notes is the API and / is the app, and a file can’t shadow a route by being named like one.

The files of a build keep their names from one build to the next, so each is served with Cache-Control: no-cache and an entity tag: a browser asks every time and is told 304 Not Modified for a file that didn’t change. A deployment that puts a version in the path can set a longer policy. The build also writes a gzip copy beside each text file that shrinks, and a browser that accepts gzip is sent that copy; a range request, and a browser that doesn’t accept it, get the file itself.

SettingWhat it does

cn1.webapp.root

The directory holding the app. webapp in the working directory by default. A directory named here that holds no index.html stops the server from starting, since a server told where its app is shouldn’t answer 404 there.

cn1.webapp.path

Where the app is served. / by default.

cn1.webapp.cacheControl

The Cache-Control header of every file. no-cache by default.

cn1.webapp.enabled

Set to false to serve no app even when the directory is there.

The goal has a few parameters of its own:

ParameterWhat it does

cn1.backend.webapp.bundle

A bundle to stage instead of building one: the archive a JavaScript build produced, or a directory unpacked from it. Use it for a bundle built by an earlier job or by the build server.

cn1.backend.webapp.output

Where to stage it. target/webapp in the server module by default.

cn1.backend.webapp.appRoot

The app’s root project. The directory above the server module by default.

A Gradle project has the same step as a task of its backend project:

./gradlew :backend:backendWebApp (1)
./gradlew :backend:runBackend (2)
1Builds the app for the browser and stages it in backend/build/webapp.
2Runs the server, which now answers / with the app.

backendWebApp runs the root project’s local JavaScript build, the one buildJavascriptLocal runs, and unpacks the bundle into the backend’s build/webapp. runBackend points the server at that directory, and backendPackage writes the binary into build, where webapp is beside it already. What it staged stays until ./gradlew clean.

-Pcn1.backend.webapp.bundle and -Pcn1.backend.webapp.output do what the Maven parameters of the same names do. There’s no appRoot: the app is the root project of the build. A backend-only project has no app to build, so its backendWebApp stages a bundle named with -Pcn1.backend.webapp.bundle.

A test that needs the app served names the directory, since a test runs in the module directory and not in target:

@BackendTest(properties = "cn1.webapp.root=target/webapp")
class HostedAppTest {
}
Talking to the server from the hosted app

The hosted app and its API share an origin, so the app needs no server address compiled in. In the browser the address of the page is the address of the server:

String origin = CN.getProperty("browser.window.location.origin", null);
String server = origin != null ? origin : "https://api.example.com";

A same-origin request needs no CORS configuration and goes straight to the server. The JavaScript build can route requests to other origins through a proxy servlet; a backend isn’t a servlet container, so the hosted build is made without one unless the project sets javascript.inject_proxy or javascript.proxy.url itself. A hosted app that calls a third-party service directly needs that service to allow the app’s origin.

A WebSocket follows the same rule. Replace http with ws in the origin and the socket goes to the server the page came from, over TLS when the page did.

Signing in from the hosted app

An installed app that signs in against the server’s own authorization server usually asks for the code to be sent to a loopback address and reads it off the redirect. A page in a browser can’t do that. The browser follows a redirect itself, shows the page only what was at the end of it, and refuses to show it anything from another origin. It also keeps the session cookie to itself: the page can neither read Set-Cookie nor set Cookie.

Three things make the same flow work there:

  • Register a redirect address on the server’s own origin for the app’s client, such as https://app.example.com/signin/code, beside the loopback one. A redirect address is matched exactly, scheme, host and port included, so it has to be the address people open the app at.

  • Answer that path with the code it was given, as JSON. The redirect then ends on a same-origin response the app can read. The path needs no sign-in: it repeats what was in its own address, and a code is worth nothing without the PKCE verifier that only the app that started the sign-in holds.

  • Answer the sign-in form with a status and not a redirect, using formLogin(form → form.successHandler(…​).failureHandler(…​)). The app can’t see which page a redirect led to, so 200 and 401 are how it learns whether the password was accepted.

The browser then carries the session cookie from the form to /oauth2/authorize on its own, because both are the same origin, and the token request is the same one the installed app makes. Tokens are kept by the app’s token store, which in a browser is the browser’s storage for that origin.

That cookie changes what the sign-in chain has to defend against. An installed app holds its session itself, so no other site can ride on it. A browser sends the cookie on its own. If the chain runs without CSRF tokens, because the app posts the form itself, two things have to do their work:

  • The session cookie is HttpOnly and SameSite=Lax unless cn1.session.same-site says otherwise, and Secure under TLS. Leave it that way: None sends the session along with another site’s requests.

  • Refuse a request that changes something and names another site in Origin. A browser sets that header on every such request and a page can’t alter it. The installed app sends none, so a request without one passes. A filter added with addFilterBefore(filter, LogoutFilter.class) covers the form, the token endpoint and sign-out. Compare against the configured issuer.

With CSRF off, sign-out answers a GET as well as a POST. Narrow it with logout(logout → logout.logoutRequestMatcher(…​)), and have the app send POST /logout once it has its tokens. The session has done its work by then. One that’s never ended lasts until cn1.session.timeout seconds pass without a request, which is 1800 unless set.

35.2. Sharing the contract with the app

This is where having the same language on both ends stops being a slogan. An interface annotated for the REST client generates the app’s client:

@RestClient
public interface NotesApi {
    @GET("/notes/{id}")
    void note(@Path("id") String id, OnComplete<Response<Note>> callback);

    @POST("/notes")
    void create(@Body Note note, OnComplete<Response<Note>> callback);
}

Building the backend module with -Dcn1.restServer=true generates two more types from that same interface: NotesApiServer, a synchronous interface the backend implements, and NotesApiDispatcher, which routes a method, path and body to it and binds the path and query parameters.

public class NotesEndpoint implements NotesApiServer {
    private final Map<String, Note> notes =
            Collections.synchronizedMap(new HashMap<String, Note>());

    public Note note(String id) {                // no callback: this IS the server
        return notes.get(id);
    }

    public Note create(Note note) {
        notes.put(String.valueOf(note.id), note);
        return note;
    }
}

The client’s methods are asynchronous because a UI can’t block; the server’s methods are synchronous because a handler has nothing to call back into. One declaration produces both shapes, which is what gRPC does and for the same reason.

The payoff is that changing the contract breaks the build on whichever side did not follow it, instead of producing a response the app fails to parse in the field. The data transfer objects are shared rather than transcribed, and their codecs are generated on both sides, so there is no handwritten mapping layer to drift.

The server half is off by default. Every existing project carries these interfaces for its client alone, and generating server classes into those builds would grow them for nothing.

35.2.1. A module both sides depend on

A project with an app and a server keeps the contract in a module of its own, which common and backend both depend on. Nothing needs switching on there:

  • The app’s build finds the contract in the dependency and generates its client, exactly as it does for an interface in common itself.

  • The backend’s generate-annotation-stubs goal writes, for each contract, NotesApiServer and a NotesApiController into target/generated-sources/cn1-annotations. The controller is an ordinary @RestController that takes the @Component implementing NotesApiServer and maps each operation to it, so routing, binding, security rules and filters treat it like one written by hand.

The module holds the data classes and the interfaces and nothing else. It compiles against codenameone-core for the callback types the interfaces name, with provided scope, so the server doesn’t inherit the client library. A contract method can’t answer with a status of its own, so the implementation throws ResponseStatusException to refuse a request.

The Initializr’s ride-hailing template is built this way and generates a starting point under your own name and package. Chapter 50, Wayline: Building on the sample describes it.

35.3. Real-time with WebSockets

The server speaks RFC 6455, so a Codename One app can hold a live connection to a Codename One server with the same language on both ends. The client half is com.codename1.io.WebSocket, which every port has shipped for years; this is the other half of it.

An endpoint implements com.codename1.backend.WebSocket:

public static final class Echo implements WebSocket {
    public void onOpen(WebSocketSession session) throws IOException {
        session.sendText("welcome");
    }

    public void onText(WebSocketSession session, String message) throws IOException {
        session.sendText(message);
    }

    public void onBinary(WebSocketSession session, byte[] message, int offset, int length)
            throws IOException {
        session.sendBinary(message, offset, length);
    }
}

The build finds it, the way it finds a @RestController:

@WebSocketMapping("/chat")
public static final class ChatEndpoint implements WebSocket {
    public void onOpen(WebSocketSession session) { }

    public void onText(WebSocketSession session, String message) { }

    public void onBinary(WebSocketSession session, byte[] message, int offset, int length) { }
}

The annotation goes on the type rather than on a method, because a @GetMapping marks a call and a WebSocket is a connection: its contract is seven callbacks that share per-connection state, which is an object. What it keeps from @GetMapping is what a reader cares about — the path is relative to a class-level @RequestMapping, a constructor taking a DataSource or an EntityManager is injected the same way, and two endpoints claiming one path is a build error rather than something registration order decides. Write the path’s characters out: an escaped character such as %61 in the mapping is a build error too, since an upgrade is matched against the decoded path, which an escaped mapping never equals. An endpoint that injects a request- or session-scoped bean, directly or through a singleton, builds with a warning: its callbacks run outside any HTTP request, so there’s no request or session to find the bean in, and using it there throws IllegalStateException, as in Spring. Keep per-connection state in the session’s attachment instead.

Only onOpen, onText and onBinary have to be written. onPing, onPong, onClose and onError have empty defaults, and a PING is answered with its PONG before the endpoint is told, so an endpoint that ignores them still keeps its connections alive.

35.3.1. One endpoint, many connections

An endpoint is created once for the route, not once per client, which is the same shape a @RestController has. Everything belonging to one client lives on the WebSocketSession the callbacks are handed, and setAttachment is where an endpoint puts its own per-connection state.

Messages arrive whole. A client that splits a two megabyte upload into thirty-two frames produces one onBinary, and a text message is validated as UTF-8 before it is decoded, so a handler never sees a replacement character standing in for bytes the client didn’t send. The array passed to onBinary is the session’s own reassembly buffer and is valid only until that call returns — the same contract HttpServer.Request carries, and for the same reason. An endpoint that keeps the bytes copies the range it wants.

35.3.2. Sending from somewhere else

A callback runs on the thread that owns its connection, and the server reads nothing more from that connection until it returns. An endpoint may therefore block, and a slow one slows down its own client and nobody else’s.

Sending is the other way round: a session may be written to from any thread, which is what makes a broadcast possible.

public static final class Room implements WebSocket {
    // Every open session in this room. A websocket endpoint is one object shared
    // by every connection, so anything per-room lives here and anything per-client
    // lives on the session.
    private final List sessions = Collections.synchronizedList(new ArrayList());

    public void onOpen(WebSocketSession session) {
        sessions.add(session);
    }

    public void onText(WebSocketSession session, String message) {
        // Sending from a thread other than the one that owns a connection is
        // supported, and this is why: a broadcast reaches every session but one
        // from the thread that received the message.
        Object[] open = sessions.toArray();
        for(int iter = 0 ; iter < open.length ; iter++) {
            WebSocketSession other = (WebSocketSession)open[iter];
            if(other == session) {
                continue;
            }
            try {
                other.sendText(message);
            } catch (IOException err) {
                // A send fails when that peer has gone. It is already being torn
                // down; onClose will take it out of the list.
                other.abort();
            }
        }
    }

    public void onBinary(WebSocketSession session, byte[] message, int offset, int length) {
    }

    public void onClose(WebSocketSession session, int code, String reason) {
        sessions.remove(session);
    }
}

Each session serializes its own writers, so two threads can’t interleave halves of two messages on one connection. What the server doesn’t do is queue: sendText writes to the socket and blocks if the peer has stopped reading. That’s honest back pressure rather than a buffer that grows until the machine runs out, but it means one unresponsive client can hold up a loop that broadcasts to every other one. A server with many clients and large messages should broadcast from a small pool rather than from the receiving thread.

35.3.3. Subprotocols

An endpoint that speaks more than one protocol lists them best first:

public static final class Graph implements WebSocket {
    public String[] getSubprotocols() {
        // The server's order decides, not the client's.
        return new String[]{"graphql-transport-ws", "graphql-ws"};
    }

    public void onOpen(WebSocketSession session) {
        if("graphql-ws".equals(session.getSubprotocol())) {
            // The legacy protocol; answer in its shape.
        }
    }

    public void onText(WebSocketSession session, String message) {
    }

    public void onBinary(WebSocketSession session, byte[] message, int offset, int length) {
    }
}

The server’s order decides, not the client’s, so a client can’t select a deprecated protocol over a current one by listing it first. When nothing matches, the handshake still succeeds and names no protocol, which is what the standard describes; getSubprotocol then answers null.

35.3.4. A connection, not a request

A WebSocket is a connection that stopped being HTTP, and the difference is something an author can feel.

Under virtual threads — the default on the packaged runtime — each connection owns one, and a parked virtual thread costs a stack rather than an operating system thread. Ten thousand mostly silent connections is the workload that model was built for.

On the thread pool it’s a worker per connection for as long as the connection lasts. That’s the mode the local development loop always runs in, because the JVM has no virtual threads here, and it’s also the mode any TLS server runs in. A pooled deployment serving many WebSockets has to size workers for them, because unlike a request they don’t give the worker back.

That makes workers the ceiling on concurrent connections in pool mode, and going past it fails in a way worth knowing about: the process stays healthy, the listener stays bound, and new connections are simply refused, because no worker ever comes back to accept them. An eight-worker server driven by the conformance suite reached case 9.4.4 and refused everything after it. The server says so now — it logs once when WebSockets hold half the pool — and the two ways out are more workers or a shorter CN1_WS_IDLE_TIMEOUT_MS, so abandoned connections give their worker back sooner. On virtual threads none of this applies.

The idle timeout is separate for the same reason. CN1_HTTP_TIMEOUT_MS sheds a client that began a request and stopped; a WebSocket is idle by design and would be shed within seconds by that rule. CN1_WS_IDLE_TIMEOUT_MS governs these instead, defaults to five minutes, and accepts 0 for connections that may stay silent indefinitely. CN1_WS_MAX_MESSAGE_MB bounds reassembly, because a message is as large as the peer chooses to make it.

getMetrics() reports webSocketConnections, and an open session doesn’t count towards activeRequests — it’s a connection, and counting it would make an idle server read as permanently saturated.

stop() sends every open connection a 1001 "going away" close before the drain window, so a shutdown reads as one to the client rather than as a network failure.

35.3.5. How the frame layer is checked

Most of RFC 6455 is about frames a conformant client never sends, which is how a server ends up wrong in ways nothing it talks to will reveal. The Autobahn|Testsuite is what finds those, and vm/backend/ws-conformance.sh runs it:

vm/backend/ws-conformance.sh --arm javase     # or --arm native

It needs Docker or Podman, starts an echo server, and drives ~300 cases through it. The gate has no per-case tolerance: every case must pass, and NON-STRICT counts as a failure, because a lenient frame parser is the thing this is looking for. The set of cases that ran also has to match a committed manifest, so the suite can’t shrink unnoticed to the ones that happen to pass.

Sections 12 and 13 are excluded while permessage-deflate is unimplemented. They’re excluded rather than tolerated: accepting their result as a pass would also accept it for a case that used to work.

35.4. Calling other services

Web makes an outbound HTTP or HTTPS request: Web.get, Web.getJson, Web.postJson and Web.request. The server’s certificate and its host name are always verified, and there is no option to turn that off. A WebClient is the same request with settings of its own:

  • a client certificate, for a service that authenticates its callers with mutual TLS. ClientCertificate.pem takes a PEM certificate and key, and ClientCertificate.pkcs12 takes a .p12 archive and its password.

  • setRequireHttp2(true), which makes the request over HTTP/2 or fails it. A server that only speaks HTTP/1.1 never receives the request.

  • a connect timeout, a read timeout (how long the transfer may stall) and a request timeout (the whole request).

  • a pool of connections, so the next request to the same server skips the TCP and TLS handshakes. setReuseConnections(false) opens a new connection for each request.

private final WebClient partner;

/** The PKCS#12 archive and its password, from configuration. */
public PartnerApi(@Value("${partner.p12}") String p12Base64,
                  @Value("${partner.p12Password}") String password) {
    byte[] archive = Base64.decode(p12Base64);
    this.partner = new WebClient()
            .setClientCertificate(ClientCertificate.pkcs12(archive, password))
            .setRequireHttp2(true)
            .setRequestTimeoutMillis(10000);
}

public String balance(String account) throws IOException {
    Web.Result result = partner.getJson(
            "https://api.partner.example/v1/accounts/" + account, null);
    if (!result.isSuccess()) {
        throw new IOException("The partner API answered " + result.getStatus());
    }
    return result.getBodyAsString();
}

Create a client once and share it between requests. Its settings are fixed by its first request, and two clients never share a connection, so a connection authenticated with one certificate is never used for a request made with another. close() releases the pool.

Web.Result.getProtocol() names the protocol the response used. Without the requirement, the packaged server offers HTTP/2 and uses HTTP/1.1 when the other side declines.

The local Java SE runtime speaks HTTP/1.1 only, so there a client that requires HTTP/2 fails every request with an exception that says so. It reads PKCS#12 archives, and PEM keys in unencrypted PKCS#8 or RSA form. The packaged server also reads encrypted PEM keys. A PKCS#12 archive works the same in both.

35.4.1. Streaming a request

Web.request holds the whole response in memory. Web.open (or WebClient.open) returns a Web.Exchange instead, which sends the request body as it’s written and reads the response as it arrives. The length is the body’s size, Web.UNKNOWN_LENGTH for a body of unknown size, or Web.NO_BODY:

static long upload(InputStream file, long length) throws IOException {
    Web.Exchange exchange = Web.open("PUT", "https://storage.internal/blobs/1",
            Collections.singletonList("Content-Type: application/octet-stream"), length);
    try {
        OutputStream up = exchange.getRequestBody();
        byte[] buffer = new byte[64 * 1024];
        for (int n = file.read(buffer); n > 0; n = file.read(buffer)) {
            up.write(buffer, 0, n);
        }
        up.close();
        if (exchange.getStatus() >= 300) {
            throw new IOException("storage answered " + exchange.getStatus());
        }
        InputStream down = exchange.getResponseBody();
        long answered = 0;
        while (down.read() >= 0) {
            answered++;
        }
        return answered;
    } finally {
        exchange.close();               // before the end, this cancels it
    }
}

Write and close the request body first, then read the status, the headers and the response body, all from one thread. Each direction buffers a fixed window, so a slow peer slows its producer. close() ends the exchange in any state. Before the response has been read to its end it cancels the exchange, closing the connection instead of draining it, so always close it in a finally. An exchange never follows a redirect, because a streamed body can’t be sent twice.

35.4.2. Forwarding to another service

HttpProxy forwards a request to another server and streams the answer back, the way a gateway in front of an internal service would:

images = new HttpProxy("https://images.internal:8443")
        .allowHost("cdn.internal");
@RequestMapping("/images/{name}")
public HttpServer.Response image(HttpServer.Request request) {
    return images.forward(request);  // the same path and query, upstream
}

The response body is streamed back as it arrives, and a binary upload is streamed up from wherever it lives, a spooled one included. A text or compressed request body is read whole on arrival, under the 8 MB limit, and forwarded decompressed. Every end-to-end header goes through, a repeated one such as Set-Cookie line by line. The hop-by-hop headers (Connection, Keep-Alive, Proxy-*, TE, Trailer, Transfer-Encoding, Upgrade) and any header a Connection field names are removed in both directions. X-Forwarded-For, X-Forwarded-Proto and X-Forwarded-Host are added unless setForwardedHeaders(false) turns them off.

Only the target’s host is reached, plus the hosts named with allowHost, over http and https. Redirects are passed back to the client. setFollowRedirects(n) follows up to n hops itself, for a request without a body and only to allowed hosts. A hop to another host doesn’t carry the client’s Authorization and Cookie headers.

Failures go both ways. A client that disconnects cancels the upstream exchange. An upstream that fails before answering is a 502. Once the status has been sent, a later upstream failure aborts the client’s response, closing the HTTP/1.1 connection or resetting the HTTP/2 stream, so the client sees a truncated response and never one that looks complete. setClient gives the proxy a WebClient for its timeouts and client certificate.

A static binary in a scratch image has no certificate store. Copy a ca-certificates.crt into the image and name it in CURL_CA_BUNDLE or SSL_CERT_FILE.

The proxy can also rename a request header on the way out (renameRequestHeader), rename a response header on the way back (renameResponseHeader) and replace the status the other service answered with (rewriteStatus), for a service whose conventions differ from the one the app expects.

35.5. Sending push notifications

A WebSocket reaches an app that’s running. A push notification reaches a phone whose app isn’t: a server tells a rider their driver has arrived, or moves the countdown on the lock screen. The server hands the message to the Codename One push service, which delivers it through Firebase, APNs, Huawei, WNS, or Web Push, and the app receives it with PushClient. Codename One Push Notifications covers the app’s half and the Console.

A server needs two values from the Console, both described in Push notifications: the application UUID of the push application, and a server API key created with the push scope. The key is a credential; keep it in configuration or the environment, never in source and never in the app.

CloudPush sends, PushNotification builds the message, and PushTarget names a device:

private final CloudPush push;

/**
 * The application UUID and a push-scoped server API key, read from
 * cn1.push.appId and cn1.push.serverKey -- or from the environment
 * variables CN1_PUSH_APPID and CN1_PUSH_SERVERKEY, which override them.
 */
public RideNotifications(@Value("${cn1.push.appId}") String appId,
                         @Value("${cn1.push.serverKey}") String serverKey) {
    this.push = new CloudPush(appId, serverKey);
}

/** deviceKey is what the app registered, such as "cn1-fcm-..." */
public boolean driverArrived(String deviceKey, String tripId) throws IOException {
    PushNotification message = PushNotification.builder()
            .title("Your driver is here")
            .body("Look for the blue sedan")
            .deepLink("ride://trip/" + tripId)
            .collapseKey("trip-" + tripId)
            .data("tripId", tripId)
            .build();
    PushResult result = push.send(message, PushTarget.fromDeviceKey(deviceKey));
    if (result.getStatus() == 429) {
        // Not admitted; try again after result.getRetryAfterSeconds()
        return false;
    }
    return result.isAccepted();
}

A device is a provider and that provider’s token. PushTarget.of("fcm", token) takes the two values and accepts the older spellings the app can report (gcm, ios, hms). PushTarget.fromDeviceKey reads the cn1-fcm-…​ form that Push.getPushKey() returns. One send can address many devices at once.

PushNotification writes the same envelope the app’s PushMessage reads: title, body, image, deep link, collapse key, time to live, silent delivery, application data, and options for one provider. A message needs a body, data, or a surface command.

35.5.1. Live Activities and widgets

A message can carry a command the app applies before its listener runs, which keeps a Live Activity or a widget current while the app is in the background. Three helpers build the command:

  • PushNotification.liveUpdate(id, state) gives a running activity new state.

  • PushNotification.liveEnd(id, finalState, dismissImmediately) ends it, optionally with a last state.

  • PushNotification.widget(kind, timelineJson) publishes new widget content.

public PushResult updateEta(PushTarget device, String tripId, int minutes)
        throws IOException {
    Map<String, Object> state = new LinkedHashMap<String, Object>();
    state.put("minutes", Integer.valueOf(minutes));
    state.put("status", minutes == 0 ? "arrived" : "on the way");
    PushNotification message = PushNotification.builder()
            .silent(true)
            .surface(PushNotification.liveUpdate("trip-" + tripId, state))
            .build();
    return push.send(message, device);
}

public PushResult tripEnded(PushTarget device, String tripId) throws IOException {
    PushNotification message = PushNotification.builder()
            .silent(true)
            .surface(PushNotification.liveEnd("trip-" + tripId, null, true))
            .build();
    return push.send(message, device);
}

The id is the one the app started the activity under, and the state map uses the names the activity’s layout binds. The helpers turn the map into the JSON string the envelope carries, with its keys sorted the way the app writes state itself. Codename One Push Notifications describes how each platform applies a command.

35.5.2. What the answer means

send returns a PushResult for every answer the service gives, a refusal included. isAccepted() is true for a 202, and that means admitted: the service has queued the message durably, but no provider or device has seen it yet. Whether it arrived is reported later, through delivery feedback. getDeliveryIds() lists one id per admitted target, to match against that feedback.

A refusal carries its status and the service’s explanation in getError():

  • 400: the request is malformed, such as an unknown provider or an appId that isn’t the application UUID.

  • 401: the key is missing, wrong, or lacks the push scope.

  • 402: the account doesn’t include what the message asked for.

  • 429: slow down. getRetryAfterSeconds() says how long to wait, or answers -1 when the service didn’t say.

Only a request that got no answer at all, because the service was unreachable or the connection failed, throws an IOException. Each notification is one HTTPS request on the calling thread, so a server that notifies as part of handling a request can hand it to an @Async method rather than make its own caller wait. withEndpoint points a sender at another URL, such as a stub server in a test.

36. Compiled HTML views

The backend can serve HTML applications without a Codename One client. Write HTML with a supported subset of Thymeleaf attributes, return view names from Java controllers, and use htmx when an interaction should update part of the page. The build parses the templates and produces Java renderers. Native packaging translates those renderers through ParparVM to C along with the rest of the server. There is no template engine, expression interpreter or compiler in the request path.

The runnable example is scripts/backend-mvc. It includes an in-memory product catalog, form errors, CSRF protection, shared page fragments, and a pinned local htmx script. Its forms work with JavaScript disabled too.

36.1. Controllers and models

Use com.codename1.backend.annotations.Controller for HTML controllers and com.codename1.backend.mvc.Model for their model. Existing REST controllers retain their response semantics. An HTML controller uses the same mapping annotations, constructor injection, sessions and security chains as a REST controller.

@GetMapping("/products")
public synchronized String list(Model model) {
    model.addAttribute("products", new ArrayList<HtmlProduct>(products));
    return "products";
}

A string return value selects a compiled view. products selects src/main/resources/templates/products.html; products :: rows selects that file’s named fragment. redirect:/products redirects to a local absolute path: 303 for normal requests, or 200 with HX-Redirect for requests from htmx. A null return is 404. Unknown view names fail the request; they never resolve file paths.

ModelAndView carries a view name and attributes added with addObject. @ResponseBody, on the method or controller, retains the REST response rules. An explicit HttpServer.Response is returned unchanged. A view’s default status is 200; @ResponseStatus can change it.

36.2. Typed HTML

Declare model types with comments. Names are explicit and types are fully qualified:

<!-- cn1:model products java.util.List<com.codenameone.developerguide.backend.HtmlProduct> -->
<ul th:fragment="rows">
  <li th:each="product : ${products}">
    <a th:href="@{/products/{id}(id=${product.id})}"
       th:text="${product.name}">Example product</a>
  </li>
</ul>

The build resolves public JavaBean getters or public fields and emits direct access. Generic type arguments are preserved through getters, fields, and inherited classes or interfaces. A missing property or undeclared model name fails the build with the file and source position. At runtime, a referenced model must be present and have the declared type. A present null renders as empty text; property navigation propagates null. Numeric comparisons require non-null operands. Fragments only require model names they read. Loops accept collections and object or primitive arrays, and check element types before access. Null collections and arrays produce no rows.

Supported directives:

  • th:text, th:if, th:unless, and th:each="item, status : ${items}". The optional status exposes index, count, size, first, last, even, and odd.

  • th:href, src, action, value, id, name, class, title, alt, placeholder, method, and for, plus th:classappend.

  • Boolean attributes checked, selected, disabled, readonly, multiple, required, autofocus, and hidden.

  • th:attr="attribute=expression, other=expression", including htmx URLs.

  • th:fragment="name", th:insert="~{layout :: name}", and

    `th:replace="~{layout

    name}"`. References are static, fragments have no parameters, and recursive inclusion is a build error. th:block adds no wrapper.

  • th:object, th:field, and th:errors for forms.

Expressions support ${model.property}, typed list/array/map indexing, string, number, boolean and null literals, boolean operators, equality, numeric comparisons, addition/subtraction, and condition ? yes : no. Selection expressions *{field} use the enclosing th:object. URL expressions use local paths with encoded path and query arguments, such as @{/search(q=${query})}.

Dynamic text and attributes are HTML-escaped. URL arguments use URL encoding before attribute escaping. Dynamic URL attributes reject executable URL schemes. Dynamic htmx attributes that evaluate expressions (hx-on*, hx-vars, hx-vals, hx-headers, hx-request, and hx-trigger) are rejected, including data-hx-* aliases. Define those attributes as static template content. Script sources, link-resource URLs (including stylesheets), and base URLs must be static template attributes. Meta http-equiv directives, including refresh content, must also be static. Named metadata such as a description can use dynamic content. Dynamic attributes are evaluated once per rendered element, including each iteration of a loop. Raw HTML, dynamic script/style content, arbitrary method calls, expression preprocessing, message expressions, inline expressions, custom dialects, and Spring EL are outside this subset. Unsupported th: attributes fail the build. This is a syntax-compatible subset, not the Thymeleaf library.

36.3. Forms and validation

A mapped method can receive a dedicated form DTO:

@PostMapping("/products")
public synchronized String save(@ModelAttribute("form") ProductForm form,
                               BindingResult errors, Model model) {
    if (form.name == null || form.name.trim().isEmpty()) {
        errors.rejectValue("name", "Enter a name.");
    }
    if (errors.hasErrors()) {
        return "edit";
    }
    products.add(new HtmlProduct(products.size() + 1, form.name));
    return "redirect:/products";
}

Form DTOs need a public no-argument constructor and writable scalar fields or setters. Supported values are strings, numeric primitives/boxes, booleans and characters. Nested objects, collections, file uploads through the form DTO, and ORM entities are refused. Bind identifiers through route parameters. Unknown submitted fields are ignored; no property path from a request is executed.

BindingResult must immediately follow its form parameter. Conversion errors are recorded before the controller runs. Without a BindingResult, conversion failure returns 400. reject(message) adds a global error; rejectValue(field, message) adds a field error. Validation is application code; Bean Validation annotations aren’t implemented.

<!-- cn1:model form com.codenameone.developerguide.backend.ProductForm -->
<form method="post" action="/products" th:object="${form}">
  <label for="name">Name</label>
  <input th:field="*{name}">
  <span th:errors="*{name}"></span>
  <button type="submit">Save</button>
</form>

th:field renders the name, a default id, and the submitted value if binding failed. It supports inputs, textareas, scalar selects, checkboxes and radio buttons. Boolean checkboxes use field presence, including with custom values. They emit a hidden marker so an unchecked field binds to false. The marker shares the checkbox’s disabled state and form association. Without a marker, Boolean fields use strict value conversion. th:errors="{}" renders all errors for the selected form. Use distinct explicit ids for radio buttons in a group. Multiple-selection collection binding is deferred.

Each @ModelAttribute parameter on a route must have a distinct name; duplicate names fail the build instead of overwriting form objects and validation results.

36.4. htmx, CSRF and assets

Ordinary hx-* attributes pass through. Put hx-post on a form and target a named fragment’s wrapper. Htmx.isRequest(request) distinguishes fragment requests from normal navigation and history restoration. A controller chooses the view; request headers never select a template themselves. Return form-error fragments with status 200 so htmx swaps them normally. Htmx.redirect, refresh, and trigger provide response-header helpers.

The existing security chain remains responsible for CSRF enforcement. The model contains _csrf, whose type is declared automatically. Unsafe forms include a hidden CSRF token when one is available for native POST submissions. Mutating htmx controls also send the configured CSRF header, including standalone controls outside forms. Authored hx-headers must be a JSON object on these controls; other headers are preserved, and the configured token header takes precedence. Form action, submit-control formaction, htmx URLs (hx-get, hx-post, hx-put, hx-patch, hx-delete), and static base URLs must be local absolute paths such as /products/save, or empty to use the current document. This applies to static and dynamic form destinations, including controls in fragments, to prevent submissions from disclosing the generated token to another origin. This includes read requests because htmx inherits headers from ancestor elements. For hx-get and hx-delete, generated hx-params filtering excludes the CSRF parameter while preserving the token for a native POST fallback. Explicit parameter allow lists and exclusion lists are retained; included fragments receive their parent’s original parameter filter, so nested POST requests don’t inherit the URL parameter CSRF exclusion. The configured CSRF parameter name is used. When a CSRF token is available, submit controls can’t override the native method with GET or an invalid value that defaults to GET. This restriction also applies to controls in fragments or controls linked to a form by its ID. Use a separate GET form for searches and previews. POST and dialog overrides remain supported. Form enctype and submit-control formenctype support application/x-www-form-urlencoded and multipart/form-data. Unsupported static encodings fail the build; unsupported dynamic values fail rendering. In particular, text/plain isn’t supported by form binding. For requests outside forms, supply the existing token header explicitly. Defining HTML controllers doesn’t enable a security chain automatically.

Files in src/main/resources/static are embedded at build time and served under /static/ after controller routes. Only enumerated assets are accessible; templates are private. Embedded assets use Cache-Control: no-cache and nosniff. Use URL-safe ASCII filenames. Each embedded asset is limited to 2 MiB; use the existing cn1.static.root facility for larger files.

36.5. Building and porting

Maven compiles views during process-annotations in process-classes; native packaging also runs this compiler. Gradle uses the same engine and tracks templates and static assets as compilation inputs. Rebuild after editing HTML. Generated view and asset registries are replaced on each build, including after file deletion. The first request only executes generated code.

To port a small Spring MVC application, change the controller/model imports, add template model declarations, use dedicated scalar form DTOs, and replace unsupported expressions or dialect features. Keep existing HTML and htmx attributes within the supported subset. Controller advice, method-level @ModelAttribute, flash attributes, forward: views, custom converters, dynamic fragment selectors, and internationalized message bundles aren’t part of this first version.

36.6. Images on the server

A backend often has to produce an image: a sharing card for a link, a thumbnail of an upload, a badge, or a chart exported as PNG. A server has no display, so com.codename1.backend.image draws and encodes images in pure Java, with no platform code. It runs on the JVM and in a backend translated by ParparVM alike. A client application uses com.codename1.ui.Image and Graphics instead.

  • RasterImage holds non-premultiplied ARGB pixels, and crops, rotates, flips and resizes them. Its resize filters (NEAREST, BILINEAR, BICUBIC, LANCZOS, BOX and HAMMING) produce the same bytes as Pillow.

  • RasterGraphics draws antialiased lines, rectangles, rounded rectangles, ellipses, arcs, polygons and Bezier paths, with stroke width, caps and joins, an affine transform, a clip rectangle, alpha, linear and radial gradients and scaled images.

  • TrueTypeFont reads a TrueType font for RasterGraphics.drawString. TrueTypeFont.createDefault(size) needs no font file: it embeds Aileron, the font Pillow uses for ImageFont.load_default().

  • PngCodec reads every PNG variant and writes 8-bit PNG; JpegCodec reads baseline and progressive JPEG and writes baseline JPEG.

public static byte[] card(int accent) {
    RasterImage card = new RasterImage(1200, 630);
    RasterGraphics g = card.createGraphics();
    g.setPaint(RasterGradient.linear(0, 0, 0, 630,
            new float[] {0, 1}, new int[] {0xff0f172a, accent}));
    g.fillRect(0, 0, 1200, 630);
    g.setPaint(null);
    g.setColor(0xccffffff);
    g.fillRoundRect(60, 60, 1080, 510, 48, 48);
    g.setColor(accent);
    g.setStrokeWidth(12);
    g.setLineCap(RasterGraphics.CAP_ROUND);
    g.drawLine(120, 500, 1080, 500);
    return PngCodec.encode(card);
}

public static byte[] thumbnail(byte[] upload) throws IOException {
    RasterImage src = JpegCodec.isJpeg(upload)
            ? JpegCodec.decode(upload) : PngCodec.decode(upload);
    int w = 320;
    int h = Math.max(1, src.getHeight() * w / src.getWidth());
    return JpegCodec.encode(src.scale(w, h, Resampler.LANCZOS), 0.85f);
}

A handler returns the encoded bytes with the matching content type, such as image/png. A Python backend gets the same classes through Pillow: PIL.Image, ImageDraw and ImageFont run on them in a server build, pixel for pixel.

37. Backend beans and dependency injection

A server that does everything in its controllers turns into classes nobody can test. This chapter covers the alternative Spring made standard: split the work into beans, let each one declare what it depends on, and have something else build them and hand them over. Here that something is the build, which is the difference worth keeping in mind throughout: every decision below is made while the project compiles, and a decision the build can’t make is an error before the server ever starts.

37.1. Services and dependency injection

A controller that does everything itself turns into a class nobody can test. The usual split is Spring’s: controllers translate HTTP, services hold the logic, repositories hold the SQL, and each one receives what it depends on instead of building it. The annotations are Spring’s too, under com.codename1.backend.annotations:

@Component
public class Signups {
    private final DataSource db;

    @Autowired
    private Mailer mailer;

    public Signups(DataSource db) {
        this.db = db;
    }

    @PostConstruct
    void createTable() throws IOException {
        db.execute("CREATE TABLE IF NOT EXISTS signup (email VARCHAR(200))", null);
    }
@RestController
public class SignupApi {
    private final Signups signups;

    public SignupApi(Signups signups) {
        this.signups = signups;
    }

    @PostMapping("/signups")
    public String signUp(@RequestParam("email") String email) throws Exception {
        signups.register(email);
        return "ok";
    }

    @GetMapping("/signups/count")
    public String count() throws Exception {
        return String.valueOf(signups.count());
    }
}

@Component marks a bean; a @RestController, @WebSocketMapping or @Configuration class is one too. A class with one constructor gets that constructor; with several, the one marked @Autowired. Fields and setters are injected only when marked @Autowired, and a private field is fine.

What makes this different from Spring is when it happens. The build finds every bean, decides which constructor each gets and which bean fills each injection point, and writes that down as a class called BackendWiring — a list of new calls, setter calls and @PostConstruct calls in dependency order. At run time there is no container, no classpath scan and no reflection, so a server with twenty beans starts as fast as one with none, and the translator can still drop every class nothing reaches. A dependency that can’t be satisfied is a build error that names the injection point, rather than a server that fails its first request:

constructor parameter 1 of com.example.SignupApi needs a com.example.Signups,
and no bean has that type. Annotate the implementing class @Component,
or declare a @Bean method returning one.

Two beans of one type are an error too, until one is marked @Primary or the injection point names one with @Qualifier. Constructors that depend on each other in a circle are refused; the same circle through @Autowired fields is fine, because fields are set after every bean exists.

37.2. Declaring beans

A bean is a class the build constructs once per server and hands to everything that needs it. These annotations make a class one:

AnnotationUse it for

@Component

Anything the application wires together.

@Configuration

A class whose @Bean methods produce beans, described under Section 37.5, “Profiles and factory methods”. It’s a bean itself, so it’s injected too.

@RestController, @WebSocketMapping

A controller or a WebSocket endpoint. Both are beans, and both are always singletons.

A bean’s name is the simple class name with its first letter lowercased — smtpMailer for SmtpMailer — unless the annotation gives one, as @Component("invoice") does. Names matter only to @Qualifier, and two beans with the same name are a build error.

A bean has to be a class the build can construct: concrete, and static if it’s nested. It also has to be public unless it’s in the package the generated entry point lives in, since the generated code has to name it.

37.3. Injection points

A bean receives its dependencies in three places, all resolved by type:

  • The constructor. A class with one constructor gets that one. With several, the build takes the one marked @Autowired, or failing that the one with no arguments; with neither it can’t choose and says so. Constructor injection is the one to prefer, because the object is complete the moment it exists and a test builds it with new.

  • A field marked @Autowired. A private field is fine: the build adds a setter to the compiled class and the generated code calls it, so there is no reflection. A final field can only be set by the constructor, and marking one @Autowired is a build error that says so.

  • A method marked @Autowired, called once with its parameters resolved like a constructor’s.

Injection points and lifecycle methods declared in a superclass count too, and are handled before the subclass’s own, and the same goes for @Scheduled, @McpTool and managed methods: a job a base class declares runs for every bean that inherits it. A method the subclass overrides follows the subclass’s annotations, not the superclass’s. The build can only do this for a superclass compiled from the project’s sources: a base class from a jar that has injected fields, or lifecycle methods that aren’t public, is a build error telling you to take those dependencies in the subclass instead.

@Autowired(required = false) leaves the point null when no bean has its type, where a required point is a build error. A List<T> or Collection<T> receives every bean of type T:

@Component
public class Checkout {
    private final PaymentProvider preferred;       // the @Primary one: CardPayments

    @Autowired
    @Qualifier("invoice")
    private PaymentProvider invoice;               // the one named "invoice"

    @Autowired
    private List<PaymentProvider> all;             // every PaymentProvider bean

    @Autowired(required = false)
    private Audit audit;                           // null when no bean provides one

    public Checkout(PaymentProvider preferred) {
        this.preferred = preferred;
    }

When several beans have the injected type and the point names none, the build takes the one marked @Primary:

@Component
@Primary
public class CardPayments implements PaymentProvider {
    public String name() {
        return "card";
    }
}

Without one it’s an error listing the candidates, and two @Primary beans of one type are an error too. @Qualifier("invoice") names the bean a point wants and overrides @Primary. The single exception is a set of candidates that are all conditional — a @Profile("dev") bean and a @Profile("!dev") one — where at most one exists at run time and the generated code picks whichever does.

Some types aren’t beans the application declares, but the server provides them and they’re injected the same way:

TypeWhat it receives

Config

The server’s configuration, for keys read at run time.

DataSource

The connection pool. A bean that takes one makes a database required, and a server with none configured refuses to start with a message naming the bean.

orm.EntityManager

The entity manager over that pool, when the module has entities.

com.codename1.orm.session.Session

The current transaction’s persistence session, described under Chapter 39, Backend data access and transactions.

A @Repository interface

The generated repository, over that same session. One instance serves every injection point, and like the session it works inside a @Transactional method. A bean of the interface’s type, when one is declared, is injected instead.

HttpServer.Request

The current request. Only a @Scope("request") bean can take it.

HttpSession

The current session. Only a @Scope("request") bean can take it.

37.4. Configuration values

@Value reads a setting, with a fallback after the colon, and converts it to the field’s type:

@Component
@Profile("!dev")
public class SmtpMailer implements Mailer {
    @Value("${mail.host:localhost}")
    private String host;

    @Value("${mail.port:25}")
    private int port;

    public void send(String to, String subject, String body) {
        // ... talk to host:port ...
    }
}

The value comes from the layers described under Section 34.8, “Configuration and profiles”, so MAIL_HOST in the environment overrides the file. A key with no fallback that nothing sets stops the server at startup with the key’s name. @ConfigurationProperties("mail") on a bean does the same for every one of its setters at once: setHost reads mail.host, and setMaxSize reads mail.maxSize or mail.max-size.

@Value converts to a String, a primitive or its box, or an enum; a field of any other type is a build error. A key that has no fallback and isn’t set in application.properties gets a build warning, since it can still come from the environment at run time.

@ConfigurationProperties suits a group of related settings better than a @Value per field, and a bean that holds them is an ordinary bean that others inject:

@Component
@ConfigurationProperties("mail")
public class MailSettings {
    private String host = "localhost";   // kept when mail.host is not set
    private int port = 25;
    private boolean startTls;

    public void setHost(String host) {          // mail.host
        this.host = host;
    }

    public void setPort(int port) {             // mail.port
        this.port = port;
    }

    public void setStartTls(boolean startTls) { // mail.startTls or mail.start-tls
        this.startTls = startTls;
    }

Each setter taking a String, a number, a boolean or an enum is bound from the prefix plus the property name, in camel case or kebab case. A setter whose key isn’t set is never called, so the field keeps its initial value — which is where a default belongs. A prefix that binds no setter at all is a build error, since it means the class and the prefix disagree.

37.5. Profiles and factory methods

@Profile and @ConditionalOnProperty make a bean depend on the deployment:

@Component
@Profile("dev")
public class ConsoleMailer implements Mailer {
    public void send(String to, String subject, String body) {
        System.out.println("mail to " + to + ": " + subject);
    }
}

The profile is the one choice the build can’t make for you, so it becomes a single if in the generated startup code. @ConditionalOnMissingBean is decided entirely at build time: the bean steps aside when the application declares another of its type.

A class from a library can’t carry annotations. A @Bean method in a @Configuration class makes one:

@Configuration
public class Limits {
    @Bean
    public RateLimiter signupLimiter(@Value("${signups.perMinute:30}") int perMinute) {
        return new RateLimiter(perMinute);
    }
}

The build calls the method once, directly. There is no proxy around the configuration class, so one @Bean method calling another gets a second object; take the other bean as a parameter instead, which the build fills like a constructor’s.

37.5.1. Conditions in detail

@Profile takes one or more profile names, and the bean exists when any of them is active. A name starting with ! is negated, so @Profile("!prod") covers every profile but prod.

@ConditionalOnProperty makes a bean depend on a key:

@Component
@ConditionalOnProperty(value = "search.enabled", havingValue = "true")
public class SearchIndexer {
    public void index(String document) {
        // ...
    }
}

With havingValue, the key must equal that value, compared ignoring case. Without it, any value but false counts. matchIfMissing = true makes an unset key count as a match, and several keys in value must all match. prefix is put in front of each key with a dot.

Both are evaluated once, at start-up, as one if around the bean’s construction. Which beans are on depends on the deployment’s configuration, so it’s the start that checks it, as Spring’s does: a bean that requires one whose conditions are all off under the running configuration stops the server from starting, with an error naming the injection point. Cover the other case with a bean of the same type under the opposite condition, make the dependency optional, or give the dependent bean the same condition.

@ConditionalOnMissingBean is the one condition decided entirely at build time. It marks a default that steps aside when the application declares another bean it would compete with, which is how a module offers a fallback:

@Configuration
public class Defaults {
    @Bean
    @ConditionalOnMissingBean
    public Audit audit() {
        return new LogAudit();      // used only when the application declares no Audit
    }
}

With no arguments, "another bean it would compete with" means one that has any of the types the default can be injected as, apart from the JDK’s own: its class, its superclasses and its interfaces. On a class, DefaultMailer implements Mailer steps aside for any other Mailer. On a @Bean method they’re the declared return type and the types above it, which is why the method above returns Audit rather than LogAudit. @ConditionalOnMissingBean(Audit.class) names the types to compete on explicitly, for a class whose default set is too wide or too narrow.

A @Bean method inherits the conditions of the @Configuration class it’s declared in, static methods included. A @Profile("prod") configuration class therefore contributes nothing on any other profile, which is what the annotation on the class says. The same holds for @ConditionalOnMissingBean on the class: a configuration class that steps aside takes its @Bean methods with it.

37.5.2. Beans with a lifecycle of their own

A library class often has methods to start and stop it, and no annotations to say so. @Bean names them:

@Configuration
public class SearchConfig {
    @Bean(initMethod = "connect", destroyMethod = "close")
    public SearchClient searchClient(@Value("${search.url:http://localhost:9200}") String url) {
        return new SearchClient(url);
    }
}

initMethod runs after the factory method returns, where a class’s @PostConstruct would. destroyMethod runs where its @PreDestroy would: at shutdown for a singleton, at the end of the request for a request-scoped bean, and when the session ends for a session-scoped one.

37.6. Scopes

A bean is a singleton unless it says otherwise. @Scope("prototype") gives each injection point its own instance. @Scope("request") and @Scope("session") give one per HTTP request or session; injected into a singleton, such a bean is reached through a small generated subclass that finds the current request’s instance on each call, so the class can’t be final and needs a constructor that takes no arguments. @Lazy builds a bean the first time it’s used, through the same kind of subclass. That subclass has to run the bean’s constructor once at startup to exist at all, so the expensive part of setting a bean up belongs in its @PostConstruct method, which runs only on the real instance.

ScopeInstances

singleton, the default

One per server, built at start-up in dependency order.

@Scope("prototype")

A new instance for each injection point. Two fields of type Ticket in one class get two tickets.

@Scope("request")

One per HTTP request, built the first time the request uses it and destroyed when the request ends.

@Scope("session")

One per HTTP session, kept by the server for as long as the session lives and destroyed when it ends. See Chapter 40, Backend sessions.

@Lazy, on a singleton

One per server, built the first time something calls it.

A request-scoped bean looks like any other to the code that uses it:

@Component
@Scope("request")
public class RequestClock {
    private final long started = System.currentTimeMillis();

    public long elapsed() {
        return System.currentTimeMillis() - started;   // since THIS request's instance
    }
}

A controller that injects RequestClock gets the generated stand-in, and each call on it reaches the instance belonging to the request being served. Two requests served at once see two instances.

The stand-in extends the bean’s class and overrides its methods, which is where the rules for a scoped or lazy bean come from. The class can’t be final, a method it declares or inherits can’t be final either — a call to it would run on the stand-in instead of the bean — and it needs a constructor with no arguments, which may be protected. Methods inherited from a library class are forwarded too, so the library has to be on the build’s classpath. Inject anything else through fields. Each rule is checked by the build.

@Lazy suits a bean that’s expensive to prepare and not always needed:

@Component
@Lazy
public class ExpensiveIndex {
    private Map<String, String> index;

    public ExpensiveIndex() {
        // Runs at start-up for the generated stand-in too: keep it cheap.
    }

    @PostConstruct
    void load() {
        // Runs once, on the real instance, the first time something calls it.
        index = new HashMap<String, String>();
    }

    public String lookup(String key) {
        return index.get(key);
    }
}

A WebSocket endpoint must be a singleton, since it serves the whole life of the server rather than one request. A bean with @Scheduled methods can’t be request- or session-scoped, because a job runs outside any request. A prototype-scoped one only draws a warning, as in Spring: one instance is built to run its jobs and is never destroyed, so make it a singleton if it needs @PreDestroy.

37.7. Lifecycle

Beans are built in dependency order, and a bean’s @PostConstruct method runs once it and everything it depends on has been built and injected. At shutdown, @PreDestroy methods run in the reverse order, so a bean’s dependencies are still there when its own method runs. Within one bean the same rule holds for its class hierarchy: a superclass’s @PostConstruct runs before the subclass’s, and a subclass’s @PreDestroy runs before the superclass’s:

@Component
public class Outbox {
    private final DataSource db;
    private final List<String> pending = new ArrayList<String>();

    public Outbox(DataSource db) {
        this.db = db;
    }

    @PostConstruct
    void createTable() throws IOException {
        // Every dependency is built, injected and initialized by now.
        db.execute("CREATE TABLE IF NOT EXISTS outbox (message VARCHAR(500))", null);
    }

    public synchronized void add(String message) {
        pending.add(message);
    }

    @PreDestroy
    synchronized void flush() throws IOException {
        // After the last request has finished, before the pool closes.
        for (String message : pending) {
            db.execute("INSERT INTO outbox (message) VALUES (?)", new Object[] {message});
        }
        pending.clear();
    }
}

Both methods take no arguments and may have any visibility; the build adds a public bridge to reach a private one. Stopping a server goes in this order, which is what makes the flush above safe:

  1. Scheduled jobs stop starting, so none begins while the server drains.

  2. The server stops accepting and waits, up to cn1.server.shutdownTimeoutMillis, for the requests in flight.

  3. @Async calls and scheduled runs that haven’t finished get the same grace. A task still waiting in a queue when that time is up is dropped rather than started against beans about to be destroyed, and the threads of the ones still running are interrupted.

  4. @PreDestroy and destroyMethod run, in reverse dependency order.

  5. The connection pool closes.

  6. The last metrics and spans are exported.

A start-up that fails partway runs the destroy methods of the beans already built, so a server a supervisor restarts doesn’t leak what their constructors opened.

Once the server is listening, every bean implementing CommandLineRunner or ApplicationRunner runs, ordered by @Order. The first receives the command line as it was given; the second receives it as ApplicationArguments, with --name=value options parsed. After them, every method annotated @EventListener that takes an ApplicationReadyEvent is called. Backend.getArguments() returns the same command line anywhere. A listener for any other event is refused at build time: the ready event is the only one the backend publishes.

37.8. Controllers and beans from a library

A server’s wiring is generated while it builds, from the classes it compiles. A library can take part in that wiring: its @RestController classes get routes, its @Component and @Service classes become beans, its entities and repositories get their data access, and its db/migration scripts run, all as if the server had compiled them itself. The server’s own code can inject the library’s beans like any other.

A jar opts in by carrying the empty resource META-INF/codenameone/backend-library. A jar without the marker is an ordinary dependency: its classes are on the classpath, but none of them are wired.

A cn1lib carries its server half inside the .cn1lib file, as backend.zip beside the client parts:

  • A library made from the Maven cn1lib archetype has a backend module. Put the server classes in backend/src/main/java; the module already holds the marker. When the module has sources or resources of its own, the .cn1lib includes it, and a server that uses the library depends on the <library>-backend artifact (or the backend classifier of an installed .cn1lib):

    <dependency>
      <groupId>com.example</groupId>
      <artifactId>notelib-backend</artifactId>
      <version>1.0</version>
    </dependency>
  • A Gradle cn1lib puts the server classes in src/backend/java and publishes them as <library>-backend, marked.

  • A library with no client side is a plain jar that depends on codenameone-backend with provided scope and carries the marker.

The library itself is never wired at its own build; only the server that uses it generates the routes and beans. When the server defines a class with the same name as one in a library, the server’s class is used.

37.8.1. The app kit

The app kit is a cn1lib built this way, published with Codename One under the same version. It holds the plumbing a client and server application usually needs, so a project needs no copy of its own:

  • On the client, com.codename1.appkit.Net adapts a generated client call to a pair of success and failure callbacks, Skeleton is a loading placeholder, and Chart draws a small bar chart with its Meter.

  • On the server, com.codename1.appkit.server.Caller reports the signed-in user and their roles, Text validates and trims request fields, and Grants ends a user’s other sessions. AccountSecurity builds the password encoder, the user store and the registered client a sign-in flow needs. None of these is a bean of its own: the kit wires nothing into a server until the server declares it, so a server that takes only Text needs no authorization server.

  • The push package sends notifications through PushSender. It ships with a sender for the push service, one that prints to the console in development, one that records what was sent for tests, and one that fails with a clear message when push has no configuration.

A project adds cn1-app-kit-lib to its client dependencies and cn1-app-kit-backend to its server, both at the Codename One version it builds with.

37.9. What the build refuses

Everything a container would discover at start-up is checked while the module compiles, and each refusal names the class and member at fault:

Message fragmentWhat to do

needs a X, and no bean has that type

Annotate the implementation @Component, or add a @Bean method returning one.

could receive any of …​

Mark one @Primary, or inject with @Qualifier("name").

The constructors form a cycle

Inject one side through an @Autowired field or setter, which is set after every bean exists.

is final, so it can only be set by the constructor

Take the dependency as a constructor parameter.

and none is marked @Autowired or takes no arguments

Mark the constructor the build should call.

is reached through a class the build generates to stand in for it

A scoped or lazy bean: make the class and its methods non-final and give it a constructor with no arguments.

asks for the current request

Only a @Scope("request") bean can inject the request. Take it as a parameter of the handler method instead.

Two beans are named

Give one a name of its own in its annotation.

37.10. How this differs from Spring

The annotations mean what they mean in Spring, and most code reads the same. The differences all follow from doing the work at build time:

  • No scanning. A bean is a class in the module, or the result of a @Bean method. A jar on the class path contributes nothing unless a @Bean method builds something from it.

  • No proxies for aspects. @Transactional, @Async, @Timed and @Counted rewrite the method itself, so they apply to a call through this, to a private method, and to an object built with new. In Spring each of those skips the aspect, and nothing says so.

  • No proxy around @Configuration. One @Bean method calling another gets a second object. Take the other bean as a parameter instead.

  • Errors at build time. A missing or ambiguous dependency, a constructor cycle, a scoped bean that can’t be subclassed and a malformed cron expression all fail the build.

  • No ApplicationContext. Nothing looks a bean up by name or type at run time. A class that needs a bean declares it as a dependency.

37.11. Testing beans and the wired server

Constructor injection is a constructor, so a unit test builds the object with fakes and needs nothing else. For the wired server — what @SpringBootTest does in Spring — annotate a test class with @BackendTest. It starts the application with the build’s wiring, lets the test replace beans, and sends requests through MockMvc or over a real port. Chapter 38, Backend testing covers it.

38. Backend testing

A backend module’s tests are JUnit 5 classes in src/test/java, written against the API a Spring Boot test uses. @BackendTest starts the module’s server, wired the way it ships, and injects what the test asks for. MockMvc sends a request to that server inside the test process, and TestRestTemplate sends one over a real port. A test can add beans of its own and replace the application’s. This chapter covers each of those, and then the same tests compiled into a native binary.

Because the names follow Spring’s, a test ported from Spring Boot mostly needs its imports changed. The differences are listed at the end of the chapter.

38.1. Setting up a module for tests

A backend module created from the project template is already set up. In another module, add the test library and JUnit 5 to the pom.xml:

<dependency>
    <groupId>com.codenameone</groupId>
    <artifactId>codenameone-backend-test</artifactId>
    <version>${cn1.version}</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>5.9.3</version>
    <scope>test</scope>
</dependency>

Then bind two more goals of the Codename One plugin beside process-annotations, and give each test class a fresh JVM:

<execution>
    <id>cn1-process-test-annotations</id>
    <phase>process-test-classes</phase>
    <goals>
        <goal>process-test-annotations</goal>
    </goals>
</execution>
<execution>
    <id>cn1-compiled-tests</id>
    <phase>test</phase>
    <goals>
        <goal>backend-test</goal>
    </goals>
</execution>
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>3.0.0-M5</version>
    <configuration>
        <reuseForks>false</reuseForks>
    </configuration>
</plugin>

process-test-annotations generates the code each test class runs against. backend-test runs the compiled tests, and does nothing unless they’re asked for. A server process runs one backend at a time, so reuseForks set to false keeps the state of one test class’s server away from the next class.

Run the tests with:

mvn -pl backend -Dcodename1.platform=backend test

A Gradle backend gets the same setup from the Codename One plugin: the test library, JUnit 5, a fresh JVM per test class and the test pass all come with it. The standard test task runs the tests, and backendTest runs them as a native binary, as described below:

./gradlew test          # on this JVM
./gradlew backendTest   # as a native binary

38.2. Testing a controller with MockMvc

This controller answers a greeting as JSON, using a Greetings bean:

@RestController
public class GreetingApi {
    private final Greetings greetings;

    public GreetingApi(Greetings greetings) {
        this.greetings = greetings;
    }

    /** A JSON object holding the greeting. */
    @GetMapping("/greet/{name}")
    public Map<String, Object> greet(@PathVariable("name") String name) {
        Map<String, Object> out = new LinkedHashMap<>();
        out.put("greeting", greetings.greet(name));
        return out;
    }
}

A test of it reads the way a Spring MVC test does:

import com.codename1.backend.annotations.Autowired;
import com.codename1.backend.test.BackendTest;
import com.codename1.backend.test.MediaType;
import com.codename1.backend.test.MockMvc;
import org.junit.jupiter.api.Test;

import static com.codename1.backend.test.MockMvcRequestBuilders.get;
import static com.codename1.backend.test.MockMvcResultMatchers.content;
import static com.codename1.backend.test.MockMvcResultMatchers.jsonPath;
import static com.codename1.backend.test.MockMvcResultMatchers.status;

@BackendTest
class GreetingApiTest {
    @Autowired
    private MockMvc mvc;

    @Test
    void greetsByName() throws Exception {
        mvc.perform(get("/greet/{name}", "Ada"))
                .andExpect(status().isOk())
                .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
                .andExpect(jsonPath("$.greeting").value("Hello, Ada"));
    }

    @Test
    void unknownRoutesAreNotFound() throws Exception {
        mvc.perform(get("/nowhere")).andExpect(status().isNotFound());
    }
}

@BackendTest starts the application with the same beans and the same wiring as the server the build produces. @Autowired fields of the test class are filled from its beans, and MockMvc is one of them. perform runs a request through the server’s dispatch — the router, the sessions, the scoped beans and the error handling — without opening a socket. Each andExpect checks one thing about the response and fails the test with a message saying what it saw.

The request builders are static methods of MockMvcRequestBuilders:

MethodBuilds

get, post, put, patch, delete, head, options

A request with that method. A URI template’s {name} placeholders are filled, encoded, from the arguments that follow it.

request(HttpMethod, uri, …​)

A request with any method.

multipart(uri, …​)

A multipart/form-data POST. .file(…​) adds a file part and .param(…​) adds a form field.

Each builder takes .header, .param (a query parameter), .content (the body, as a string or bytes), .contentType, .accept, .characterEncoding and .cookie.

The matchers are static methods of MockMvcResultMatchers:

MatcherChecks

status()

The status: isOk(), isCreated(), isNotFound() and the other names, a class with is4xxClientError() and similar, or a number with is(int).

content()

The body with string, bytes or json (a JSON body holding every field of the expected one), and the content type with contentType or contentTypeCompatibleWith.

jsonPath(expression)

A value in a JSON body: value, exists, doesNotExist, isArray, isEmpty and the type checks. The expression supports $, .name, ['name'], [index] (negative counts from the end), [], . and a final .length().

header()

A response header: string, longValue, exists or doesNotExist.

cookie()

A cookie the response sets: value, exists or doesNotExist.

redirectedUrl(url)

The Location of a redirect.

andExpectAll checks several matchers and reports every one that failed rather than stopping at the first. andDo(print()) writes the request and response to standard output. andReturn() gives the result, for assertions no matcher covers:

String body = mvc.perform(get("/greet/{name}", "Ada"))
        .andReturn().getResponse().getContentAsString();

A server with a security layer needs its requests to come from somebody. @WithMockUser and the request post-processors user(), jwt(), apiKey(), httpBasic() and csrf() do that, and Section 41.21, “Testing” describes them.

38.3. Testing over a real port

MockMvc skips the socket, the HTTP parser and the response writer. It also skips the checks the parser makes on a request target, so a malformed one such as /users/%FF reaches the routes instead of getting a 400. To test through them, serve the application on a free port:

import com.codename1.backend.annotations.Autowired;
import com.codename1.backend.test.BackendTest;
import com.codename1.backend.test.LocalServerPort;
import com.codename1.backend.test.ResponseEntity;
import com.codename1.backend.test.TestRestTemplate;
import org.junit.jupiter.api.Test;

import java.util.Map;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

@BackendTest(webEnvironment = BackendTest.WebEnvironment.RANDOM_PORT)
class ServedGreetingTest {
    @Autowired
    private TestRestTemplate rest;

    @LocalServerPort
    private int port;

    @Test
    void answersOverARealSocket() throws Exception {
        assertTrue(port > 0);
        ResponseEntity<Map> answer = rest.getForEntity("/greet/{name}", Map.class, "Ada");
        assertEquals(200, answer.getStatusCodeValue());
        assertEquals("Hello, Ada", answer.getBody().get("greeting"));
    }
}

With RANDOM_PORT, the test injects TestRestTemplate, an HTTP client for the running server, and @LocalServerPort holds the port it chose. The client resolves paths against the server, so a test never builds a URL. It encodes a body as JSON and decodes an answer into a String, a byte[], a Map or a List. getForObject returns the body, and getForEntity returns a ResponseEntity with the status and headers too. postForEntity, put, delete and exchange cover the other methods, and withBasicAuth returns a client that signs every request in. A status of 4xx or 5xx is an answer, not an exception, so a test can assert on it.

The client is the backend’s own, so a compiled test run sends its requests from the native binary’s HTTP stack.

webEnvironmentThe application is

MOCK (the default)

Reached through MockMvc, in the test’s process.

RANDOM_PORT

Served on a free port of the loopback interface.

DEFINED_PORT

Served on the configured cn1.server.port.

NONE

Started for its beans only; the test calls them directly.

Every environment but DEFINED_PORT listens on a free loopback port, so test runs never collide with each other or with a server running on the machine.

38.4. Settings and profiles

A test runs with the module’s application.properties, then the profile’s file, then the settings the annotation names:

@BackendTest(properties = {"app.greeting=Hi", "cn1.session.timeout=5"})

The settings a test names win over everything, the environment included, unlike a deployed server, where the environment has the last word. A shell that exports PORT or DATABASE_URL therefore doesn’t move a test off its free port or its test database.

The profile is test unless profile names another, and test is a development profile: unless the test or the profile’s file names a database, the application gets an in-memory SQLite one, and the generated daos create their tables. A test therefore starts from an empty database with no setup.

Starting an application costs time, so test classes share one. Classes with the same test beans, settings, profile and web environment use the same running application, much as Spring caches a context. A class whose configuration differs stops it and starts its own. State that a test leaves in a bean or the database is visible to the next test that shares the application, so a test must not depend on the order tests run in.

38.5. Replacing a bean

A static nested class marked @TestConfiguration adds its @Bean methods to the test’s application. Marked @Primary, a test bean wins every injection of its type, which replaces the application’s bean without a mocking library:

@TestConfiguration
static class Fakes {
    @Bean
    @Primary
    public Greetings formalGreetings() {
        return new Greetings() {
            @Override
            public String greet(String name) {
                return "Good evening, " + name;
            }
        };
    }
}

@Test
void theControllerGetsTheTestBean() throws Exception {
    mvc.perform(get("/greet/{name}", "Ada"))
            .andExpect(jsonPath("$.greeting").value("Good evening, Ada"));
}

A top-level @TestConfiguration class is added by listing it in @BackendTest(classes = …​). A test bean is an ordinary singleton: it receives its own injections, and the test can @Autowired it. It can’t be request-scoped, session-scoped or lazy, and it can’t carry @Transactional, @Async or the other annotations the build weaves; the build says so when one does.

38.6. Mocking a bean with Mockito

With org.mockito:mockito-core on the test classpath, @MockitoBean replaces every bean of the field’s type with a Mockito mock and injects it:

@MockitoBean
private Greetings greetings;

@Test
void theControllerCallsTheMock() throws Exception {
    when(greetings.greet("Ada")).thenReturn("Hi, Ada");
    mvc.perform(get("/greet/{name}", "Ada"))
            .andExpect(jsonPath("$.greeting").value("Hi, Ada"));
    verify(greetings).greet("Ada");
}

The mock is reset after every test. A controller can’t be mocked, because it’s what the test is exercising. Mockito builds classes while it runs, which a native binary can’t do, so @MockitoBean tests run only on the JVM. A @Primary test bean works in both.

38.7. Testing one slice of the application

@BackendTest starts the whole application. A slice starts only the part a test is about, so the test starts faster and a failure points at that part.

@WebMvcTest wires the controllers it names, and the beans its includes lists, behind MockMvc. Nothing else is created: no other controller, repository, scheduled job or bean is constructed, so a bean whose constructor needs a database or a remote service can’t slow the test down or break it.

import com.codename1.backend.annotations.Autowired;
import com.codename1.backend.test.MockMvc;
import com.codename1.backend.test.WebMvcTest;
import org.junit.jupiter.api.Test;

import static com.codename1.backend.test.MockMvcRequestBuilders.get;
import static com.codename1.backend.test.MockMvcResultMatchers.jsonPath;
import static com.codename1.backend.test.MockMvcResultMatchers.status;

@WebMvcTest(value = GreetingApi.class, includes = Greetings.class)
class GreetingSliceTest {
    @Autowired
    private MockMvc mvc;

    @Test
    void greetsWithOnlyTheControllerWired() throws Exception {
        mvc.perform(get("/greet/{name}", "Ada"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.greeting").value("Hello, Ada"));
    }
}

A dependency the slice leaves out is a build error, not a failure when the test runs. The error names the bean and the field or parameter that needs it, and the three ways out: list it in includes, replace it with a @MockitoBean, or declare it in a @TestConfiguration. A class named as a controller that isn’t one is a build error too.

@DataJpaTest wires the entities, the generated repositories and the beans its includes lists, with no web layer (its environment is NONE). It runs against its own database, an in-memory SQLite one unless its database attribute names a file or a URL, and the test’s own settings can’t point it at a shared one by accident. Each test method runs in a transaction that rolls back when it returns, whether it passed or failed, so tests can’t see each other’s rows; rollback = false keeps what a test wrote. A test can inject a repository interface the application never implements and gets the generated one.

Both slices take properties, profile and classes as @BackendTest does, and both run compiled, as the next sections describe.

38.8. Mail in a test

A test’s application sends no mail unless the test names a cn1.mail.url. Every mail is kept in memory instead, and MailSender.sent() returns them, so a test can assert on the recipient, the subject and the rendered body. The flows that mail a link or a code, such as a password reset, are tested the same way: read the link out of the captured mail and follow it. Chapter 44, Backend email has an example.

38.9. Turning production features on

A test’s application starts without the management endpoints, the MCP endpoint and the OpenTelemetry exporters, whatever the module’s settings say, so a test that doesn’t exercise them doesn’t pay for them. features turns them on for one test class: MANAGEMENT, TELEMETRY, MCP, or AS_PACKAGED for the set the packaged server is built with.

The test library has two fixtures for such tests, and both run on the JVM and compiled:

  • ManagementContract is an interface of @Test default methods that checks the management contract: the probes need no token, every other endpoint answers 401 without the right one, the schema describes its metrics, and the Prometheus scrape is typed. A test class implements it and supplies a client and the token.

  • OtlpTestCollector is an OTLP receiver on a loopback port. Point cn1.otel.endpoint at its getEndpoint(), turn TELEMETRY on, and await the export requests the server sends to /v1/traces or /v1/metrics.

import com.codename1.backend.annotations.Autowired;
import com.codename1.backend.test.BackendTest;
import com.codename1.backend.test.ManagementContract;
import com.codename1.backend.test.TestRestTemplate;

@BackendTest(webEnvironment = BackendTest.WebEnvironment.RANDOM_PORT,
        features = BackendTest.Feature.MANAGEMENT,
        properties = "cn1.management.token=test-token")
class ManagedServerTest implements ManagementContract {
    @Autowired
    private TestRestTemplate rest;

    @Override
    public TestRestTemplate managementClient() {
        return rest;
    }

    @Override
    public String managementToken() {
        return "test-token";
    }
}

38.10. Running the tests compiled

The server ships as a native binary, and the tests can run that way too:

mvn -pl backend -Dcodename1.platform=backend test -Dcn1.backend.compiledTests=true

After Surefire runs the tests on the JVM, the backend-test goal compiles the same test classes with the application into one native binary, the way cn1:backend-package builds the server, then runs it. The test binary has the generated wiring, the woven methods and the natives of the shipped server, so a difference between the two runtimes fails a test rather than a deployment.

The binary has no JUnit and no reflection. The build finds the tests in the compiled classes and generates the calls JUnit would make: @BeforeAll, @BeforeEach, @Test, @AfterEach and @AfterAll, with @Disabled and assumptions honored. The tests compile against a subset of JUnit 5 that the test library provides for the purpose. It covers those annotations, @DisplayName (reports keep the method name, as Surefire’s do by default) and @Tag, Assumptions, and the Assertions methods: assertEquals, assertNotEquals, assertTrue, assertFalse, assertNull, assertNotNull, assertSame, assertNotSame, assertArrayEquals, assertIterableEquals, assertInstanceOf, assertThrows, assertThrowsExactly, assertDoesNotThrow, assertAll and fail.

The compiled run picks the same test classes as the JVM run: under Maven, the ones Surefire’s includes and excludes select (its defaults, unless the pom names others), or the ones -Dtest names, down to the methods a Class#method entry selects; under Gradle, every test class. Tag selection isn’t applied to it.

@BackendTest is inherited, so an abstract base class can carry it with the shared fields and tests. Each concrete subclass gets its own context, and tests declared as default methods of an interface the class implements run too.

The results go to target/surefire-reports as TEST-<class>-compiled.xml, beside the JVM run’s reports, and a failed test fails the build.

A compiled run has these limits:

  • Mockito. A test class whose code uses Mockito is left out of the binary, and a class with a @MockitoBean field is reported as skipped. Pass -Dcn1.backend.compiledTests.strict=true to make either one fail the build.

  • JUnit and Surefire subsets. The compiled run reads the common JUnit 5 annotations and Surefire selections, not every one. Repeating @Tag on a class or method stops the compiled run from compiling, so use one per element. A -Dtest regex selector with a method part, such as %regex[.Api.#one.*], selects nothing in the compiled run. The JVM run handles both. The compiled run reads the inline <includes> and <excludes> lists one pattern per entry: it ignores includesFile and excludesFile, and doesn’t split comma-separated or !-negated patterns inside one entry.

  • Nested classes. The compiled run doesn’t run the tests of a @Nested class. A @Nested class inside a @BackendTest class isn’t supported on either run; give it a top-level @BackendTest class of its own.

  • Java tests only. The binary is compiled from Java test sources. A module with Kotlin tests runs them on the JVM, and the compiled run reports them by name and stops rather than running without them. Gradle builds look for Kotlin tests in src/test/kotlin only.

  • Toolchain. The binary needs what cn1:backend-package needs: clang, and the OpenSSL, libcurl and nghttp2 headers. It builds on Linux and macOS. On Windows, which has no native backend, the goal reports that and does nothing.

  • Time. Building the binary takes about as long as packaging the server, so it suits CI better than an edit-and-run loop.

38.11. Differences from Spring Boot

  • Packages. The annotations and classes live in com.codename1.backend.test, and @Autowired is com.codename1.backend.annotations.Autowired.

  • @BackendTest instead of @SpringBootTest. Its options are the web environment, properties, profile, classes and features. @WebMvcTest and @DataJpaTest are the two slices; there are no others, such as @JsonTest or @RestClientTest.

  • Wiring at build time. The test’s application is generated by the build rather than assembled when the test starts. An injection that can’t be satisfied fails the build.

  • No management, MCP or tracing unless asked. The test’s application is built without the management endpoints, the MCP endpoint and the OpenTelemetry exporters, whatever the module’s application.properties asks for, unless the test’s features names them. Spring starts Actuator in every @SpringBootTest.

  • One application at a time. Spring can keep several contexts cached. Here a class with a different configuration stops the running application before it starts its own.

  • A listener in every environment. MOCK and NONE also start the application listening on a free loopback port, because its server hosts the threads its tasks run on.

  • The JSON path subset. jsonPath supports the expressions listed above, without filters or functions other than length().

38.11.1. Migrating Spring Boot tests

Most of a Spring Boot test carries over with its imports changed:

  • @SpringBootTest becomes @BackendTest, with the same webEnvironment, properties and classes. @ActiveProfiles("x") becomes profile = "x".

  • @WebMvcTest(controllers = X.class) stays @WebMvcTest(X.class). Spring’s slice scans for @ControllerAdvice, converters and filters and leaves services out; this one leaves out everything not named, so list the services the controller uses in includes or mock them with @MockitoBean. The build error says which.

  • @DataJpaTest stays @DataJpaTest. @AutoConfigureTestDatabase has no equivalent, because the slice always has its own database; name it with database. TestEntityManager has no equivalent either; use the repositories.

  • @MockBean and @MockitoBean become @MockitoBean, and @TestConfiguration classes carry over. Mockito tests run on the JVM only.

  • MockMvc, TestRestTemplate, @LocalServerPort and the JUnit 5 assertions keep their names and the common methods.

  • A test of /actuator/health becomes one of /manage/health/liveness and /manage/health/readiness with features = Feature.MANAGEMENT, and a test of /actuator/prometheus one of /manage/prometheus with the management token.

39. Backend data access and transactions

A server’s data lives in a database, and this chapter is about reaching it: the connection pool, which speaks to SQLite, PostgreSQL and MySQL with one dialect of SQL, the object mapping the build generates daos from, and the transactions that make several statements one unit of work. The last of those gets the most room, because declarative transactions are where a Spring developer’s intuitions are most likely to be almost right.

For generated CRUD interfaces, derived finders, paging, declared queries, and conditional aggregates over managed sessions, see Generated repositories.

39.1. Talking to a database

The server opens a connection pool from cn1.datasource.url — a SQLite path or a PostgreSQL or MySQL URL — and injects it as a DataSource into any bean that asks for one. It returns rows as the same Java types whichever engine answered:

// db is the pool the server opened from cn1.datasource.url and injected
List rows = db.query("SELECT id, body FROM note WHERE id > ?",
                     new Object[] { Integer.valueOf(10) });

There is no JDBC driver involved. SQLite is linked into the binary, and the PostgreSQL and MySQL clients speak their wire protocols directly, and a mariadb:// URL is served by the same client. MySQL 8.0 and MariaDB 10.4 and newer are supported: a string key needs a case-sensitive NO PAD collation, so "A" and "a" are two keys and "token " keeps its space, and the two server families spell that collation differently. Which one is used comes from the server rather than from the URL scheme, so a mysql:// URL pointed at MariaDB is still correct.

MariaDB 10.3 works too. It has the same collation, which MariaDB added in 10.2.2, but it reached its upstream end of life in 2023 and isn’t among the versions the tests run against, so 10.4 is the oldest release that’s verified.

39.1.1. Encrypted connections

TLS is set on the URL. sslmode=require and its synonym verify-full demand TLS whose certificate chains to a trusted root and names the host the URL connects to. sslmode=verify-ca with sslrootcert=<CA file> verifies the chain up to that CA and doesn’t check the host name, which is what a managed instance or a container with a generated certificate needs. sslmode=prefer uses TLS when the server offers it, and sslmode=disable is plaintext:

# PostgreSQL behind a private CA: the chain is verified, the host name is not
cn1.datasource.url=postgres://app:[email protected]:5432/app?sslmode=verify-ca&sslrootcert=/etc/ssl/db-ca.pem
# MySQL's own spellings work too: chain and host name both verified
cn1.datasource.url=mysql://app:[email protected]/app?ssl-mode=VERIFY_IDENTITY&ssl-ca=/etc/ssl/db-ca.pem

MySQL’s own spellings are accepted on any URL: ssl-mode=DISABLED, PREFERRED, REQUIRED, VERIFY_CA or VERIFY_IDENTITY, and ssl-ca for the CA file. An unknown mode is refused at start-up rather than read as prefer.

Unlike libpq and MySQL Connector/J, require verifies here. Those clients read it to mean encrypt but trust any certificate, which an on-path peer satisfies with a certificate of its own. There is no setting that encrypts without verifying.

39.1.2. Typed columns

PostgreSQL and MySQL send DECIMAL, NUMERIC, date and time values as text, and they come back as the String the server sent, so an exact amount keeps every digit. Database.columnTypes says which columns those are, so code that maps rows to objects can parse each value by its kind:

List rows = db.query("SELECT total, placed FROM orders", new Object[0]);
String[] types = Database.columnTypes(rows);
// types[0] is "decimal": the value is a String of digits, such as "19.90"
// types[1] is "date", "datetime" or "datetimetz", depending on the column

The kinds are decimal, date, datetime (no zone), datetimetz (PostgreSQL’s timestamp with time zone) and time. Every other column is null, because its value is already a Long, Double, String or byte[]. SQLite has no column types to report, so the call answers null there.

39.1.3. Portable statements

Statements are written once, in one portable form: ? for every parameter, and plain unquoted names. PostgreSQL binds $1 rather than ?, and that difference stops inside execute and query rather than at every call site. SQL already written for one engine keeps working, because a statement carrying no ? at all is passed through untouched — so hand-written $1 is left alone. A literal question mark that isn’t a parameter is written ??, which matters on PostgreSQL, whose jsonb operators are spelled ?, ?| and ?&.

A parameter count that doesn’t match the statement is refused before the statement is sent. The three engines answer a mismatch three different ways, and SQLite’s answer is to bind the missing parameters to NULL and commit the row.

The other thing the engines disagree about is the key an insert generated. insert asks whichever way this engine answers — last_insert_rowid() on SQLite, LAST_INSERT_ID() on MySQL, and INSERT …​ RETURNING on PostgreSQL, which has no last-insert-id concept at all:

long id = db.insert("INSERT INTO note (body) VALUES (?)",
                    new Object[] { "first" }, "id");

Several statements that have to be one go through inTransaction, which holds a single connection for the whole body and rolls back if it throws:

db.inTransaction(new DataSource.Work() {
    public Object run(Database connection) throws Exception {
        connection.execute("UPDATE account SET balance = balance - ? WHERE id = ?",
                           new Object[] { Integer.valueOf(100), Integer.valueOf(1) });
        connection.execute("UPDATE account SET balance = balance + ? WHERE id = ?",
                           new Object[] { Integer.valueOf(100), Integer.valueOf(2) });
        return null;
    }
});

Everything each engine spells differently is reachable through db.dialect(), which is what code that generates schema needs:

Dialect dialect = db.dialect();
String create = "CREATE TABLE IF NOT EXISTS " + dialect.quote("note") + " ("
        + dialect.quote("id") + " " + dialect.generatedKeyColumn(Dialect.BIGINT) + ", "
        + dialect.quote("body") + " " + dialect.columnType(Dialect.TEXT) + ")";

Quoting every identifier isn’t caution. PostgreSQL folds an unquoted name to lower case while SQLite and MySQL preserve it, so a column called createdAt becomes createdat on one engine of the three, and code that reads rows by name stops finding it there.

A Database — one connection rather than a pool — is still available through Database.open for code that wants exactly one, and every one of its operations is synchronized, so sharing one across handlers is safe and serialized. That’s the right shape for a single-file SQLite server and the wrong one for a database that’s a machine across a network: there the single connection isn’t a safety property, it’s the bottleneck. The pool is the default for that reason.

39.2. Storing objects

A class with @Entity on it gets a data access object written for it at build time. The annotations are the ones the SQLite ORM chapter documents, and they are the same annotations in the same package, because an entity is the one class both halves of an application own:

@Entity(table = "reminders")
public class Reminder {
    @Id public long id;

    @Column(nullable = false) public String title;

    public java.util.Date due;

    public boolean done;

    @DbTransient public String cachedLabel;   // never stored

    public Reminder() {
    }
}

What differs between the app’s copy and the server’s is what the build generates from it: a module compiled against the Codename One core gets a dao over the local SQLite database, and a module compiled against this runtime gets one whose statements are built for whichever engine the connection turns out to be. The class says what the data is; the module says where its rows live.

The names differ too. A table or column the entity doesn’t name is called after the class or field in the app’s database, and after the same name in snake case on the server, the way Spring Boot names it: RideEvent is stored in ride_event and fareCents in fare_cents. An underscore goes before an upper case letter that sits between two lower case letters or digits, so userID becomes userid rather than user_i_d. A name given with @Entity(table) or @Column(name) is used as written on both. Queries keep naming the Java fields; only SQL written by hand sees the column names.

Dao<Reminder> reminders = em.dao(Reminder.class);

Reminder reminder = new Reminder();
reminder.title = "renew the certificate";
reminder.due = new Date();
reminders.insert(reminder);          // reminder.id is now the generated key

Reminder stored = reminders.findById(Long.valueOf(reminder.id));
stored.done = true;
reminders.update(stored);

The entity manager comes from the entry point, which opens one when the build generated at least one entity. A controller asks for it by declaring a constructor that takes one, and the generated entry point calls that constructor:

@RestController
@RequestMapping("/reminders")
public class ReminderApi {
    private final Dao<Reminder> reminders;

    /** The entry point calls this one because it is the one declared. */
    public ReminderApi(EntityManager entities) {
        this.reminders = entities.dao(Reminder.class);
    }

    @GetMapping
    public List<Reminder> outstanding() throws IOException {
        return reminders.query().eq("done", Boolean.FALSE).orderBy("due", true).list();
    }
}

A controller is a bean, so its constructor can take the entity manager, the pool, or any service built on them, as Chapter 37, Backend beans and dependency injection describes. The generated entry point holds a new with the argument written into it, and a controller that needs a database nothing configured is refused at start-up rather than handed a null to fail on later.

The build writes the entry point, and the daos are registered there: this runtime has no reflection and the translator drops a class nothing references, so the generated code’s direct reference to every dao is what keeps them in the binary. Put start-up work in a bean’s @PostConstruct method.

Outside the server — in a unit test, say — an entity manager is a single call over a pool:

EntityManager em = EntityManager.open(pool);

Queries name JAVA FIELDS rather than columns, and the builder quotes the column each one maps to:

List<Reminder> overdue = em.dao(Reminder.class).query()
        .eq("done", Boolean.FALSE)
        .lt("due", new Date())
        .orderBy("due", true)
        .limit(20)
        .list();

A name that isn’t a field of the entity is refused at once, listing the ones that are, rather than reaching the server as a column it doesn’t have. eq, ne, gt, gte, lt, lte, like, in, isNull and isNotNull are joined with AND in the order they were added, and list, first, count and delete end the chain. A query the builder can’t express takes SQL instead, through dao.find(where, params), which is the point at which portability becomes yours to keep.

Transactions take the same shape as everywhere else: the entity manager the body is handed is pinned to one connection, so every dao reached through it runs inside the transaction. Called inside a @Transactional method, it joins that transaction instead of starting another.

em.transaction(new EntityManager.Work() {
    public Object run(EntityManager tx) throws Exception {
        Dao<Reminder> reminders = tx.dao(Reminder.class);
        Reminder first = reminders.findById(Long.valueOf(1));
        first.done = true;
        reminders.update(first);
        reminders.insert(follower(first));
        return null;
    }
});

Three things this doesn’t do, on purpose. A Dao maps one row to one object and nothing more: an entity with a relationship, such as @OneToMany, is refused by it, and belongs to a managed session instead — see Annotation ORM Section and Section 39.4.8, “The transaction’s session”. createTable creates a table that isn’t there and does nothing at all to one that is, so it’s a convenience for development and for tests rather than a migration tool; see Section 39.3, “Schema migrations” for that. And a boolean, a date and a char are stored as integers on every engine — 0 or 1, epoch milliseconds, and the UTF-16 code unit — because a native timestamp comes back as text whose format follows the server’s own time zone and would not round-trip the same way on three engines, and because a char that was never assigned holds NUL, which PostgreSQL refuses inside a text value. A field declared as a primitive gets a NOT NULL column, because a primitive has no null to read: a nullable column would load as 0, false or \0, which is indistinguishable from a row that holds those. Declare the field as its boxed type — Integer rather than int — when the column can be empty.

39.3. Schema migrations

A schema changes for as long as the application does, and every database the server has ever run against has to change with it: the production one, the staging one, the file on a colleague’s laptop. A migration is one such change, written once as a script and applied exactly once to each database, in order. The server keeps a table recording which ones a database has had, so starting it is all it takes to bring any database up to the schema the code expects.

The file naming, the commands and the history table are Flyway’s, so a schema that Flyway already manages carries straight over, and the scripts work with either.

39.3.1. Writing migrations

Scripts go in src/main/resources/db/migration:

src/main/resources/db/migration/
    V1__create_note.sql
    V2__add_note_created.sql
    R__note_summary_view.sql
    postgresql/V3__note_search_index.sql
    mysql/V3__note_search_index.sql
    sqlite/V3__note_search_index.sql

A file called V<version>__<description>.sql is a versioned migration. The version is digits separated by dots or underscores, so V2, V2_1 and V2026_05_21_1 are all valid, and they sort as numbers: 2.10 comes after 2.9. Two underscores separate it from the description, where a single underscore reads as a space.

-- V1__create_note.sql
CREATE TABLE note (
    id INTEGER PRIMARY KEY,
    body VARCHAR(2000) NOT NULL
);
CREATE INDEX note_body ON note (body);

A change to the schema is always a new file with a higher version. A script that has already run is never edited, because databases that ran the old text would no longer match the ones that ran the new text. The server records a checksum of every script it applies and refuses to start when an applied script has changed.

-- V2__add_note_created.sql
ALTER TABLE note ADD COLUMN created BIGINT;
UPDATE note SET created = 0 WHERE created IS NULL;

A file called R__<description>.sql is a repeatable migration. It runs after the versioned ones, and again whenever its text changes, which suits a view or a set of reference rows that you want to edit in place.

The build compiles the scripts into the server. A packaged server can’t read files from the classpath, so there’s nothing to deploy beside the binary and nothing that can go missing from it. The build also refuses what could only fail later: a file whose name doesn’t parse, two files with the same version, an empty script.

39.3.2. One schema, several engines

A script directly in db/migration runs on every engine, so it has to be SQL that SQLite, PostgreSQL and MySQL all accept. Where they differ, put one script per engine in the sqlite, postgresql and mysql directories instead, under the same file name. MariaDB reads the mysql directory. A version needs either the one common script or a script for each engine the server runs on, never both.

On MySQL and MariaDB, text key columns need a case-sensitive NO PAD collation. The server refuses to start when one uses the default, utf8mb4_0900_ai_ci, because that collation treats "A" and "a", or "token" and "token ", as the same key. The two server families name the collation differently, and executable comments let one script in the mysql directory serve both:

ALTER DATABASE CHARACTER SET utf8mb4
    COLLATE /*!80000 utf8mb4_0900_bin */ /*M!100400 utf8mb4_nopad_bin */;
ALTER TABLE account CONVERT TO CHARACTER SET utf8mb4
    COLLATE /*!80000 utf8mb4_0900_bin */ /*M!100400 utf8mb4_nopad_bin */;

MySQL runs the first comment of each pair and skips the second, which only MariaDB reads. MariaDB runs the second and skips the first. The first statement sets the default that tables created later inherit. Tables that already exist keep their collation, so convert each of them too. Give the script a new, higher version than any applied one. A database that has already applied later versions refuses a script that sorts before them. The same version then needs a script in the sqlite and postgresql directories too. Their text is already case-sensitive and NO PAD, so a SELECT 1; is all those scripts have to hold.

39.3.3. What happens at start-up

Before the server opens its entity manager or accepts a request, it applies every script the database hasn’t had. Each one runs in a transaction together with the row that records it, so a script that fails leaves no trace and the server doesn’t start.

MySQL and MariaDB are the exception, because they commit every schema change as it runs and can’t take it back. A script that fails there may have left part of itself behind, so the server records it as failed and refuses to migrate again until someone has looked. Remove what the script left, fix it, and call repair:

Migrations.of(pool).repair();
Migrations.of(pool).migrate();

Several server processes starting at once against one database take a lock in the database, so each migration still runs exactly once and the others wait for it.

A script must not open or end a transaction, since the server already runs it in one. The rare script that has to manage its own, such as a SQLite table rebuild that switches foreign keys off, says so in a file beside it with the same name plus .conf, containing executeInTransaction=false. On SQLite, nothing keeps two server processes that start together from both running such a script, because SQLite has no lock that lasts beyond a transaction. Apply it from one process: cn1:migrate before the servers start, or one server ahead of the rest.

39.3.4. Adopting an existing database

A database that already has tables and no history is refused, because applying V1 to a schema of unknown shape is how a migration runs against the wrong database. To adopt one, tell the server which version it’s already at:

cn1.flyway.baselineOnMigrate=true
cn1.flyway.baselineVersion=12

The server records a baseline at that version and applies only the scripts above it. Tables whose names start with cn1_ belong to the framework and don’t count as an existing schema.

39.3.5. Settings

The settings mirror Spring Boot’s spring.flyway properties.

KeyWhat it sets

cn1.flyway.enabled

Whether pending migrations run at start-up. True unless set.

cn1.flyway.table

The history table, flyway_schema_history unless set.

cn1.flyway.baselineOnMigrate, cn1.flyway.baselineVersion, cn1.flyway.baselineDescription

Whether to adopt a database that has tables and no history, at which version, and the description recorded for it. Off, and version 1, unless set.

cn1.flyway.validateOnMigrate

Whether applied scripts are checked against the ones in this build before migrating. True unless set.

cn1.flyway.outOfOrder

Whether a script older than the newest applied one is applied instead of refused. A branch merged late is the usual reason to want it.

cn1.flyway.target

The highest version to migrate to. Every version unless set.

cn1.flyway.ignoreFutureMigrations

Whether a database migrated by a newer build is tolerated. True unless set, because a rolling deployment runs the old build against the new schema for a while.

cn1.flyway.cleanDisabled

Whether dropping the whole schema through clean() is refused. True unless set.

cn1.flyway.installedBy

The name recorded against each migration; the database user unless set.

cn1.flyway.lockRetryCount

How many one-second attempts to wait for another process that’s migrating. 50 unless set.

39.3.6. Looking at the schema from the build

The Maven goals run against the database named by cn1.datasource.url, with the project’s scripts:

mvn cn1:migrate-info
mvn cn1:migrate
mvn cn1:migrate-validate
mvn cn1:migrate-repair
mvn cn1:migrate-baseline -Dcn1.flyway.baselineVersion=12

migrate-info lists every migration with its state and changes nothing. migrate-validate fails when the database isn’t exactly at this build’s scripts, which makes it a useful check before a deployment. A repeatable migration that changed since it last ran, or never ran, fails it too. Point any of them at another database on the command line:

mvn cn1:migrate -Dcn1.datasource.url=postgres://app:[email protected]/app

The same information is available to code:

for (MigrationInfo migration : Migrations.of(pool).info()) {
    System.out.println(migration.getVersion() + " " + migration.getDescription()
            + " " + migration.getState());
}

39.3.7. Migrations in Java

A change that SQL can’t express, such as recomputing a column, is a class instead of a script. It runs once, in version order with the scripts, inside the same transaction a script would get.

@Migration(version = "4", description = "normalize note bodies")
public class NormalizeNotes implements JavaMigration {
    @Override
    public void migrate(MigrationContext context) throws IOException {
        List<String[]> rows = context.query("SELECT id, body FROM note", null);
        for (String[] row : rows) {
            context.execute("UPDATE note SET body = ? WHERE id = ?",
                    new Object[] { row[1].trim(), Long.valueOf(row[0]) });
        }
    }
}

A Java migration has no checksum, so editing one after it has run goes unnoticed. Treat it like a script and leave it alone.

39.3.8. Migrations a library brings

A library that keeps tables of its own registers a migration set under its own name. The set gets its own history table, so its versions never collide with the application’s, and it runs before the application’s scripts so they can refer to its tables.

A library jar marked as a backend library ships its own db/migration scripts the same way; see Section 37.8, “Controllers and beans from a library”.

Migrations.register(MigrationSet.builder("audit")
        .sql("1", "create audit log",
             "CREATE TABLE cn1_audit_log (id BIGINT PRIMARY KEY, entry VARCHAR(2000))")
        .sql("2", "index audit log", "postgresql",
             "CREATE INDEX cn1_audit_entry ON cn1_audit_log USING hash (entry)")
        .sql("2", "index audit log", "mysql",
             "CREATE INDEX cn1_audit_entry ON cn1_audit_log (entry(191))")
        .sql("2", "index audit log", "sqlite",
             "CREATE INDEX cn1_audit_entry ON cn1_audit_log (entry)")
        .build());

39.3.9. What isn’t supported

Undo scripts aren’t supported: write a forward migration that reverses the change. Flyway’s placeholders, callbacks and schema management aren’t read, and neither is MySQL’s DELIMITER, which is a directive of the mysql command-line client and not SQL. Scripts are found when the project is built, so a directory of scripts added beside a deployed server isn’t picked up.

39.4. Transactions

A transaction makes several statements succeed or fail together. @Transactional declares one around a method, and the build writes the code that begins, commits and rolls back the transaction around the method’s body:

@Transactional(rollbackFor = IOException.class)
public void register(String email) throws IOException {
    db.execute("INSERT INTO signup (email) VALUES (?)", new Object[] {email});
    // Throws when the mail server refuses: the insert above is rolled back,
    // because both run in the one transaction this method began. A failed
    // statement would roll back on its own -- it is a DataAccessException --
    // but the mailer's IOException is checked, so it takes rollbackFor.
    mailer.send(email, "Welcome", "Thanks for signing up.");
}

Everything the method does through the server’s DataSource joins the transaction without being handed anything, and so does every method it calls on the same thread. On a class, @Transactional applies to each public method the class declares. As in Spring, a method it inherits from a superclass isn’t covered until the class overrides it, and the build warns about each one. The same holds for @Async on a class.

39.4.1. How a method joins a transaction

The transaction belongs to the thread that began it. When a thread inside one asks the pool for a connection — directly, through an entity manager’s daos, or through a DataSource method — it gets the transaction’s connection back instead of a pooled one. That’s why a service three calls deep takes part without a parameter for it, and why the programmatic forms, DataSource.inTransaction and EntityManager.transaction, run as part of an open transaction rather than starting a second one.

The connection is borrowed, and BEGIN sent, only when the method first touches the database. A @Transactional method that returns early, or that turns out to have nothing to write, never takes a connection at all. The same laziness settles which database a transaction is on: the first pool it touches. Statements through any other pool run outside it, each committing on its own.

A transaction doesn’t follow work to another thread. An @Async method, a task given to Tasks, or a scheduled job runs outside the caller’s transaction, and begins its own if it’s @Transactional itself.

39.4.2. Propagation

propagation says what a method does when it’s called with a transaction already open. The default, REQUIRED, is right for most methods: join the open transaction, or begin one if there is none.

Three timelines: REQUIRED sharing one connection, REQUIRES_NEW suspending the outer transaction and committing on a second connection, NESTED using a savepoint
Figure 248. What each propagation does when a transaction is already open
PropagationWith a transaction openWith none open

REQUIRED

Joins it.

Begins one.

REQUIRES_NEW

Suspends it and begins another, on a second connection.

Begins one.

NESTED

Sets a savepoint in it.

Begins one.

SUPPORTS

Joins it.

Runs without one.

MANDATORY

Joins it.

Throws TransactionException.IllegalState.

NOT_SUPPORTED

Suspends it and runs without one.

Runs without one.

NEVER

Throws TransactionException.IllegalState.

Runs without one.

REQUIRES_NEW suits work that must be kept whatever happens to the caller, an audit record being the usual case:

@Component
public class AuditLog {
    private final DataSource db;

    public AuditLog(DataSource db) {
        this.db = db;
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void record(String event) throws IOException {
        // Commits on its own connection, whatever the caller's transaction does.
        db.execute("INSERT INTO audit (event) VALUES (?)", new Object[] {event});
    }
}

It costs a second connection for as long as it runs, taken from the same pool while the first one is still held. See the pitfalls at the end of this chapter before using it on SQLite.

39.4.3. Rollback rules

The rules are Spring’s. An unchecked exception or an Error leaving the method rolls the transaction back, and a checked exception commits it — with the one addition that keeps the outcome Spring’s, described in the note below. rollbackFor adds exception types that roll back, noRollbackFor adds types that commit, and when several listed types match the thrown one the most specific wins. The decision is written into the method as a chain of instanceof tests, so nothing reads the annotation when the method runs:

@Component
public class Orders {
    private final DataSource db;
    private final AuditLog audit;

    public Orders(DataSource db, AuditLog audit) {
        this.db = db;
        this.audit = audit;
    }

    @Transactional(rollbackFor = PaymentDeclined.class, timeout = 10)
    public long place(String sku, int quantity) throws IOException, PaymentDeclined {
        long id = db.insert("INSERT INTO orders (sku, quantity) VALUES (?, ?)",
                new Object[] {sku, Integer.valueOf(quantity)}, "id");
        audit.record("order " + id + " attempted");  // kept even if this rolls back
        charge(id);                                  // may throw PaymentDeclined
        return id;
    }

In Spring, a statement that fails throws the unchecked DataAccessException, so it rolls the transaction back. The methods of DataSource, Database and the daos declare the checked IOException, and the failures they report — a statement the engine refused, a connection that couldn’t be opened, a query that returned more than one row where one was expected — are com.codename1.backend.DataAccessException, a subclass of it. The default rule rolls back for that type as well, so a failed statement undoes the transaction as it would in Spring. Any other IOException — a file that couldn’t be read, a mail server that refused a message — is checked and commits, as it would in Spring; list it in rollbackFor to make it roll back, as the Signups example does. noRollbackFor = DataAccessException.class restores plain commit-on-checked.

One kind of failure isn’t a fault in the statement or the data. When two transactions change the same rows, the database may end one of them: as the loser of a deadlock, after a lock wait that timed out, or because a row changed after the transaction first read it. PostgreSQL, MySQL and MariaDB each report that their own way, and every one arrives as ConcurrencyFailureException, a DataAccessException. The transaction rolls back like any other, and the code that called the @Transactional method can run it again or answer that someone else made the change first. A session reports a database failure as an unchecked PersistenceException, so ConcurrencyFailureException.isCauseOf(err) looks for it among the causes. Catch it outside the @Transactional method, not inside: the database has usually ended the whole transaction by then, so nothing in it can continue.

A method that joined a transaction can’t roll back what the method that began it did before it, so when it fails with an exception that rolls back, it marks the whole transaction rollback-only instead. The method that began the transaction then rolls back when it ends. If it ends normally — because it caught the exception — the rollback is reported by throwing TransactionException.UnexpectedRollback, so the caller doesn’t take a rolled-back transaction for a committed one.

Transactions.setRollbackOnly() undoes a transaction without an exception. Called in the method that began the transaction, it lets that method return normally, and the transaction rolls back without an error when the method ends. Called in a method that joined the transaction, it counts as that method failing: the transaction becomes rollback-only, and the method that began it throws TransactionException.UnexpectedRollback when it ends normally. Called in a NESTED method, it undoes only that method’s work: its savepoint is rolled back when it returns, and the surrounding transaction carries on.

Transactions.isActive() and Transactions.isRollbackOnly() answer the obvious questions about the calling thread.

39.4.4. Read-only transactions and timeouts

readOnly = true begins a transaction the engine is told only reads. PostgreSQL and MySQL then refuse any write inside it, which turns a read path that writes by mistake into an error. SQLite accepts the flag and enforces nothing.

timeout is in seconds, counted from the start of the method. It’s checked when the transaction first touches the database, where a transaction already past its limit fails with an IOException, and again at commit, where it’s rolled back and reported with TransactionException.TimedOut. It doesn’t interrupt a statement that’s running, so it bounds how long a transaction can take to commit rather than how long any one query may run.

39.4.5. Transaction isolation

@Transactional(isolation = Isolation.SERIALIZABLE) selects isolation for the physical transaction. Import com.codename1.backend.annotations.Isolation. DEFAULT preserves the database’s configured default. An explicit isolation request in a joined REQUIRED, SUPPORTS, MANDATORY, or NESTED call must match the outer transaction’s explicit level. Joining a DEFAULT transaction with an explicit level fails, even if that database happens to use the requested default. Choose the level on the outer method, or use REQUIRES_NEW for an independent one. Isolation on a scope that runs without a transaction is rejected.

EngineExplicit levels

SQLite

SERIALIZABLE. A connection configured with PRAGMA read_uncommitted is rejected for that request. Other explicit levels are unsupported.

PostgreSQL

READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE. READ_UNCOMMITTED is rejected instead of mapping it to READ_COMMITTED.

MySQL/MariaDB

READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE. Use transactional tables such as InnoDB.

Support is checked when the lazy transaction first borrows a connection, before application SQL executes. A failure to acquire a connection or start a transaction marks the scope rollback-only. PostgreSQL uses transaction-local BEGIN characteristics; MySQL uses a next-transaction setting. Neither changes the session default. SQLite’s supported level requires no setting change. Commit and rollback therefore leave pooled connections with their original defaults; connections with uncertain state are discarded. This also applies to read-only transactions.

These choices follow the engines' transaction controls: PostgreSQL, MySQL, and SQLite.

For programmatic work, Transactions.execute(Propagation.REQUIRED, false, -1, Isolation.SERIALIZABLE, work) provides the same thread-bound scope. Its Transactions.Work.run() body returns a value and may throw an exception; every body exception or Error rolls back. Transactions.execute(work) uses REQUIRED and default isolation. DataSource.inTransaction(Isolation, Work) also creates or joins this scope, and pool operations within its body join it.

For a connection-local transaction, Database.beginTransaction(boolean, Isolation) and Database.transaction(Isolation, Work) select isolation without creating a thread-bound scope. The existing DataSource.inTransaction(Work) retains its connection-local behavior when called outside a declarative transaction. Use Transactions.execute or the isolation overload when callbacks/resources are needed.

39.4.6. Completion hooks and transaction resources

Register a Transactions.Synchronization within a thread-bound transaction:

Transactions.registerSynchronization(new Transactions.Synchronization() {
    public void beforeCommit(boolean readOnly) {
        // Validate application state before the ORM flush and database commit.
    }
    public void afterCommit() {
        // Invalidate a cache or schedule an event only after a successful commit.
    }
    public void afterCompletion(Transactions.Outcome outcome) {
        // Dispose resources on COMMITTED, ROLLED_BACK, or UNKNOWN.
    }
});

Hooks run synchronously in registration order within each phase. beforeCommit runs before the session flush; it may use the transaction’s database connection. It receives the physical transaction’s read-only flag, including for read-only transactions. Read-only scopes still run all phases. Registration closes when completion starts, so a callback can’t register further hooks on that scope. A before-commit exception or Error aborts the remaining before hooks and rolls back. Rollback-only and timeout checks run again after before hooks.

afterCommit runs only after the database acknowledges commit. A failure in one hook doesn’t stop later after-commit hooks or completion hooks; the caller gets TransactionException reporting that the transaction committed but its callback failed. Don’t retry the whole transaction based on that exception alone. afterCompletion runs once per registration at the end of each physical scope, including one that never needed a connection. Its failures are logged, and later cleanup still runs. Exception-driven rollback preserves the body’s original exception. A commit failure or failed rollback reports UNKNOWN because database durability can’t be established; no after-commit hooks run in that case.

The session closes and the connection returns to the pool before after-commit and completion hooks. During those hooks Transactions.isActive() is false; database work must use REQUIRES_NEW or an explicitly suspended scope.

Transactions.bindResource(key, value) binds a non-null value under a non-null key. Duplicate bindings fail. getResource(key) returns the binding or null; unbindResource(key) removes it. Bindings remain available to all completion hooks and are cleared afterward, even if a hook fails. Values aren’t implicitly closed: use a completion hook for disposal.

REQUIRED participants share the physical scope’s hooks and bindings. REQUIRES_NEW suspends both and restores them when its independent scope ends, even after failure. NESTED shares the physical bindings: savepoint rollback does not undo arbitrary Java objects. Hooks registered inside a rolled-back nested scope skip their before/after-commit phases, but still receive the physical transaction’s final outcome in afterCompletion. Successful nested hooks wait for the outer commit; releasing a savepoint never triggers a commit hook.

39.4.7. Savepoints

NESTED runs a method inside the open transaction, behind a savepoint. A failure rolls back to the savepoint and nothing more, and the outer method can go on and commit. That suits a batch in which one bad item shouldn’t cost the rest:

@Component
public class Imports {
    private final DataSource db;

    public Imports(DataSource db) {
        this.db = db;
    }

    @Transactional
    public int importAll(List<String> lines) {
        int imported = 0;
        for (String line : lines) {
            try {
                importLine(line);           // a call through this: still transactional
                imported++;
            } catch (Exception bad) {
                // Only this line's rows were rolled back, to its savepoint.
            }
        }
        return imported;                    // the good lines commit together
    }

    @Transactional(propagation = Propagation.NESTED)
    void importLine(String line) throws IOException {
        String[] fields = line.split(",");
        db.execute("INSERT INTO contact (name) VALUES (?)", new Object[] {fields[0]});
        db.execute("INSERT INTO phone (number) VALUES (?)", new Object[] {fields[1]});
    }
}

The loop calls importLine through this, which in Spring would bypass the annotation entirely and run every line in the outer transaction without a savepoint. Here the annotation is part of the method, so the call gets its savepoint however it’s made.

The savepoints are named by the runtime and released when the method returns normally. All three engines support them.

39.4.8. The transaction’s session

A bean can inject com.codename1.orm.session.Session, the persistence session of the ORM, and use it inside a transaction:

@Component
public class ReminderService {
    private final Session session;      // the current transaction's session

    public ReminderService(Session session) {
        this.session = session;
    }

    @Transactional
    public long remind(String title) {
        Reminder reminder = new Reminder();
        reminder.title = title;
        reminder.due = new Date();
        session.persist(reminder);      // written by the time the transaction commits
        return reminder.id;
    }

    @Transactional(readOnly = true)
    public Reminder find(long id) {
        return session.find(Reminder.class, Long.valueOf(id));
    }
}

The injected object stands in for the session of whichever transaction is open on the calling thread. The session is opened on the transaction’s connection the first time it’s used, its pending changes are flushed into the transaction before it commits, and it’s closed when the transaction ends. A savepoint that rolls back also clears the session, since the rows it had loaded since the savepoint no longer exist. Used outside a transaction, it throws with a message saying to annotate the method, or to open a session with EntityManager.openSession().

A @Repository interface, described in the SQLite ORM chapter, is injected the same way, as Spring Data injects one: the generated implementation is built once, over this session, and handed to every bean that asks for the interface. Its methods therefore run in the calling @Transactional method’s transaction, and refuse outside one exactly as the session does.

39.4.9. Why a call through this works

Spring applies @Transactional with a proxy: a wrapper object stands between a caller and the bean, and the transaction happens in the wrapper. A call that doesn’t go through the wrapper — one from the bean to itself, to a private method, or on an object the application built with new — gets no transaction, and nothing warns about it.

Here the build rewrites the compiled method. Its body moves to a method of its own and the method keeps its name, now starting the transaction, calling that body, and committing, with the rollback decision written in. The transaction is therefore a property of the method, and every call gets it. The same rewriting gives @Async, @Timed and @Counted the same property.

A private method may take and return private nested classes of its bean; the method needs no change for that. Two things must stay nameable from the bean’s package, and the build reports each with the class and method concerned: the class that declares the annotated method can’t itself be private, local or anonymous, and an exception listed in rollbackFor or noRollbackFor can’t be a private class.

39.4.10. Pitfalls

  • Checked exceptions other than database failures commit. A failed statement rolls back, but an IOException from anything else — a file, a mail server, an outbound HTTP call — commits unless it’s listed in rollbackFor.

  • REQUIRES_NEW needs a second connection. The outer transaction keeps its connection while the inner one borrows another, so on a pool of one — the default for an in-memory SQLite database — the inner borrow waits for cn1.datasource.pool.borrowTimeoutMillis and fails.

  • SQLite has one writer. A transaction that has written holds the database’s write lock until it ends, so a REQUIRES_NEW method that writes while its caller holds the lock waits cn1.datasource.busyTimeoutMillis and fails. Reading works. On SQLite, record the audit row after the outer transaction, or in it.

  • Transactions don’t cross threads. Work handed to @Async or Tasks isn’t part of the caller’s transaction and can’t see its uncommitted rows.

  • A transaction holds a connection. From its first statement until it ends, the connection is out of the pool. An outbound HTTP call inside a transaction keeps it there for the length of the call, and enough of those at once starve the pool. Make the call before the transaction begins, or after it ends.

40. Backend sessions

HTTP is stateless: every request arrives on its own, and nothing in it says the client has been here before. A session is how a server remembers a client between requests. The server gives the client an unguessable id in a cookie, the client sends it back with every request, and the server finds the state it kept under that id. This chapter covers the session API, the cookie, where sessions are stored, and session-scoped beans.

The states of a session: no session, new, active and ended, with the change of id at sign-in and expiry after inactivity, above the two stores
Figure 249. A session from the first request to the last

40.1. Starting a session at sign-in

A handler reaches the session through the request:

@RestController
public class Login {
    @PostMapping("/login")
    public String login(HttpServer.Request request, @RequestParam("user") String user) {
        // ... check the credentials ...
        HttpSession session = request.getSession(true);
        session.changeSessionId();        // never keep an id from before the login
        session.setAttribute("user", user);
        return "ok";
    }
}

getSession(true) returns the client’s session, creating one if the request carried no valid cookie. Nothing is stored and no cookie is sent until something calls it, so a server that never uses sessions — an API authenticated with bearer tokens, say — pays nothing for them and sets no cookie. The server the build generates stores each session and sends its cookie when the request ends.

The call to changeSessionId() isn’t optional at sign-in. It gives the session a new id, keeps its attributes, and sends the client the new cookie. Without it a session id the client held before signing in stays valid after, and an attacker who planted that id in the victim’s browser beforehand — a session fixation attack — is signed in along with the victim.

A handler that checks credentials itself is one way to sign a user in. The security layer in Chapter 41, Backend security does it for you: its form login, its sign-in through another provider and its passkeys end in this same session, change its id, and protect it against CSRF.

40.2. Reading and ending a session

Most requests want the session only if there is one:

@GetMapping("/me")
public String me(HttpServer.Request request) {
    HttpSession session = request.getSession(false);   // never creates one
    Object user = session == null ? null : session.getAttribute("user");
    return user == null ? "nobody" : String.valueOf(user);
}

getSession(false) never creates a session, and answers null for a client without a valid one, so a read-only request doesn’t create a session as a side effect. invalidate() ends one, and the response clears the client’s cookie:

@PostMapping("/logout")
public String logout(HttpServer.Request request) {
    HttpSession session = request.getSession(false);
    if (session != null) {
        session.invalidate();          // the response clears the cookie
    }
    return "bye";
}

After invalidate(), the request no longer has that session: getSession(false) returns null, and getSession(true) starts a new one, whose cookie the response sends after clearing the old one.

HttpSession methodWhat it does

getAttribute(name), setAttribute(name, value), removeAttribute(name)

Read, set and remove the session’s state. Setting null removes the attribute.

getAttributeNames()

A copy of the attribute names.

changeSessionId()

A new id for the same session, with a new cookie. Call it at sign-in.

invalidate(), isValid()

End the session, and ask whether it has been ended. Reading or writing an attribute of an ended session throws IllegalStateException.

isNew()

Whether the current request created the session.

getMaxInactiveInterval(), setMaxInactiveInterval(seconds)

How long the session may go unused before it expires, for this session alone.

getCreationTime(), getLastAccessedTime()

When it was created and last used, in milliseconds since the epoch.

getId()

The id the cookie carries. It’s a credential, so never log it.

A session is saved after the handler returns, and only when the request changed it. A request that only reads its session writes nothing, apart from the last access time the database store keeps. That store updates it when it’s older than a minute, or a quarter of the session’s timeout when that’s shorter, and allows the same interval on top of the timeout before it calls a session expired, so a session in use is never expired early.

With the database store, two requests of one client load separate copies of the session. If one of them invalidates it, the other can’t write it back: a copy of a session whose row is gone is dropped rather than saved again, so a request still running with an old cookie can’t undo a sign-out.

The session id is 192 bits from a cryptographically secure random source, encoded for a cookie. The cookie is sent with Path=/ and HttpOnly, so scripts in a page can’t read it. SameSite=Lax keeps a browser from sending it with a form another site posts. On a TLS server it’s also Secure, so a browser never sends it over plain HTTP. It carries no Max-Age, so it lasts until the browser closes; how long the session lasts is the server’s decision.

KeyWhat it sets

cn1.session.cookie

The cookie’s name, CN1SESSION by default. It has to be a valid cookie name —  letters, digits and the punctuation HTTP allows in a token, such as -, _ and . — and anything else stops the server at start-up.

cn1.session.timeout

Seconds a session may go unused before it expires, 1800 by default. Zero means sessions never expire, and a negative value stops the server at start-up.

cn1.session.store

memory, the default, or db. See Section 40.4, “Where sessions are kept”.

cn1.session.same-site

Lax, Strict or None. None lets other sites send the cookie, and a browser accepts it only when it’s Secure, so the server refuses to start with None unless the cookie is.

cn1.session.secure

auto, the default, which marks the cookie Secure when the server terminates TLS; true for a server behind a proxy that terminates TLS for it; or false. Anything else stops the server at start-up.

40.4. Where sessions are kept

cn1.session.store=memory keeps sessions in the server’s own memory. It needs nothing, any object can be an attribute, and the object a request sets is the object the next one gets. It also means sessions end with the process, and that a second instance of the server doesn’t know about them, so behind a load balancer it needs the balancer to send each client to the same instance.

cn1.session.store=db keeps sessions in the server’s own database, in a table called cn1_http_session that the server creates on first use. Every instance of the server then sees every session, a restart loses nothing, and a deployment can add or replace instances at will. The price is in what an attribute can be: the attributes are stored as JSON, so a value must be a string, a number, a boolean, or a map or list of those. Anything else is written as JSON can write it and read back as whatever JSON reads, which isn’t the object that was stored.

Each row belongs to a namespace, and a server only reads the rows of its own. By default the namespace is empty, so every server that uses the database shares its sessions, as Spring Session’s JDBC store does. Browsers don’t keep cookies apart by port, so two different servers on one host that share a database would each accept the session cookie the browser sends to both, including a signed-in user’s. Give each project its own cn1.session.namespace to keep them apart; every instance of one project keeps the same one, so they still share sessions.

Either way, an expired session is removed at most once a minute, by the next request that asks for a session, and a request that presents an expired session’s cookie is treated as having no session at all.

40.5. Session-scoped beans

A bean marked @Scope("session") exists once per session, which suits state that belongs to a client and has behaviour of its own:

@Component
@Scope("session")
public class Cart {
    private final List<String> items = new ArrayList<String>();

    public synchronized int add(String sku) {
        items.add(sku);
        return items.size();
    }

    public synchronized List<String> items() {
        return new ArrayList<String>(items);
    }
}

A singleton that injects it receives a generated stand-in, and each call on the stand-in reaches the calling client’s own instance:

@RestController
public class CartApi {
    private final Cart cart;        // a stand-in: each call reaches the caller's own cart

    public CartApi(Cart cart) {
        this.cart = cart;
    }

    @PostMapping("/cart")
    public String add(@RequestParam("sku") String sku) {
        return String.valueOf(cart.add(sku));
    }

    @GetMapping("/cart")
    public List<String> list() {
        return cart.items();
    }
}

Using the stand-in starts a session if the client has none, as getSession(true) would. The instance is built on the session’s first use and kept by the server in memory for as long as the session lives. It’s never written to the session store, whichever store is configured, so with cn1.session.store=db each instance of the server builds its own copy for a client it serves. State that has to follow the client from one instance to another belongs in the session’s attributes instead.

The bean’s @PreDestroy method, or its destroyMethod for a @Bean method, runs when the session ends. That’s at the end of the request that invalidated it, when the periodic purge finds it expired, or when the server stops.

Two requests from the same client can run at once — two browser tabs, or an app that doesn’t wait for one answer before sending the next — and they reach the same instance. The methods of a session-scoped bean therefore need to be safe to call concurrently, which is why the Cart above synchronizes them.

A session-scoped bean can’t inject the request or the HttpSession: it outlives the request that built it, and with the database store each request loads its own copy of the session, so a copy held by the bean would go stale. The build refuses both. A method that needs the session reads the current one when it runs, with Backend.currentRequest().getSession(true).

40.6. Pitfalls

  • Skipping changeSessionId() at sign-in leaves the server open to session fixation. Call it whenever a session gains a privilege.

  • Storing objects the database store can’t write. A service, a stream or a domain object in an attribute works on the memory store and comes back as something else from the database store. Store ids and plain values, and load the rest per request.

  • Relying on memory sessions behind a load balancer without sticky routing makes a client appear signed out whenever a request lands on another instance.

  • Holding a lock across the whole session. Concurrent requests from one client share its attributes and its session-scoped beans, so a long synchronized method serializes that client’s requests. Keep critical sections short.

41. Backend security

The backend’s security layer decides who a request is from and whether that caller may have what it asked for. It has the shape of Spring Security: you declare a filter chain as a bean, describe it with HttpSecurity, and the names and defaults are the ones you already know. This chapter covers the chain, the ways of signing in, the tokens a server verifies and issues, the tables it keeps, and how to test it. The differences from Spring Security are collected in Section 41.24, “How this differs from Spring Security”.

The client side is covered in Chapter 95, Authentication and Identity: signing a Codename One app in against this server with OidcClient, storing its tokens, authorizing its requests, the device grant and passkeys.

41.1. The filter chain

A filter chain is an ordered list of filters that every request it guards passes through before it reaches a controller. One filter reads the session, another checks a password or a token, another applies the authorization rules. You don’t write the filters. You declare a SecurityFilterChain bean, and the HttpSecurity its method is handed builds the chain from what you ask for:

@Configuration
public class SecurityConfig {
    @Bean
    @Order(1)
    SecurityFilterChain api(HttpSecurity http) {
        http.securityMatcher("/api/**")
            .authorizeHttpRequests(auth -> auth
                    .requestMatchers("/api/orders/**").hasAuthority("SCOPE_orders:read")
                    .anyRequest().authenticated())
            .sessionManagement(session ->
                    session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()));
        return http.build();
    }

    @Bean
    SecurityFilterChain pages(HttpSecurity http) {
        http.authorizeHttpRequests(auth -> auth
                    .requestMatchers("/", "/css/**").permitAll()
                    .requestMatchers("/admin/**").hasRole("ADMIN")
                    .anyRequest().authenticated())
            .formLogin(Customizer.withDefaults());
        return http.build();
    }

This server has two chains. Requests under /api carry a bearer token and keep no session. Everything else belongs to a browser that signs in through a form.

A request is put to the chains in @Order, lowest first. Only the first chain whose securityMatcher matches the request sees it. A chain without a securityMatcher guards every request, so it has to come last, and a server whose catch-all chain isn’t last refuses to start. A bean without @Order comes after those that have one. A request that no chain matches isn’t guarded at all.

The server’s own endpoints, which are management, MCP and the telemetry relay, aren’t put to any chain. They keep their own tokens. A WebSocket handshake is a request like any other, and its chain can refuse it.

A chain is an ordinary singleton. The server takes its chains when it starts, so the build refuses one that’s @Lazy or scoped.

Out of the box a chain guards every request it matches, writes the security headers, keeps the signed-in user in the HTTP session, protects that session against CSRF, and gives a request nobody signed in for an anonymous authentication. It has no way of signing in and no authorization rules until you give it some.

41.1.1. A server without a chain has no security layer

Nothing here is switched on by a dependency. The build links the security layer only when it finds a SecurityFilterChain bean, so a server without one has no filters, no login page and no generated password. Its routes are open, exactly as they were before. That’s the opposite of Spring Boot, where the starter on the classpath locks every route. See Section 41.22, “A server links only the security it declares” for what else follows from this.

41.1.2. Who is calling

A handler receives the caller by declaring a parameter:

@RestController
public class AccountApi {
    @GetMapping("/api/whoami")
    public String whoAmI(Authentication who) {
        return who.getName() + " " + who.getAuthorities();
    }

    @GetMapping("/account/name")
    public String name(@AuthenticationPrincipal UserDetails user) {
        return user == null ? "nobody" : user.getUsername();
    }
}

An Authentication parameter is the authentication of the request. An @AuthenticationPrincipal parameter is its principal, and it’s null when the principal isn’t of the declared type. That includes a request nobody signed in for, whose principal is the text anonymousUser. A handler can also declare a CsrfToken parameter. The build refuses all three in a module with no chain, where they would always be null.

Anywhere else, ask the holder:

Authentication who = SecurityContextHolder.getContext().getAuthentication();
String name = who == null ? null : who.getName();

The context belongs to the thread that serves the request, for the length of that request. It doesn’t follow work handed to another thread: an @Async method or a @Scheduled job starts with none.

41.2. Users and passwords

A chain that takes a password needs to know its users. It finds them in the application’s UserDetailsService bean. For a demonstration or a test, keep them in memory:

@Bean
UserDetailsService users() {
    return new InMemoryUserDetailsManager(
            User.withUsername("ada").password("{noop}secret").roles("ADMIN").build(),
            User.withUsername("grace").password("{noop}secret").roles("USER").build());
}

For a real application, keep them in the database. JdbcUserDetailsManager uses the cn1_users and cn1_authorities tables described in Section 41.18, “Keeping it in the database”:

@Bean
UserDetailsService users(DataSource dataSource) {
    return new JdbcUserDetailsManager(dataSource);
}

@Bean
PasswordEncoder passwordEncoder() {
    return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}

Both stores compare names without regard to the case of A to Z, and keep the spelling a user was created with. A store keeps a password as it’s given, so encode it first:

users.createUser(User.withUsername(name)
        .password(encoder.encode(password))
        .roles("USER")
        .build());

You can also implement UserDetailsService yourself over your own tables, or hand a chain its users directly with http.userDetailsService(…​). A chain uses the application’s AuthenticationProvider beans or its AuthenticationManager bean when it has them.

A server with no user store at all can describe one user in its configuration, which suits a first run:

cn1.security.user.name=ada
cn1.security.user.password={noop}secret
cn1.security.user.roles=ADMIN,USER

41.2.1. Password encoders

A stored password starts with the scheme that made it, in braces:

{pbkdf2-sha256}pbkdf2$210000$<salt>$<hash>
{bcrypt}$2a$10$<22 characters of salt><31 characters of hash>
{noop}secret

PasswordEncoderFactories.createDelegatingPasswordEncoder() returns the encoder that reads that prefix, and a chain uses it when the application declares no PasswordEncoder bean. It encodes new passwords with {pbkdf2-sha256}, which is PBKDF2 over HMAC-SHA256 with a random salt and the round count written into the result.

It also verifies what a Spring application wrote: {bcrypt}, {pbkdf2} and {pbkdf2@SpringSecurity_v5_8}. A user table brought over from Spring therefore signs its users in as it is. A password in an older scheme is re-encoded in the current one the next time its owner signs in, as long as the user store implements UserDetailsPasswordService. Both stores above do.

A password whose prefix names a scheme the encoder doesn’t know is refused. A password with no prefix is refused too, unless you call setDefaultPasswordEncoderForMatches for a store that predates the prefixes.

{noop} stores a password as clear text. It verifies only on a development profile, which is dev, development, test or local. Anywhere else a {noop} password matches nothing, and the server says why once on standard error.

Checking a password takes tens of milliseconds of processor time that can’t be interrupted. Set cn1.security.password.maxConcurrent to bound how many are checked at once. A sign-in beyond the bound is answered 503 with Retry-After immediately, instead of taking a thread from the rest of the server. A value near the number of processors, less one or two, is reasonable. There’s no bound unless you set one.

An unknown username still costs one password comparison, so the time an answer takes doesn’t say whether the account exists.

41.3. Authorization rules

authorizeHttpRequests says which requests need what:

http.authorizeHttpRequests(auth -> auth
        .requestMatchers("/", "/css/**").permitAll()
        .requestMatchers("/admin/**").hasRole("ADMIN")
        .requestMatchers(AntPathRequestMatcher.antMatcher("DELETE", "/api/**"))
                .hasAuthority("orders:delete")
        .requestMatchers("/account/password").fullyAuthenticated()
        .anyRequest().authenticated());

The rules are asked in the order they’re written, and the first that matches decides. A request that no rule matches is denied, so most chains end with anyRequest().

A pattern is an Ant pattern. ? is one character, and * is any run of characters within one path segment. is any number of whole segments, including none, so /api/ matches /api, /api/ and /api/users/7. {name} binds one segment. Matching is case-sensitive, as routing is, and a trailing slash is part of the path. AntPathRequestMatcher.antMatcher adds an HTTP method, and RequestMatchers combines matchers with allOf, anyOf and not.

RuleWho passes

permitAll(), denyAll()

Everyone, and nobody.

authenticated()

Anyone who signed in.

fullyAuthenticated()

Someone who signed in during this session, and wasn’t only recognized by a remember-me cookie. Use it for what should ask for the password again.

rememberMe(), anonymous()

Someone recognized by a remember-me cookie, and a caller who didn’t sign in.

hasRole("ADMIN"), hasAnyRole(…​)

A caller with the authority ROLE_ADMIN, or with any one of the roles.

hasAuthority("orders:delete"), hasAnyAuthority(…​)

A caller with the authority exactly as it’s written.

access(manager)

Whoever your own AuthorizationManager grants.

A role is an authority with the ROLE_ prefix, and nothing more. roles("ADMIN") on a user grants ROLE_ADMIN, and hasRole("ADMIN") asks for it. A token’s scopes become authorities with the SCOPE_ prefix, which is why the first chain in this chapter asks for SCOPE_orders:read.

41.3.1. Paths the layer refuses

Before any rule of a chain sees a request, the chain checks that its path can’t mean one thing to a rule and another to the router. A path with a ; parameter, a backslash, an empty segment, a . or .. segment or a control character is answered 400 Bad Request. The same goes for a path with an encoded slash, backslash, percent, dot, semicolon, or NUL.

The check belongs to the chain that claims the request. A request no chain matches is answered exactly as a server with no chain answers it, however its path is written.

A request can’t leave its chain by being misspelled. A path of that kind is also compared as a proxy or a handler might read it, with its escapes resolved, its ; parameters dropped and its empty and dot segments removed. If a chain matches any of those readings, the request is refused. With a chain on /api/**, both //api/orders and /public/..%2Fapi/orders get a 400.

Matching is case-sensitive, as routing is. /API/orders is a different route from /api/orders, so it reaches nothing the chain guards.

41.3.2. The answers to a refused request

A request that must sign in is answered by the chain’s entry point. With form login that’s a redirect to the login page. With HTTP Basic it’s a 401 with a challenge, when Basic is the only way in or a script made the request. A bearer token or an API key gets a 401 with the reason in WWW-Authenticate. A chain with no way of signing in answers 403. A signed-in caller that’s denied gets a 403. Change either one with exceptionHandling:

http.exceptionHandling(handling -> handling
        .authenticationEntryPoint(new HttpStatusEntryPoint(401))
        .accessDeniedHandler((request, denied) ->
                HttpServer.Response.json(403, "{\"error\":\"forbidden\"}")));

41.4. Form login, HTTP Basic and sign-out

41.4.1. Form login

With nothing set, formLogin serves a plain login page at GET /login. It takes the form at POST /login with the fields username and password. It sends a signed-in user back to the page that asked for the sign-in, or to /, and a refused one to /login?error.

Name a loginPage to serve your own:

http.formLogin(form -> form
        .loginPage("/signin")
        .defaultSuccessUrl("/home")
        .permitAll())
    .logout(logout -> logout
        .logoutUrl("/signout")
        .logoutSuccessUrl("/")
        .permitAll());

The chain then serves no page and takes the form at that same path. Call permitAll() with a page of your own. Without it, a rule such as anyRequest().authenticated() redirects the login page to itself.

Only the address of the page that asked for the sign-in is remembered, and only for a GET that a browser made. A request with a body isn’t replayed after the user signs in.

41.4.2. HTTP Basic

httpBasic checks the Authorization: Basic header on every request that carries one. It keeps nothing and starts no session:

http.securityMatcher("/internal/**")
    .authorizeHttpRequests(auth -> auth.anyRequest().hasRole("SERVICE"))
    .sessionManagement(session ->
            session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
    .httpBasic(basic -> basic.realmName("Internal API"));

41.4.3. Sign-out

POST /logout ends the session, forgets who was signed in and redirects to /login?logout. logout changes the path, the destination and the cookies to delete, as the form example above shows. The request must be a POST while CSRF protection is on, so that a link on another site can’t sign a user out.

A chain has sign-out when it has a way of signing in to a session, which is formLogin, oauth2Login, rememberMe, mfa or webAuthn. Any other chain has no POST /logout until it calls http.logout(…​).

41.5. CSRF, sessions and headers

41.5.1. CSRF

A chain that keeps a session requires a CSRF token on every request that isn’t a GET, HEAD, TRACE or OPTIONS, and answers 403 without it. The token travels in the _csrf form field or the X-CSRF-TOKEN header. The generated login page carries it already. Your own pages get it from a CsrfToken handler parameter or from CsrfFilter.getToken(request).

The token a page is given is masked with random bytes, so every response carries a different string for the same token. The token is replaced when a user signs in.

A single-page application usually wants the token in a cookie that its script reads and sends back in the X-XSRF-TOKEN header:

http.csrf(csrf -> csrf
        .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
        .ignoringRequestMatchers("/webhooks/**"));

The cookie repository also stores the token in the HTTP session. It accepts the cookie only when it matches that session’s token. A sibling subdomain can’t gain access by injecting a known cookie or copying one from another session.

ignoringRequestMatchers leaves out an endpoint that another server calls and that authenticates some other way. A request authenticated by a bearer token or an API key is never asked for the token, because a browser doesn’t attach those to a request another site made it send. csrf.disable() turns the protection off for a chain whose clients aren’t browsers.

A STATELESS chain has no CSRF filter unless it calls http.csrf(…​). It keeps nothing a forged request could ride on. A stateless chain that takes HTTP Basic credentials from browsers should ask for it.

41.5.2. Sessions

sessionManagement says whether a chain may use the HTTP session that Chapter 40, Backend sessions describes:

http.sessionManagement(session -> session
        .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
        .sessionFixation(fixation -> fixation.newSession()));
PolicyWhat the chain does

IF_REQUIRED

Starts a session when it needs one: at sign-in, or to remember where an anonymous request was going. The default.

ALWAYS

Gives every request under the chain a session.

NEVER

Never starts a session, and uses one that’s already there.

STATELESS

Neither starts nor reads a session. Each request carries its own credentials.

At sign-in the chain changes the session id and keeps the attributes, which is the changeSessionId() call that the sessions chapter asks you to make by hand. sessionFixation chooses otherwise: newSession() starts an empty session, and none() leaves the session as it is.

41.5.3. Security headers

Every chain puts these on its responses:

X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Strict-Transport-Security: max-age=31536000 ; includeSubDomains

The cache headers are left out when the handler set any of the three itself. Strict-Transport-Security is sent only for a request that arrived over TLS. A header the handler set is never replaced. headers changes the defaults and adds a Content-Security-Policy, which isn’t sent unless you configure it:

http.headers(headers -> headers
        .frameOptions(frame -> frame.sameOrigin())
        .contentSecurityPolicy(csp -> csp.policyDirectives("default-src 'self'")));

41.6. Method security

Rules about paths guard the door. Method security guards the service behind it, whoever calls it:

@Component
@RolesAllowed("ADMIN")
public class Reports {
    public String revenue() {
        return "...";                 // the class's rule: ROLE_ADMIN
    }

    @PreAuthorize("hasRole('ADMIN') or #owner == authentication.name")
    public String activity(String owner) {
        return "...";
    }

    @PreAuthorize("@documentPermissions.canEdit(authentication, #id)")
    public void rename(@P("id") long documentId, String title) {
        // ...
    }

    @PermitAll
    public String status() {
        return "ok";
    }
}
AnnotationWho may call

@PreAuthorize("…​")

A caller for whom the expression holds.

@Secured("ROLE_ADMIN")

A caller with one of the authorities, each written in full.

@RolesAllowed("ADMIN")

A caller with one of the roles. ADMIN asks for ROLE_ADMIN.

@PermitAll, @DenyAll

Anyone, and nobody.

On a class, an annotation covers every public method. On a method, it replaces the one on the class. A caller who hasn’t signed in gets an InsufficientAuthenticationException, which a chain answers with its sign-in challenge. A signed-in caller who’s refused gets an AccessDeniedException, which is a 403.

41.6.1. The expression subset

The backend has no expression language at run time. The build compiles each @PreAuthorize expression into plain Java, so an expression costs what an if costs, and a mistake in one is a build error. An expression may contain:

  • hasRole('X'), hasAnyRole('X', 'Y'), hasAuthority('X') and hasAnyAuthority('X', 'Y').

  • isAuthenticated(), isAnonymous(), isFullyAuthenticated(), isRememberMe(), permitAll and denyAll.

  • and, or and not, also written &&, || and !, and parentheses.

  • authentication.name and principal.username, compared with == or != to a string literal or to a String parameter written #name.

  • A call on a bean, written @beanName.method(…​).

A parameter is named as the source names it when the class is compiled with debug information or -parameters. Otherwise name it with @P, as rename does above.

41.6.2. Calling a bean

Anything the subset can’t say goes in a bean method:

@Component
public class DocumentPermissions {
    public boolean canEdit(Authentication who, long documentId) {
        return who != null && ownerOf(documentId).equals(who.getName());
    }

The arguments of the call can be authentication, principal, a parameter written #name, or a string, whole number or boolean literal. The build checks the call against the bean’s class: the method has to exist, be public in a public class, and return boolean. The bean has to be a singleton. Its name is the class’s simple name with the first letter in lower case, unless @Component names it.

41.6.3. Where the build draws the line

What the build can’t compile, it refuses with the reason and the fix:

@PreAuthorize("hasPermission(#id, 'read')") on Reports.read: hasPermission(...) is not
supported: there is no PermissionEvaluator. Write the decision as a bean method and call
it: @permissions.canRead(authentication, #id).

@PreAuthorize("#order.owner.id == authentication.name") on Reports.open: #order.owner is a
property chain, which is not supported: the build compiles expressions and does not read
properties by name. Pass the parameter to a bean method and read it there:
@bean.method(authentication, #order).

Reports uses method security, and this module has no SecurityFilterChain bean: without a
chain nobody ever signs in, so every guarded method would refuse every caller. Declare
one -- a @Bean method that takes an HttpSecurity and returns http.build() -- or remove
the annotations.

The build also refuses returnObject, T(…​), @PostAuthorize, @PreFilter and @PostFilter, two security annotations on one element, and an annotation on an interface method or an abstract method.

Because the build rewrites the method itself instead of wrapping the object in a proxy, the check runs however the method is called: from another bean, from this, on a private method, or on an object made with new. In Spring a call through this skips the check. For an @Async method the check runs on the caller’s thread, before the work is handed off.

41.7. A JWT resource server

A resource server takes a bearer token on each request and verifies it as a JWT. oauth2ResourceServer turns it on, as the api chain at the top of this chapter does, and two properties tell it whose tokens to accept:

cn1.security.oauth2.resourceserver.jwt.issuer-uri=https://id.example.com
cn1.security.oauth2.resourceserver.jwt.audiences=orders-api

With an issuer-uri, the server reads the issuer’s metadata from its .well-known address when it starts, and refuses metadata that names another issuer. It fetches the keys from the metadata’s jwks_uri when the first token arrives, and requires every token’s iss to be that issuer.

Set audiences too. Without it, a token the issuer made for another application is accepted here.

A token with a bad signature, an expired token, or one from another issuer is answered 401 with the reason in WWW-Authenticate. A good token that doesn’t grant enough is answered 403 with insufficient_scope. No session is started for a request that carries a token.

A request with no token is answered 401 with a challenge and no error, because nothing was wrong with a token it didn’t send. When the rule that refused the request asks for a scope, the challenge names it, and so does the 403:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer scope="orders:read"

HTTP/1.1 403 Forbidden
WWW-Authenticate: Bearer error="insufficient_scope",
    error_description="The request requires higher privileges than provided by the access token.",
    error_uri="https://tools.ietf.org/html/rfc6750#section-3.1", scope="orders:read"

realmName on oauth2ResourceServer adds a realm to every challenge.

41.7.1. Keys

For an issuer that publishes no metadata, set jwk-set-uri instead, or public-key-location for a PEM file holding the one public key. For anything the properties can’t say, declare a JwtDecoder bean:

@Bean
JwtDecoder jwtDecoder() {
    DefaultJwtDecoder decoder = DefaultJwtDecoder
            .withJwkSetUri("https://id.example.com/oauth2/jwks")
            .jwsAlgorithms(SignatureAlgorithm.RS256, SignatureAlgorithm.ES256)
            .build();
    decoder.setJwtValidator(JwtValidators.createDefaultWithValidators(
            new JwtIssuerValidator("https://id.example.com"),
            new JwtAudienceValidator("orders-api")));
    return decoder;
}

A fetched key set is kept for five minutes. A token that names a key the set doesn’t have makes the server fetch early, which is how a rotated key is picked up, but never more than once in 30 seconds. When a fetch fails, the server goes on using the keys it has.

Use an https address for the keys. They’re what every token is trusted by.

41.7.2. What’s verified

The token’s alg header never chooses the algorithm. A decoder is built with the algorithms it accepts, RS256 unless told otherwise, and holds keys of a matching kind. A token whose header disagrees with either is refused, so alg: none fails, and so does a token signed with HMAC using an RSA public key as the secret. The supported algorithms are RS256, RS384, RS512, PS256, ES256 and ES384, and HS256, HS384 and HS512 for a shared secret.

The default validators check exp and nbf with a minute’s allowance for clocks that disagree. A decoder checks iss and aud only when it’s told what they should be. JwtClaimValidator tests any other claim.

41.7.3. From scopes to authorities

A token’s authorities come from its scope claim, or else scp, each with the SCOPE_ prefix. A token with "scope": "orders:read orders:write" is granted SCOPE_orders:read and SCOPE_orders:write. Its name is the sub claim. A converter changes either one:

JwtGrantedAuthoritiesConverter roles = new JwtGrantedAuthoritiesConverter();
roles.setAuthoritiesClaimName("roles");     // ["ADMIN", "USER"]
roles.setAuthorityPrefix("ROLE_");          // so hasRole("ADMIN") matches

JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
converter.setJwtGrantedAuthoritiesConverter(roles);
converter.setPrincipalClaimName("preferred_username");

http.oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt ->
        jwt.jwtAuthenticationConverter(converter)));

41.7.4. Several issuers

A server that trusts more than one issuer routes each token by its iss:

http.oauth2ResourceServer(oauth2 -> oauth2.authenticationManagerResolver(
        JwtIssuerAuthenticationManagerResolver.fromTrustedIssuers(
                "https://login.example.com", "https://partners.example.com")));

A token that names an issuer not on the list is refused without a request being made anywhere.

41.8. API keys

An API key is a long-lived secret that a program presents instead of signing in. apiKey turns it on:

http.securityMatcher("/api/**")
    .authorizeHttpRequests(auth -> auth
            .requestMatchers("/api/deploy/**").hasAuthority("SCOPE_deploy")
            .anyRequest().authenticated())
    .sessionManagement(session ->
            session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
    .apiKey(Customizer.withDefaults());

A client sends its key in either of two headers:

curl -H "X-API-Key: cn1_your-key" https://api.example.com/api/deploy/status
curl -H "Authorization: Bearer cn1_your-key" https://api.example.com/api/deploy/status

The chain looks keys up in the application’s ApiKeyRepository bean. That’s a JdbcApiKeyRepository over the cn1_api_key table, an InMemoryApiKeyRepository, or your own. Make a key with ApiKeyGenerator:

GeneratedApiKey made = new ApiKeyGenerator().generate("ci-bot", "deploy", "read");
repository.save(made.getApiKey());        // the hash, the owner and the scopes
String shownOnce = made.getPlaintext();   // cn1_...; it can't be read back later

A key is a prefix followed by 256 random bits. Only its SHA-256 is stored, so a copy of the table isn’t a set of working keys, and the key’s text exists only at the moment it’s made. The stored record keeps the prefix and the last four characters, which is enough to show someone which key a row is. revoke withdraws a key.

A request authenticated by a key is named after the key’s owner, and each scope is the authority SCOPE_ and its name. Those are the authorities a token with the same scopes gets, so one set of rules covers both. On a chain that also has oauth2ResourceServer, a bearer value that starts with the key prefix is an API key and any other is a token. The prefix is cn1_ unless you change it, and the chain’s prefix has to be the one the keys were generated with.

41.9. Rate limiting

rateLimit bounds how often the requests a matcher matches may be made under one key. A request over the limit is answered 429 with Retry-After:

http.rateLimit(AntPathRequestMatcher.antMatcher("POST", "/login"),
        RateLimitKeys.clientAddress(), new JdbcRateLimiter(dataSource, "login", 5, 60));
http.rateLimit("/api/**",
        RateLimitKeys.firstOf(RateLimitKeys.apiKeyId(), RateLimitKeys.principal()),
        new InMemoryRateLimiter(600, 60));

RateLimitKeys has the usual keys: the client’s address, the name of who is signed in, the session id and the API key’s id. firstOf takes the first one a request has. A limit whose key the request has from the start runs before anything else in the chain, so a refused request costs no password hash and no query. A limit keyed by who signed in runs once that’s known. A request with no key for a rule isn’t limited by it.

Give each rule its own limiter. Two rules that share one share its counts.

InMemoryRateLimiter is a token bucket, and its counts are per process. A server that runs as several instances has one count in each, so a client is allowed up to the limit times the number of instances. The counts are also gone when the process restarts. That’s usually fine for a limit that keeps load down. A limit that’s a security bound, such as attempts at a password, needs JdbcRateLimiter, which counts in the cn1_rate_limit table so that every process shares one limit. It costs a statement or two per request. When the database can’t be reached it refuses nobody.

41.9.1. The limits the layer keeps itself

Two parts of the layer count something without being asked. mfa counts the wrong codes entered for each user, and the authorization server counts the device codes each user tries at the verification page.

What’s countedKeysLimitWindow

Wrong one-time codes for a user, from everywhere

cn1.security.mfa.attempts, cn1.security.mfa.attemptsWindowSeconds

5

300 seconds

Wrong codes for a user from one client address

cn1.security.mfa.attemptsPerAddress

Half of attempts, rounded up: 3

The same window

Device codes tried

cn1.security.authorizationserver.device.verificationAttempts, cn1.security.authorizationserver.device.verificationWindowSeconds

10

300 seconds

With no RateLimiter bean, both are counted in the process. Declare one RateLimiter bean and they’re counted wherever that bean counts. A JdbcRateLimiter bean makes each a single count for every instance:

@Bean
RateLimiter limits(DataSource dataSource) {
    return new JdbcRateLimiter(dataSource, "api", 600, 60);
}

The bean’s own limit doesn’t apply to them. The layer asks the bean for a separate limiter for each purpose, with the numbers in the table, so a bean that throttles an API at 600 requests a minute doesn’t allow 600 guesses at a code.

attemptLimiter on mfa and deviceVerificationRateLimiter on the authorization server take a limiter directly, and it counts by its own limit. A bean of your own RateLimiter class that doesn’t implement derive does the same. Setting the keys as well is then refused when the server starts, because they’d decide nothing.

An application with several RateLimiter beans has to say which one these two use. The bean marked @Primary is used, as it would be for an injection. With no bean marked, or more than one, the server doesn’t start, and the error names the beans. It never falls back to counting in the process, because that would look the same as the shared count you asked for. There are two ways to choose: mark one bean @Primary, or inject the one you mean into the chain’s method, with @Qualifier and its name, and pass it to attemptLimiter or deviceVerificationRateLimiter. A rateLimit rule that names no limiter follows the same rule.

What the second factor’s limits promise

A wrong code is counted twice: once for the user, whatever address and session it came from, and once for the user at the client’s address. An IPv6 address counts by its first 64 bits, because one subscriber has all the addresses behind them. A right code isn’t counted. A sign-in that completes clears what was counted against that user, whether it was completed with a one-time code, a recovery code or a passkey that verified the user.

Recovery codes are counted apart from one-time codes, and only at the client’s address. That keeps a recovery code usable when the one-time codes aren’t.

With the default numbers, this is what somebody who has a user’s password and not their second factor can and can’t do:

  • They get five wrong one-time codes in five minutes in total. Signing in again with the password, starting another session or using another address doesn’t buy more. At most three of the five can come from one address.

  • They get three wrong recovery codes in five minutes from each address, with no total for the user. A recovery code is ten characters from an alphabet of 31 and a user has ten of them, so one guess is right about once in 80 trillion tries.

  • They can’t keep the user out from one address. When that address has used its three, it’s refused there and takes nothing more from the user’s five. Two are left for everyone else, and a right code needs one.

  • From two addresses or more they can use up all five. One-time codes are then refused for that user from everywhere until the window has passed. The user can still sign in with a recovery code from an address the attacker isn’t using, or with a passkey, which isn’t counted at all. Either one clears the count. The attacker can run the count up again, so this lasts until the password is changed. A run of 429 answers for one user is the sign that it needs changing.

  • At the user’s own address they can use up both counts, the one-time codes' and the recovery codes'. A passkey is then the way in.

The last point matters behind a proxy. A server that isn’t told to believe the forwarding headers sees the proxy’s address for every client, so every client is at the user’s own address. Set cn1.server.forwardHeaders; see Section 41.9.2, “Client addresses behind a proxy”.

Setting cn1.security.mfa.attemptsPerAddress to the same number as cn1.security.mfa.attempts gives up the third point: one address that knows the password can then keep the user out. A larger number is refused when the server starts.

The window depends on the limiter. The count kept in the process hands attempts back evenly, so after five at once it allows one more each minute. A JdbcRateLimiter counts five from the first of each window.

A limiter you pass to attemptLimiter counts both by its own single limit, so one address may use every attempt a user has. Pass two limiters, attemptLimiter(perUser, perAddress), to keep the promises in the list. Clearing a count uses RateLimiter.reset. A limiter of your own that doesn’t implement it clears nothing, and a right code then costs an attempt.

41.9.2. Client addresses behind a proxy

Behind a load balancer every connection comes from the load balancer, so RateLimitKeys.clientAddress() would be one key for every client. The real address arrives in X-Forwarded-For, and anybody can send that header. The server therefore believes it only when you say so, and only from a proxy it trusts:

cn1.server.forwardHeaders=true
cn1.server.trustedProxies=10.0.0.0/8,192.0.2.10

cn1.server.forwardHeaders is false unless set. cn1.server.trustedProxies is a list of addresses and CIDR ranges. An omitted or empty list trusts no peers, including loopback and private addresses. List only the deployment’s actual reverse proxies. X-Forwarded-For is read from the right, past every trusted proxy, so what a client wrote at the left end is never reached.

The same setting decides whether X-Forwarded-Proto is believed. That’s what request.isSecure() answers with behind a proxy that terminates TLS, and it decides whether Strict-Transport-Security is sent. request.getRemoteAddress() is the client’s address under these rules, and request.getPeerAddress() is always the other end of the connection.

41.10. Signing in through another provider

oauth2Login signs users in through Google, GitHub, Microsoft, Apple or any OAuth2 or OpenID Connect provider:

http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
    .oauth2Login(Customizer.withDefaults());

The providers come from the configuration:

cn1.security.oauth2.client.registration.google.client-id=your-google-client-id
cn1.security.oauth2.client.registration.google.client-secret=your-google-client-secret

cn1.security.oauth2.client.registration.github.client-id=your-github-client-id
cn1.security.oauth2.client.registration.github.client-secret=your-github-client-secret

cn1.security.oauth2.client.registration.acme.client-id=web
cn1.security.oauth2.client.registration.acme.client-secret=your-acme-client-secret
cn1.security.oauth2.client.registration.acme.scope=openid,profile,email
cn1.security.oauth2.client.registration.acme.provider=acme-id
cn1.security.oauth2.client.provider.acme-id.issuer-uri=https://id.example.com

A registration called google, github or microsoft needs only the client id and secret the provider issued. Any other provider is described by a cn1.security.oauth2.client.provider.<id> block. Give it an issuer-uri and the endpoints are read from the issuer’s metadata. Otherwise name them with authorization-uri, token-uri, user-info-uri, jwk-set-uri and user-name-attribute. Under a registration, the keys are client-id, client-secret, client-authentication-method, scope, redirect-uri, client-name, response-mode and provider.

A sign-in starts at GET /oauth2/authorization/{registrationId}, which sends the browser to the provider. It ends at /login/oauth2/code/{registrationId}, which is the redirect address to register with the provider. A chain with no login page of its own serves one at GET /login with a link for each provider. When there’s only one provider, a request that must sign in goes straight to it.

Every request to a provider carries a state, a PKCE challenge and, with OpenID Connect, a nonce. An ID token is accepted only when its signature verifies under the provider’s published keys and its iss, aud, exp and nonce are right. After the sign-in, the user goes back to the page that asked for it or to defaultSuccessUrl. Nothing the provider or the request says chooses the address.

The Microsoft registration uses the multi-tenant common endpoints, which accept accounts of any organization. An application that admits one tenant should also check the tid claim.

41.10.1. Sign in with Apple

Apple’s client secret isn’t a text Apple issues. It’s a token the server signs with the .p8 key from the developer account, so Sign in with Apple is declared in code, beside the registrations the configuration holds:

@Bean
ClientRegistrationRepository providers(Config config) throws IOException {
    List<ClientRegistration> all =
            new ArrayList<ClientRegistration>(ClientRegistrations.fromConfig(config));
    all.add(CommonOAuth2Provider.APPLE.getBuilder("apple")
            .clientId("com.example.web")          // the Services ID
            .clientSecretSupplier(AppleClientSecret.fromFile(
                    config.get("apple.team-id"), config.get("apple.key-id"),
                    config.get("apple.key-file")))
            .build());
    return new InMemoryClientRegistrationRepository(all);
}

A ClientRegistrationRepository bean replaces the registrations read from the configuration, which is why this one adds them itself.

A registration for Apple in the configuration is refused when the server starts, whether it names the apple provider or spells out Apple’s endpoints. A client-secret setting could never be right for it, and the error shows the bean to declare instead.

Apple answers with a form that the browser posts from Apple’s page, and a browser doesn’t send the session cookie with such a request. The pending sign-in is therefore kept in a signed cookie of its own. Its __Host- name, Path=/, Secure flag, and absence of a Domain attribute prevent a sibling subdomain from injecting a parent-domain cookie. The old unprefixed cookie isn’t accepted; a sign-in started with that cookie must be started again. Set cn1.security.oauth2.client.cookie-secret, at least 32 characters, to the same value on every instance. Without it each process makes its own key when it starts.

41.10.2. Account linking

By default, a user who signs in through a provider is that provider’s user and nothing more. LinkingOAuth2UserService ties them to one of the application’s own users, so the same person has the same account and the same roles however they sign in:

@Bean
FederatedIdentityRepository identities(DataSource dataSource) {
    return new JdbcFederatedIdentityRepository(dataSource);
}

@Bean
SecurityFilterChain web(HttpSecurity http, FederatedIdentityRepository identities,
                        UserDetailsService users) {
    LinkingOAuth2UserService linking = new LinkingOAuth2UserService(identities, users);
    linking.setCreateUsers(true);

    http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
        .oauth2Login(oauth2 -> oauth2
                .userService(linking)
                .oidcUserService(linking.oidc()));
    return http.build();
}

It decides who the provider’s user is in this order:

  1. An identity that’s already tied to a local user signs in as that user. An identity is the provider and the provider’s subject, never the email address, which can change hands.

  2. Otherwise the provider must say that it has verified the user’s email address. An address it doesn’t vouch for is refused with email_not_verified. GitHub’s user carries no such flag, so GitHub is asked for its list of addresses, and the one marked both primary and verified is used.

  3. A verified address that’s the name of a local user ties the identity to that user.

  4. A verified address that nobody here has makes a new local user when setCreateUsers(true) allows it and the user store is a UserDetailsManager. Otherwise the sign-in is refused with account_not_found.

A user made this way has a password nobody knows, and signs in through the provider until they set one. The identities are kept in a FederatedIdentityRepository, in memory or in the cn1_federated_identity table.

41.11. Calling other services

A server that calls another API as itself, not on behalf of a user, needs an access token of its own. AccessTokenProvider gets one, keeps it until a minute before it expires, and gets the next one. Two grants are supported:

  • Client credentials (RFC 6749), with the client secret in an HTTP Basic header, in the form, or replaced by a signed private_key_jwt assertion.

  • JWT bearer (RFC 7523), where the server signs an assertion with its own key and trades it for a token. A Google service account works this way.

A Google service account is read from the JSON file Google gives you. Its private_key_id becomes the assertion’s kid:

@Bean
AccessTokenProvider firestore() throws IOException {
    GoogleServiceAccountCredentials account =
            GoogleServiceAccountCredentials.fromFile("/run/secrets/service-account.json");
    return new AccessTokenProvider(
            account.grant("https://www.googleapis.com/auth/datastore"));
}

Any other provider’s client credentials grant:

@Bean
AccessTokenProvider billing(Config config) throws IOException {
    return new AccessTokenProvider(ClientCredentialsGrant
            .builder("https://auth.example.com/oauth/token", "orders-service")
            .clientSecret(config.get("billing.client-secret"))
            .scopes("invoices:write")
            .build());
}

Or the whole definition can come from configuration, under cn1.security.oauth2.client.credentials.NAME. (see Section 41.23, “Configuration keys”):

@Bean
AccessTokenProvider payments(Config config) throws IOException {
    // Reads cn1.security.oauth2.client.credentials.payments.*
    return AccessTokenProviders.fromConfig(config, "payments");
}

Each call then asks the provider for the header:

static String authorization(AccessTokenProvider tokens) {
    // Cached until a minute before it expires; one refresh for every caller.
    return tokens.getToken().toAuthorizationHeader();
}

What the provider promises:

  • One refresh at a time. Callers that arrive while a refresh is running get the current token if it’s still valid, and otherwise wait for that refresh instead of starting their own.

  • Never an expired token. If a refresh fails after the token expired, getToken() throws TokenAcquisitionException.

  • A cooldown, not retries in place. A failure the endpoint may recover from (a 5xx, a 429, an unreachable host) puts the provider in a cooldown that doubles with each failure, up to a minute, with jitter. Calls during it fail at once rather than holding a request thread. A refused grant (invalid_client, invalid_grant) is never retried, and the exception says so.

  • No secrets in errors. An exception names the endpoint, the HTTP status and the OAuth error code. It never includes the client secret, the assertion, the token or the response body.

Call invalidate() when the other service rejects a token before its expiry, for example after the provider revoked it.

41.12. The authorization server

authorizationServer makes the server an OAuth2 authorization server and OpenID Connect provider: the one that signs users in for clients and issues them tokens. A Codename One app signs in against it with a system browser and PKCE, and then calls your API with the access token.

@Bean
SecurityFilterChain web(HttpSecurity http) {
    http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
        .formLogin(Customizer.withDefaults())
        .authorizationServer(Customizer.withDefaults());
    return http.build();
}

How a user signs in is whatever else the chain declares: a form, another provider, a second factor, a passkey. A browser that arrives signed out is sent to sign in and comes back to the request it made. A client that isn’t a browser is answered 401 with login_required.

EndpointWhat it does

GET /oauth2/authorize

The authorization endpoint, for the signed-in user.

POST /oauth2/token

The token endpoint.

GET /oauth2/jwks

The public halves of the signing keys.

POST /oauth2/revoke

Revokes a token.

POST /oauth2/device_authorization

Starts a device grant.

/oauth2/device_verification

The page where the signed-in user types the device’s code.

GET /userinfo

The user’s claims, for an access token granted openid.

GET /.well-known/openid-configuration, GET /.well-known/oauth-authorization-server

The metadata a client discovers the endpoints from.

The server needs to know its issuer, which is the address clients reach it at, with no trailing slash:

cn1.security.authorizationserver.issuer=https://id.example.com
cn1.security.authorizationserver.jwk.keys=/etc/acme/signing-new.pem,/etc/acme/signing-old.pem

The issuer is the iss of every token and the base of every address in the metadata. Outside a development profile the server doesn’t start without it. On a development profile it’s taken from the request. settings sets the issuer in code and moves the endpoints, and tokenCustomizer changes the claims of a token before it’s signed:

http.authorizationServer(server -> server
        .settings(AuthorizationServerSettings.builder()
                .issuer("https://id.example.com")
                .build())
        .tokenCustomizer(context -> {
            if (OAuth2TokenContext.ACCESS_TOKEN.equals(context.getTokenType())) {
                context.getClaims().claim("tenant", "acme");
            }
        }));

41.12.1. Registered clients

The clients are the application’s RegisteredClientRepository bean, and the server doesn’t start without one:

@Bean
RegisteredClientRepository clients(PasswordEncoder encoder, Config config)
        throws IOException {
    RegisteredClient app = RegisteredClient.withId("mobile")
            .clientId("acme-app")
            .clientAuthenticationMethod(ClientAuthenticationMethod.NONE)   // public: PKCE
            .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
            .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
            .authorizationGrantType(AuthorizationGrantType.DEVICE_CODE)
            .redirectUri("com.acme.app:/oauth2redirect")
            .scope("openid").scope("profile").scope("orders:read")
            .tokenSettings(TokenSettings.builder()
                    .accessTokenTimeToLive(300)
                    .refreshTokenTimeToLive(30L * 24 * 3600)
                    .build())
            .build();
    RegisteredClient reports = RegisteredClient.withId("reports")
            .clientId("nightly-reports")
            .clientSecret(encoder.encode(config.get("reports.client-secret")))
            .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
            .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
            .scope("orders:read")
            .build();
    return new InMemoryRegisteredClientRepository(app, reports);
}

The first client is public. A mobile app can’t keep a secret, so it authenticates with nothing and proves with PKCE that the code it redeems is the one it asked for. PKCE is required of a public client, and only S256 is accepted.

The second client is confidential. It has a secret, which is stored as a PasswordEncoder wrote it and compared through the application’s PasswordEncoder bean, or the one given to clientSecretEncoder(…​). With neither, a server whose clients are declared in memory doesn’t start if one of them has a secret, and the error names the client. A server that keeps its clients in a table can’t know them all when it starts. It warns once at start-up, and answers a client that presents a secret with invalid_client.

A redirect address is matched whole, character for character. There are no wildcards. The one exception is an http address on 127.0.0.1 or [::1], which may be asked for with any port, because a desktop application can’t know which port it will get. A request whose client or redirect address is wrong is answered 400 and never a redirect.

A client is never granted a scope it wasn’t registered with. There’s no consent page: registering a client with a scope is the consent.

JdbcRegisteredClientRepository keeps the clients in the cn1_oauth2_registered_client table instead.

41.12.2. Grants

  • Authorization code. A code works once, for five minutes. Presenting it again later revokes what its use issued.

  • Refresh token. Opaque, stored as a hash, and issued to public clients too.

  • Client credentials. For a client with a secret, acting as itself:

    curl -u nightly-reports:your-client-secret \
         -d grant_type=client_credentials -d scope=orders:read \
         https://id.example.com/oauth2/token
  • Device code. For a device with no browser or keyboard, described below.

41.12.3. Refresh tokens

A refresh token is replaced every time it’s used. Using one that was already replaced means two parties hold it, so the server revokes the whole grant. That rotation is what protects a public client, which has no secret to present with the token. A client that refreshes twice at the same moment is allowed ten seconds in which the second request is refused and nothing is revoked.

TokenSettings sets the lifetimes for each client. Unless set, an authorization code, an access token and a device code last 5 minutes, an ID token 30 minutes, and a refresh token 60 minutes from its last use. reuseRefreshTokens(true) turns rotation off.

Token issuance and grant revocation are coordinated by the store. Once a grant is removed, a refresh request can’t recreate it. Custom stores must implement OAuth2AuthorizationService.issueTokens: check the active grant, record or extend the refresh token, and extend the grant in one operation that’s atomic with remove. The default implementation refuses issuance.

Client-credentials access tokens also have independent stored grants. Their owner can remove a grant through /oauth2/revoke; revoking one token doesn’t revoke tokens issued by other client-credentials requests. They never include refresh tokens, even when the client also supports the refresh grant.

A resource server that must reject revoked JWTs immediately needs access to the same authorization store. Add OAuth2AuthorizationValidator(store, issuer) to its decoder’s JwtValidators.createDefaultWithValidators(…​), alongside its audience validator. This checks the grant on each request after signature verification. A resource server that verifies JWTs offline continues accepting them until expiry; fetching public keys alone doesn’t convey revocation state.

Device polling uses OAuth2AuthorizationService.pollToken to check the last accepted poll and claim the next interval atomically. Custom stores must implement this operation before enabling the device grant; concurrent polls must not each claim the same interval.

The grants are kept by the application’s OAuth2AuthorizationService bean:

@Bean
OAuth2AuthorizationService authorizations(DataSource dataSource) {
    return new JdbcOAuth2AuthorizationService(dataSource);
}

Without one, the grants are kept in the process, and a line at start-up says so. Refresh tokens then don’t survive a restart and aren’t shared between instances.

41.12.4. Keys and rotation

Tokens are signed with the keys in cn1.security.authorizationserver.jwk.keys, a list of PEM files that each hold an RSA or a P-256 private key. Make one with:

openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out signing.pem

The first key signs every new token, with RS256 for an RSA key and ES256 for a P-256 key. Every key is published at /oauth2/jwks. To rotate, put the new key first and keep the old one in the list for as long as its tokens live. A resource server picks the new key up on its own, as Section 41.7, “A JWT resource server” describes.

A key file protected by a passphrase is refused. On a development profile with no key set, the server makes a key when it starts and warns you, and every restart then invalidates every token. Anywhere else, a missing key stops the server from starting.

An application that signs tokens of its own declares the keys and an encoder as beans, and the authorization server uses the same ones:

@Bean
JwkSource signingKeys(Config config) throws IOException {
    return AuthorizationServerKeys.load(config);
}

@Bean
JwtEncoder jwtEncoder(JwkSource keys) {
    return new DefaultJwtEncoder(keys);
}

41.12.5. The device grant

A television or a command-line tool can’t show a login page. It asks the server for a code, and then polls the token endpoint while the user approves it somewhere else:

curl -d client_id=acme-app -d "scope=openid orders:read" \
     https://id.example.com/oauth2/device_authorization

curl -d grant_type=urn:ietf:params:oauth:grant-type:device_code \
     -d client_id=acme-app -d device_code=the-device-code \
     https://id.example.com/oauth2/token

The first answer carries a device_code, a user_code of eight letters, a verification_uri and the interval to poll at. The user opens the verification page on a phone or a computer, signs in, types the code, and is asked by name whether to let that client in. Until they answer, the device’s polling is answered authorization_pending, slow_down, access_denied or expired_token.

The verification endpoint also answers in JSON, for an application that signed the user in itself and wants its own approval screen. A request gets the JSON form when its Accept header names application/json and not text/html, or when its body is application/json:

curl -b cookies.txt -H "Accept: application/json" \
     https://id.example.com/oauth2/device_verification

curl -b cookies.txt -H "Content-Type: application/json" -H "X-CSRF-TOKEN: the-token" \
     -d '{"user_code":"BCDF-GHJK"}' \
     https://id.example.com/oauth2/device_verification

curl -b cookies.txt -H "Content-Type: application/json" -H "X-CSRF-TOKEN: the-token" \
     -d '{"user_code":"BCDF-GHJK","ticket":"the-ticket","decision":"approve"}' \
     https://id.example.com/oauth2/device_verification

The first request answers with the CSRF token to send back, when the chain has CSRF protection. The second looks the code up and answers with client_id, client_name, scope, principal and a ticket. The third carries that ticket with "decision": "approve" or "deny", and is answered {"status":"approved"} or {"status":"denied"}.

Nothing is relaxed for the JSON form. It needs a session, as the page does: the ticket is kept in the session between the lookup and the answer, so a client that doesn’t send the session cookie back can’t approve a device. The user has to be signed in, and a request that isn’t is answered 401 with login_required instead of a redirect. The chain’s CSRF protection covers both posts. An answer counts only with the ticket from the lookup in the same session, and a ticket works once. A code that isn’t valid is invalid_grant, an answer without its ticket is invalid_request, and too many tries is 429 with slow_down.

One user may try ten codes in five minutes at the verification page. Change the numbers with cn1.security.authorizationserver.device.verificationAttempts and cn1.security.authorizationserver.device.verificationWindowSeconds. See Section 41.9.1, “The limits the layer keeps itself” for where the tries are counted.

41.12.6. What a resource server sees

An access token is a JWT of type at+jwt. Its payload looks like this:

{
  "iss": "https://id.example.com",
  "sub": "ada",
  "aud": "https://api.example.com",
  "client_id": "acme-app",
  "scope": "openid profile orders:read",
  "iat": 1767225600,
  "nbf": 1767225600,
  "exp": 1767225900,
  "jti": "..."
}

sub is the user’s name, or the client’s id for the client credentials grant. client_id is the client the token was issued to. scope becomes the SCOPE_ authorities that Section 41.7, “A JWT resource server” describes.

aud is the resource server the token is for, and it’s the value that resource server lists in its audiences. A client names the resource server with the resource parameter of its request, at the authorization endpoint, the device authorization endpoint, or the token endpoint. A request can carry the parameter more than once, and aud is then a list. At the token endpoint the parameter can only narrow what the grant was made for.

A request that names no resource gets the default audience. That’s the issuer, unless defaultAudience on the settings or cn1.security.authorizationserver.audience names another:

http.authorizationServer(as -> as.settings(AuthorizationServerSettings.builder()
        .issuer("https://id.example.com")
        .defaultAudience("https://api.example.com")
        .build()));

A client registered with resource(…​) can ask for those resources and no others. Anything else is answered invalid_target. A client registered with none can name any resource, so give a client a list when it shouldn’t choose.

/userinfo answers a token that’s for this server: one with the default audience, or one whose request named the address of /userinfo as a resource. A token made only for other resource servers gets a 401 there, so a service that’s handed such a token can’t use it to read the user’s profile. A client that wants one token for a resource server and for /userinfo names both.

An ID token is for the client, so its aud is the client’s id.

It also carries nonce, auth_time, azp and at_hash. Without a userInfoMapper, the profile scope yields preferred_username and the email scope yields nothing, because the server doesn’t know that a username is an address.

Authorizing a client or approving a device requires a sign-in stored in the current HTTP session. API keys, bearer tokens, HTTP Basic credentials and authentication restored from a remembered sign-in don’t satisfy this check. Sign in through the chain’s form, OAuth2 login or passkey flow first.

The authorization endpoint returns login_required for prompt=login, max_age=0, or a session whose last credential check is older than max_age. It also refuses a bounded-age request when the session has no recorded sign-in time. The client must arrange a fresh sign-in before retrying. The server issues no code when fresh authentication is required. A completed sign-in updates auth_time, including a sign-in completed with a second factor.

An access token is verified by its signature alone. Revoking a grant stops its refresh token and its answers at /userinfo, but an access token that’s already issued stays good until it expires. Keep access tokens short.

41.13. A second factor

mfa asks a user who has enrolled an authenticator app for a one-time code after their password:

@Bean
TotpService totp(DataSource dataSource, Config config) {
    return new TotpService(JdbcTotpRepository.fromConfig(dataSource, config), "Acme");
}

@Bean
RecoveryCodeService recoveryCodes(DataSource dataSource) {
    return new RecoveryCodeService(new JdbcRecoveryCodeRepository(dataSource));
}

@Bean
SecurityFilterChain web(HttpSecurity http) {
    http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
        .formLogin(Customizer.withDefaults())
        .mfa(Customizer.withDefaults());
    return http.build();
}

The password of an enrolled user no longer signs them in. It’s accepted, the request stays anonymous, and the user is sent to /login/mfa, which asks for the code. Posting a right one there signs them in. A user who hasn’t enrolled signs in as before. The chain serves a plain page at GET /login/mfa unless secondFactorPage names your own. The user has five minutes to enter the code. Five wrong codes are allowed for the user in five minutes, and three of them from one address. See Section 41.9.1.1, “What the second factor’s limits promise” for what that does and doesn’t stop, and Section 41.9.1, “The limits the layer keeps itself” to change the numbers or to count across instances.

41.13.1. What counts as a sign-in

A declared second factor holds for every way a user of that chain can present a first one. None of it affects a user who hasn’t enrolled.

MechanismFor a user who has a second factor

formLogin

The password is accepted and the sign-in waits for the code.

oauth2Login

The other provider’s sign-in is accepted and waits for the code here.

webAuthn

A passkey whose authenticator verified the user is two factors already, and signs in. One that didn’t waits for the code.

httpBasic

Refused with a 401. Credentials sent with every request have no step to present a code in.

rememberMe

The cookie signs the user in only if the sign-in that issued it passed the second factor. A cookie issued for a password alone, before the user enrolled, is withdrawn. A RememberMeServices of your own has to carry that fact itself: record SECOND_FACTOR_ATTRIBUTE when it issues a cookie, and answer isAfterSecondFactor() on the token autoLogin returns. One that doesn’t can’t sign in a user who has a second factor.

oauth2ResourceServer, apiKey

Accepted. A token or a key isn’t a user signing in. It was issued by a sign-in that already went through the chain’s factors, or by an administrator, and is revoked on its own terms.

The 401 for HTTP Basic says why, in the body and as error="second_factor_required" in the challenge. A wrong password gets the ordinary challenge, so the answer tells nothing to a caller who doesn’t know the password. A chain whose Basic callers are scripts on a trusted network can opt out with httpBasic(basic → basic.secondFactorExempt()).

41.13.2. Enrolling

Enrollment takes two steps, so that nobody is locked out by an app that was never set up. First make a secret and show it to the user:

TotpEnrollment enrollment = totp.beginEnrollment(username);
String forQrCode = enrollment.getOtpauthUri();   // otpauth://totp/...
String forTyping = enrollment.getSecret();       // the same secret, in Base32

Then take a code from their app. Only then does the user have a second factor:

if (!totp.confirmEnrollment(username, code)) {
    return null;                                  // a wrong code: nothing changed
}
List<String> shownOnce = recoveryCodes.generate(username);

Codes are six digits that change every 30 seconds, which is what authenticator apps expect. One step either side of the current one is accepted, to allow for a clock that’s off. A code is good once.

41.13.3. A code by mail

A user without an authenticator app can be mailed a code. Declare an EmailCodeService beside the TotpService, or in its place:

@Bean
EmailCodeService emailCodes(DataSource dataSource, MailSender mail) {
    return new EmailCodeService(new JdbcEmailCodeRepository(dataSource), mail);
}

@Bean
SecurityFilterChain account(HttpSecurity http) {
    http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
        .formLogin(Customizer.withDefaults())
        .mfa(Customizer.withDefaults());
    return http.build();
}

emailCodes.enable(username) turns it on for a user, and disable turns it off. A user with only this factor is mailed a code as soon as their password is accepted. A user who also has an authenticator app is asked for the app’s code, and the page has a button that mails one. Either is accepted.

A mailed code is six digits and good for ten minutes, once. Five wrong guesses spend it, whoever makes them. A new code can be asked for every 30 seconds and replaces the one before it, but it doesn’t bring five more guesses: the count carries over until a code is entered correctly or the last one runs out. Once the five are spent, no code is mailed until then. The server stores a hash of the code, bound to the user it was made for. validitySeconds, maxAttempts and resendSeconds change the numbers, and template renders the mail from a template of your own, which is given code, username and minutes.

The code goes to the address EmailAddressResolver gives for the user. The default takes a username that’s an address as it is. An EmailVerificationService is such a resolver too, and passing it to addressResolver sends codes only to addresses users have proved are theirs.

A mailed code is as strong as the user’s mailbox. It stops a stolen password from being enough. It doesn’t stop someone who reads the user’s mail, which an authenticator app or a passkey does.

41.13.4. Recovery codes

RecoveryCodeService.generate makes ten codes that stand in for a lost phone. Show them to the user once. The server keeps a hash of each and can’t show them again. Each code works once, in place of a one-time code at sign-in, and generating again replaces whatever was left.

New codes are hashed with PBKDF2 and stored as {pbkdf2-sha256}…​. A stored hash says which scheme made it, the way a password does, so codes another system issued can be imported without asking every user for new ones: store the hexadecimal SHA-256 of each code as {sha256}<hex>, hashed from the code in lower case without its dashes or spaces. To verify another scheme, pass your own PasswordEncoder to new RecoveryCodeService(repository, encoder).

41.13.5. The encryption key

JdbcTotpRepository seals each authenticator secret with AES-GCM before it stores it, under a key the database doesn’t hold:

cn1.security.mfa.encryptionKey=replace-with-the-output-of-openssl-rand-base64-32

The key is 32 bytes in base64:

openssl rand -base64 32

Outside a development profile the server doesn’t start without the key. Losing the key loses every enrollment, and so does changing it.

41.14. Passkeys

webAuthn lets a signed-in user register a passkey and, from then on, sign in with it:

http.formLogin(Customizer.withDefaults())
    .webAuthn(passkeys -> passkeys
            .rpId("example.com")
            .rpName("Example")
            .allowedOrigins("https://example.com",
                    "android:apk-key-hash:Zm9vYmFyZm9vYmFyZm9vYmFyZm9vYmFyZm9vYmFyZm9"));

The rpId is the domain the passkeys belong to. The allowed origins are where a ceremony may run, and each is compared whole with what the client reports. A web origin is a scheme, a host and a port when it isn’t the default, with no path and no trailing slash.

An Android application reports android:apk-key-hash: followed by the base64url SHA-256 of its signing certificate. List that origin beside the web one for the application to use the same passkeys. This command prints the hash for a key in a keystore:

keytool -exportcert -alias upload -keystore release.keystore \
    | openssl sha256 -binary | openssl base64 | tr '+/' '-_' | tr -d '='

41.14.1. The two ceremonies

Registration makes a passkey for a user who’s already signed in. Sign-in proves that the caller holds one. Each ceremony is two requests: the client asks for options, which carry a challenge, and then sends back what the authenticator answered. The endpoints take and answer the JSON forms the WebAuthn specification defines, so a browser’s parseCreationOptionsFromJSON and toJSON() and the Codename One client’s WebAuthnClient work with them as they are. The chain serves no page.

RequestWhoWhat it does

POST /webauthn/register/options

Signed in

Answers the options to make a passkey with.

POST /webauthn/register

Signed in

Takes the authenticator’s answer and stores the passkey. A refused answer gets a 400.

DELETE /webauthn/register/{credentialId}

The owner

Removes a passkey.

POST /webauthn/authenticate/options

Anybody

Answers the options to sign in with.

POST /login/webauthn

Anybody

Takes the authenticator’s answer and signs the user in. A refused answer gets a 401 that doesn’t say why.

"Signed in" means in this session. Somebody a remember-me cookie brought back is asked to sign in before they may add or remove a passkey. A ceremony’s options wait in the session for five minutes, and a challenge is answered once. The memory and database session stores consume those options atomically, including across server instances sharing the database. A custom SessionStore must implement consumeAttribute with the same guarantee; the default refuses the ceremony instead of using a separate read and delete.

A passkey whose authenticator verified the user, with a fingerprint, a face or a PIN, is two factors in one step. It signs the user in without mfa asking for a code. One that didn’t verify the user is one factor, and the second factor is asked for, the way it’s asked for after a password. Call userVerification("required") to make every passkey sign-in the first kind.

A registration whose attestation isn’t none or self-signed packed is refused unless you call allowUnverifiedAttestation(true).

41.14.2. Apps and the CSRF token

On a chain that keeps a session, the ceremony’s requests are checked for the CSRF token like any other POST. A page sends it as it does for its other requests. An app has no page to read it from, so leave the ceremony out of the check:

http.csrf(csrf -> csrf.ignoringRequestMatchers(
        AntPathRequestMatcher.antMatcher("POST", "/webauthn/**"),
        AntPathRequestMatcher.antMatcher("POST", "/login/webauthn")));

The four POST requests lose little by it, because each one answers a random challenge kept in the caller’s own session. The DELETE has no such protection, which is why the example leaves it under the check.

41.14.3. Where passkeys are kept

Passkeys are kept in the application’s UserCredentialRepository and PublicKeyCredentialUserEntityRepository beans:

@Bean
UserCredentialRepository passkeys(DataSource dataSource) {
    return new JdbcUserCredentialRepository(dataSource);
}

@Bean
PublicKeyCredentialUserEntityRepository passkeyUsers(DataSource dataSource) {
    return new JdbcPublicKeyCredentialUserEntityRepository(dataSource);
}

With neither, they’re kept in memory and are gone when the server stops, which a server outside a development profile says once when it starts. Neither table holds a secret: a public key verifies and can’t sign. A user who signs in with a passkey is looked up in the application’s UserDetailsService for their authorities.

41.15. Resetting a forgotten password

passwordReset adds the two pages a forgotten password needs, and mails the link between them through the MailSender of Chapter 44, Backend email:

@Bean
OneTimeTokenService oneTimeTokens(DataSource dataSource) {
    return new OneTimeTokenService(new JdbcOneTimeTokenRepository(dataSource));
}

@Bean
PasswordResetService passwordReset(OneTimeTokenService tokens, MailSender mail,
        JdbcUserDetailsManager users, PasswordEncoder encoder) {
    return new PasswordResetService(tokens, mail, users, users, encoder);
}

@Bean
SecurityFilterChain web(HttpSecurity http) {
    http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
        .formLogin(Customizer.withDefaults())
        .passwordReset(Customizer.withDefaults());
    return http.build();
}

GET /forgot-password asks for the username. Posting it mails a link to /reset-password, where the user chooses a new password. The link works once and for 30 minutes. A newer link replaces an older one, and after a reset the user’s remembered sign-ins are removed, so a browser that was remembered has to sign in again. A session that’s already signed in stays until it ends. requestUrl and resetUrl move the pages, and servePages(false) leaves the GET of both to controllers of your own, which post to the same paths with the fields username, and token, password and confirm.

The login page the layer generates gains a "Forgot your password?" link to the request page, and tells a user the reset sends back that the password was changed. A login page of your own links there itself; the reset returns to it with ?reset in the address.

What the layer does so that the pages can’t be turned against your users:

  • The answer never says whether an account exists. A username nobody has gets the same redirect, and no mail. An account that’s disabled or has no address is answered the same way.

  • Asking is rate limited. Five requests in fifteen minutes from one network, and five for one username, then 429 Too Many Requests. A RateLimiter bean is used when there is one, so the limit holds across instances. See Section 41.9.1, “The limits the layer keeps itself”.

  • Only a hash of the token is stored. A copy of the database can’t be used to reset anyone’s password.

  • The link is never built from the request’s Host header. That header is whatever the client sent, and a link built from it would mail your user a link to someone else’s site. Set cn1.security.base-url=https://example.com, or call baseUrl(…​). Without it only a request to localhost is served, which is enough for development, and any other fails naming the setting.

  • The pages aren’t cached and send no referrer, so the token in the address doesn’t leave the browser.

The new password has to be eight characters or more. minimumLength on the service changes that, validityMinutes the life of a link, and template names a mail template of your own, which is given link, username and minutes. The mail goes to the address EmailAddressResolver gives for the user, as in Section 41.13.3, “A code by mail”.

41.16. Verifying an email address

An address a user typed at sign-up is a claim. EmailVerificationService turns it into a fact by mailing a link to it:

@Bean
EmailVerificationService emailVerification(OneTimeTokenService tokens, MailSender mail,
        DataSource dataSource) {
    return new EmailVerificationService(tokens, mail,
            new JdbcVerifiedEmailRepository(dataSource));
}

@Bean
SecurityFilterChain shop(HttpSecurity http, EmailVerificationService verification) {
    http.authorizeHttpRequests(auth -> auth
            .requestMatchers("/checkout/**").access(verification.verified())
            .anyRequest().authenticated())
        .formLogin(Customizer.withDefaults())
        .emailVerification(Customizer.withDefaults());
    return http.build();
}

Send the mail when the account is created, or when the user changes their address:

void afterSignup(EmailVerificationService verification, String username, String email)
        throws IOException {
    verification.send(username, email, "https://example.com/verify-email");
}

emailVerification serves /verify-email, the page the link opens. It has one button. Pressing it marks the address as verified and redirects to /?verified, or to successUrl. Opening the link isn’t enough by itself, because mail gateways open every link in a message to scan it, before the reader sees the message. The user doesn’t have to be signed in when they follow the link. Most people open mail on a different device from the one they signed up on. A link works once and for a day, and a link that’s spent or made up gets a 400 page. A link proves only the address it was mailed to.

verification.verified() is an authorization rule: the request needs a signed-in user whose address is verified. isVerified(username) answers the same question in code. Sending again for a user replaces their pending address and their earlier link. An address stays verified until send is called with another or forget removes it.

41.17. Remembering a user

rememberMe gives a user who ticks the box on the login form a cookie that signs them in on a later visit:

http.formLogin(Customizer.withDefaults())
    .rememberMe(remember -> remember
            .tokenRepository(new JdbcTokenRepository(dataSource))
            .tokenValiditySeconds(30 * 24 * 3600));

The cookie holds a series and a token, and the server keeps token hashes. Using the cookie replaces the token. For ten seconds after that replacement, parallel requests may use either the current token or its immediate predecessor without replacing it again. The database keeps the preceding hash, so this grace also works across servers. An older or unrelated token is treated as a possible copy, and every remembered sign-in of that user is deleted. The cookie lasts two weeks unless you set tokenValiditySeconds.

A remembered user is authenticated, but not fully. fullyAuthenticated() in the rules and isFullyAuthenticated() in a @PreAuthorize refuse them until they sign in again. Signing out deletes the cookie and forgets the user in every browser.

On a chain with mfa, the cookie of a user who has a second factor works only if the sign-in that issued it passed that factor. The server records which kind each cookie is.

Each token records the User-Agent and client address of the sign-in that issued it. PersistentTokenRepository.getTokensForUser lists a user’s tokens for a "signed-in devices" page, and removeUserToken(username, series) signs one of them out. It refuses a series that belongs to someone else.

Without a tokenRepository or a PersistentTokenRepository bean, the tokens are kept in memory. They’re then forgotten when the server restarts, and they’re no use to a deployment of several instances.

41.18. Keeping it in the database

Each store in this chapter has an implementation that keeps its rows in the server’s own database. The tables come from a migration set that ships with the security layer. Ask for it in application.properties:

cn1.security.schema.enabled=true

The build reads the key and registers the set in the server it generates, so this is a build-time setting. It has to be in the module’s application.properties. A server that finds it true only at run time, in the environment, a system property or a properties file beside it, doesn’t start, and the error says where the key belongs. Set to false at run time in a server built with it, the set isn’t applied, and the tables are whatever the database already has. The other build-time keys follow the same two rules; see Section 34.8.2, “Build-time settings”.

The cn1:migrate goals of a module that asks for the tables apply them too, before the module’s own scripts, and cn1:migrate-info lists both histories. A module with no scripts of its own gets the goals as well, for the security tables alone.

Each version is recorded in cn1_security_schema_history under a script name of its own, such as com.codename1.backend.security.SecuritySchema.V4__second_factors, and cn1:migrate prints that name when it applies the version. A history written before the versions had names holds one class name in every row. That history still validates and migrates, because the script name isn’t compared with anything, and its rows are left as they were written. The goals run for a module that has scripts of its own.

A test, or a server you assemble by hand, registers the set before the server starts:

Migrations.register(SecuritySchema.migrations());

The tables are migrations, and Section 39.3, “Schema migrations” describes how those run. The set is called security. It keeps its history in cn1_security_schema_history, apart from your own, and runs before the application’s migrations, so your scripts may refer to its tables. The tables are the same on SQLite, PostgreSQL, and MySQL.

VersionTablesUsed by

1

cn1_users, cn1_authorities

JdbcUserDetailsManager

2

cn1_api_key

JdbcApiKeyRepository

3

cn1_persistent_logins

JdbcTokenRepository, for remembered sign-ins

4

cn1_mfa_totp, cn1_mfa_recovery_code

JdbcTotpRepository, JdbcRecoveryCodeRepository

5

cn1_rate_limit

JdbcRateLimiter

6

cn1_federated_identity

JdbcFederatedIdentityRepository

7

cn1_oauth2_registered_client

JdbcRegisteredClientRepository

8

cn1_oauth2_authorization, cn1_oauth2_token

JdbcOAuth2AuthorizationService

9

cn1_webauthn_user, cn1_webauthn_credential

JdbcUserCredentialRepository, JdbcPublicKeyCredentialUserEntityRepository

10

cn1_rate_limit.window_end

Cleanup retains active windows even when limiters use different periods.

11

cn1_persistent_logins.previous_token_hash

A brief grace period for parallel uses of a remembered sign-in after token rotation.

12

cn1_persistent_logins.user_agent, cn1_persistent_logins.ip_address

The device each remembered sign-in came from.

13

cn1_one_time_token, cn1_mfa_email, cn1_verified_email

JdbcOneTimeTokenRepository, JdbcEmailCodeRepository, JdbcVerifiedEmailRepository

To use tables you already have, give their names in application.properties. A per-table setting names one table, and a prefix replaces the cn1_ in front of every name. The per-table setting wins:

cn1.security.table-prefix=auth_
cn1.security.table.cn1_users=app_users

A name must be letters, digits and _, at most 48 characters, and must not start with a digit. The server refuses to start with anything else. A name is never qualified by a schema; to keep the tables in another schema, set the connection’s search path. Indexes are named after their tables, so two applications with different names can share one database. An adopted table must have the columns this chapter’s stores use. Every store and every schema version uses the configured names.

The key creates the tables. It doesn’t choose the stores. Each store is still a bean you declare, or an object you hand to a chain, as the examples in this chapter do. A feature whose store you don’t declare keeps its state in memory where it has an in-memory default, and the sections above say which do.

Secrets aren’t stored as they are. Passwords are stored as their encoder wrote them. Recovery codes use salted PBKDF2 password hashes; checking one still ends with an atomic removal, so concurrent requests can’t use it twice. Recovery codes from earlier builds that stored plain SHA-256 digests must be regenerated. Verification allows at most four concurrent requests per process and one per username across service instances. Excess attempts fail immediately without queuing hash work or consuming a code; a completed or failed check releases its slot. API keys, remembered sign-in tokens, authorization codes, refresh tokens and device codes are stored as SHA-256 hashes. Authenticator secrets are sealed under cn1.security.mfa.encryptionKey.

Anything that must happen once is one conditional statement and the count of rows it changed. Two instances that present the same code at the same moment can’t both be told yes. That covers a revoked key, a replaced token, a used recovery code and a rate limit’s last permit.

JdbcRateLimiter.deleteExpired, JdbcTokenRepository.deleteExpired and OAuth2AuthorizationService.purgeExpired remove rows nobody will present again. The first two are yours to call from a scheduled job.

41.19. Migrating an existing identity store

Users move to a new server without resetting anything they sign in with, as long as the new server can verify what the old one stored. Part of the work is configuration the server already reads, and the rest is IdentityMigration, which imports the records.

41.19.1. Password hashes

DelegatingPasswordEncoder picks an encoder by the {id} in front of a stored hash, so the old store’s hashes can stay as they are:

  • {bcrypt} reads $2a$, $2b$ and $2y$ hashes.

  • {pbkdf2-sha256} reads Spring Security’s PBKDF2 format.

  • ModularPbkdf2PasswordEncoder reads Django (pbkdf2_sha256$…​), passlib ($pbkdf2-sha256$…​) and Werkzeug (pbkdf2:sha256:…​) hashes, with the digest and the round count taken from each stored value. Register it under an id of your choosing.

  • Any other algorithm is a PasswordEncoder you write and register under its own id.

static PasswordEncoder passwords() {
    Map<String, PasswordEncoder> encoders = new LinkedHashMap<>();
    encoders.put("pbkdf2-sha256", new Pbkdf2Sha256PasswordEncoder());
    encoders.put("bcrypt", new BCryptPasswordEncoder());
    encoders.put("django", new ModularPbkdf2PasswordEncoder(
            ModularPbkdf2PasswordEncoder.Format.DJANGO));
    return new DelegatingPasswordEncoder("pbkdf2-sha256", encoders);
}

An imported hash is re-encoded with the default encoder the first time its owner signs in, as Section 41.2, “Users and passwords” describes, so the old formats fade out without a reset.

41.19.2. Importing the records

The application reads its old store and passes each row to IdentityMigration, which writes it through the server’s own stores:

static MigrationReport migrate(List<OldUser> rows, UserDetailsManager users,
        DelegatingPasswordEncoder passwords, FederatedIdentityRepository links,
        PublicKeyCredentialUserEntityRepository handles,
        UserCredentialRepository credentials, boolean dryRun) {
    IdentityMigration migration = new IdentityMigration(users, passwords);
    migration.setDryRun(dryRun);
    migration.setPasswordPrefix("django");     // the old rows carry no {id}
    migration.setFederatedIdentities(links);
    migration.setPasskeys(handles, credentials);
    for (OldUser row : rows) {
        migration.user(row.email, row.passwordHash,
                Arrays.asList(row.roles.split(",")), row.active);
        if (row.googleSubject != null) {
            migration.federatedIdentity("google", row.googleSubject, row.email);
        }
        if (row.passkeyId != null) {
            migration.passkey(new LegacyPasskey(row.email, row.passkeyHandle,
                    row.passkeyId, row.passkeyCoseKey).signatureCount(row.passkeyCount));
        }
    }
    MigrationReport report = migration.finish();
    System.out.println(report);   // every row that needed more than a copy
    return report;
}

Usernames, authorities, federated subjects, credential ids and user handles are written exactly as given, so a token’s sub and every link other systems hold stay the same. Nothing that already exists is overwritten, so a run can be repeated after fixing the rows it skipped. A dry run writes nothing and returns the same report.

The MigrationReport lists every record with one outcome:

  • MIGRATED: carried over, and its owner signs in as before.

  • NEEDS_ACTION: carried over, but its owner has to act. A hash in a format the encoder can’t verify isn’t imported; the user is created with a random password and has to reset it. A passkey whose public key can’t be read has to be registered again.

  • SKIPPED: not carried over, with the reason. Examples are a user that already exists, a credential id that’s taken, or a user handle that belongs to someone else.

  • NOT_CARRIED: state no migration moves, listed in the table below.

A passkey works on the new server only if it has the same relying-party ID (the domain) as the old one. That’s a rule of WebAuthn, not of this migration.

41.19.3. Signing keys

Tokens the old server issued keep verifying if the new server publishes the same keys under the same kid:

  • cn1.security.authorizationserver.jwk.key-ids gives each key in cn1.security.authorizationserver.jwk.keys the kid it had, in the same order. An empty entry keeps the derived ID.

  • cn1.security.authorizationserver.jwk.verification-keys lists keys that only verify: a public key PEM, or a .json JWK Set, which keeps each key’s kid. Use it for an old key whose private half stays with the old provider, and remove it when the last token it signed has expired. A private key there is refused.

41.19.4. What’s kept and what isn’t

StateKeptWhy

Password hashes

Yes

Verified as stored, re-encoded on the next sign-in. A format no encoder reads needs a reset.

Usernames, subjects, authorities

Yes

Written verbatim.

Federated identities

Yes

Linked by provider and subject.

Passkeys

Yes

Credential ID, public key, counter and user handle. Same relying-party ID only.

TOTP secrets

Yes

Imported confirmed, so authenticator apps keep working.

Signing keys

Yes

Through key-ids and verification-keys.

Sessions

No

Bound to the old server. Every user signs in once.

Remembered sign-ins

No

Hashed or signed with the old server’s secret.

Authorization codes

No

Single use and short lived. A sign-in in progress starts again.

Refresh tokens from the old server

No

The old server issued them. Its clients sign the user in again.

Recovery codes

No

Stored as hashes of the old server’s choosing. Users generate new ones.

41.20. Certificates, key stores and key agreement

com.codename1.backend.security.pki reads and writes the files a server exchanges with certificate authorities and partners. It’s plain Java over the same primitives as the rest of the layer, so a local run and the native build give the same answers.

// A PEM chain, validated against the partner's CA and nothing else
List<Certificate> anchors = Certificate.listFromPem(KeyFiles.read("/etc/app/partner-ca.pem"));
List<Certificate> path = new CertificateValidator(anchors)
        .forHost("partner.example.com")
        .validate(Certificate.listFromPem(presentedPem));

// A key and a certification request to send to a CA
byte[] key = Crypto.generateEcKey(Crypto.P256);
String csr = CertificationRequest.create(DistinguishedName.parse("CN=api.example.com"),
        key, Arrays.asList("api.example.com")).toPem();

// A .p12 in, and one out
Pkcs12 store = Pkcs12.decode(p12Bytes, password);
byte[] p12 = Pkcs12.encode(store.getPrivateKey(), store.getCertificates(), "api", password);

Keys are bytes in two forms: PKCS#8 DER for a private key and SubjectPublicKeyInfo DER for a public one. Crypto.sign, Crypto.verify and Crypto.ecdh take those forms, KeyFiles reads them from PEM, and Der.publicKeyOf derives the public half of a private key.

Crypto.ecdh returns the shared secret of two P-256 or P-384 keys, as SEC 1 defines it. That secret is key material, not a key: derive the key from it with a KDF such as HKDF.

A CertificateValidator trusts only the anchors it’s given. There is no default trust store, so a server that accepts certificates from a partner trusts that partner’s CA and no other. The validator builds a path from the leaf through the other certificates, which may come in any order, and checks:

  • every signature;

  • the validity periods, at the current time or the one at gives;

  • basic constraints, key usage and path length on every issuer;

  • that no critical extension is one it doesn’t understand;

  • the host name and extended key usage, when forHost or forPurpose asks for them.

Host names match the subject alternative names only. The common name is never used, as RFC 9525 requires. The validator doesn’t check revocation.

The algorithm profile is the same on every runtime:

UseSupportedRefused

Signatures on certificates and requests

RSA with SHA-256, SHA-384 or SHA-512; RSASSA-PSS with SHA-256; ECDSA with P-256 and SHA-256, or P-384 and SHA-384

MD5, ECDSA with SHA-1 or a digest that doesn’t match its curve. RSA with SHA-1 is checked, for older intermediates, but never made

Keys

RSA from 2048 to 8192 bits; EC on P-256 and P-384

Other curves, DSA, Ed25519

PKCS#12

PBES2 with PBKDF2 and AES-CBC, with an HMAC integrity check. This is what OpenSSL 3 and current JDKs write. The legacy 3DES and RC2 schemes (openssl pkcs12 -legacy, Apple’s keychain) are read too, and Pkcs12.encodeLegacy writes them for the keychain, which imports nothing newer

Stores without an integrity check

Encoding

DER and PEM

BER indefinite lengths

A file outside the profile is refused with a message that names what it uses.

Certificate.selfSigned makes a self-signed certificate for a key, and Certificate.fetchChain returns the chain a server presents, which is what a pinning check compares. SignedData reads the content and certificates of a CMS envelope, such as a provisioning profile, but it doesn’t check the signature. Asn1 is the DER reader and writer the package is built on, for formats it doesn’t cover.

41.21. Testing

The test library that Chapter 38, Backend testing describes has Spring Security’s test support under the same names:

import com.codename1.backend.annotations.Autowired;
import com.codename1.backend.test.BackendTest;
import com.codename1.backend.test.MockMvc;
import com.codename1.backend.test.WithMockUser;
import org.junit.jupiter.api.Test;

import static com.codename1.backend.test.MockMvcRequestBuilders.get;
import static com.codename1.backend.test.MockMvcRequestBuilders.post;
import static com.codename1.backend.test.MockMvcResultMatchers.status;
import static com.codename1.backend.test.SecurityMockMvcRequestPostProcessors.apiKey;
import static com.codename1.backend.test.SecurityMockMvcRequestPostProcessors.csrf;
import static com.codename1.backend.test.SecurityMockMvcRequestPostProcessors.httpBasic;
import static com.codename1.backend.test.SecurityMockMvcRequestPostProcessors.jwt;
import static com.codename1.backend.test.SecurityMockMvcRequestPostProcessors.user;

@BackendTest
class SecuredApiTest {
    @Autowired
    private MockMvc mvc;

    @Test
    @WithMockUser(username = "ada", roles = "ADMIN")
    void anAdminSeesTheReport() throws Exception {
        mvc.perform(get("/admin/report")).andExpect(status().isOk());
    }

    @Test
    void aStrangerIsSentToSignIn() throws Exception {
        mvc.perform(get("/admin/report")).andExpect(status().isFound());
    }

    @Test
    void aTokenNeedsTheScope() throws Exception {
        mvc.perform(get("/api/orders/7").with(jwt().subject("svc").scopes("orders:read")))
                .andExpect(status().isOk());
        mvc.perform(get("/api/orders/7").with(jwt().scopes("profile")))
                .andExpect(status().isForbidden());
        mvc.perform(get("/api/orders/7").with(apiKey("billing").scopes("orders:read")))
                .andExpect(status().isOk());
    }

    @Test
    void aPostNeedsTheCsrfToken() throws Exception {
        mvc.perform(post("/notes").with(user("ada").roles("EDITOR")).content("{}"))
                .andExpect(status().isForbidden());
        mvc.perform(post("/notes").with(user("ada").roles("EDITOR")).with(csrf())
                        .content("{}"))
                .andExpect(status().is2xxSuccessful());
    }

    @Test
    void realCredentialsAreChecked() throws Exception {
        mvc.perform(get("/internal/health").with(httpBasic("svc", "wrong")))
                .andExpect(status().isUnauthorized());
    }
}

@WithMockUser runs a test, or every test of a class, as a signed-in user who exists nowhere but in the test. No user store is asked and no password is checked. Every request the test sends through MockMvc comes from that user, and SecurityContextHolder on the test’s thread names them too. @WithAnonymousUser runs one test of such a class as nobody.

The request post-processors say something about one request:

Post-processorWhat the request carries

user("ada").roles("EDITOR")

A signed-in user, with the role USER unless told otherwise.

jwt().subject("svc").scopes("orders:read")

A bearer token that was accepted. No token is sent and none is verified. A request it’s refused for gets the 403 a real token gets, insufficient_scope included.

apiKey("billing").scopes("orders:read")

An API key of that owner that was accepted. No repository is asked. A refusal is the one a real key gets.

httpBasic("svc", "secret")

Real credentials in an Authorization: Basic header, for the chain to check.

csrf()

A valid CSRF token in the _csrf parameter. asHeader() sends it in the header, and useInvalidToken() sends a wrong one.

anonymous(), authentication(…​)

Nobody, and an authentication you built yourself.

TestSecurityContextHolder changes who a test runs as part-way through.

Requests sent over a socket with TestRestTemplate aren’t affected by any of this. They’re served on the server’s threads and authenticate as a real client does.

A test’s @PreAuthorize expressions call the beans of the test’s application, so a bean replaced with @MockitoBean is the one an expression reaches.

41.22. A server links only the security it declares

A packaged server is one native binary, and the build leaves out every class that nothing refers to. The security layer is written so that each feature is reached only from the HttpSecurity method that turns it on. A server therefore carries the code of what its chains ask for and nothing else. A server that only verifies tokens has no login page, no password hashing and no user store in it. One that only has a login form has no JWT or key-handling code.

That keeps the binary small, and it has consequences you can see:

  • No chain, no security. A server without a SecurityFilterChain bean links none of the layer. Method security and the Authentication handler parameter are build errors there.

  • Sign-out comes with a session. formLogin, oauth2Login, rememberMe, mfa and webAuthn bring POST /logout and the memory of where a request was going. A chain without one of them lacks both until it calls logout or requestCache.

  • A stateless chain has no CSRF filter unless it calls csrf.

  • Database stores are declared. Setting cn1.security.schema.enabled creates the tables, but nothing picks a Jdbc store for you. A server that declares none of them carries no SQL for them.

  • Client secrets need an encoder you declare. The authorization server compares secrets through the PasswordEncoder bean or clientSecretEncoder. It doesn’t bring the password encoders with it.

  • Sign in with Apple is declared in code. A registration read from the configuration never signs a client secret, so a server that doesn’t declare AppleClientSecret carries nothing that signs one. Declaring Apple in the configuration stops the start.

  • The configured user belongs to the password mechanisms. The cn1.security.user.* keys are read by formLogin, httpBasic and rememberMe only.

41.23. Configuration keys

Every key here is read when the server starts, from wherever the server’s configuration comes from, except cn1.security.schema.enabled. That one is read by the build, because it decides what’s linked into the server.

KeyWhat it sets

cn1.security.user.name, cn1.security.user.password, cn1.security.user.roles

The one user of a server with no user store. The user exists when the password is set. The name is user unless set, and the roles are separated by commas. A password without a {id} prefix is taken as {noop}.

cn1.security.base-url

The address the server is reached at, such as https://example.com, with nothing after the host. Mailed links start with it. See Section 41.15, “Resetting a forgotten password”.

cn1.security.password.maxConcurrent

The most passwords checked at one time. No bound unless set.

cn1.security.schema.enabled

true to create the security tables. Build-time: read by the build from the module’s application.properties. Off unless set. true at run time alone stops the start. false at run time leaves the tables out.

cn1.security.oauth2.resourceserver.jwt.issuer-uri

The issuer whose tokens a resource server accepts.

cn1.security.oauth2.resourceserver.jwt.jwk-set-uri

Where the keys are, for an issuer that publishes no metadata.

cn1.security.oauth2.resourceserver.jwt.public-key-location

A PEM file holding the one public key.

cn1.security.oauth2.resourceserver.jwt.jws-algorithms

The signature algorithms accepted, separated by commas. RS256 unless set.

cn1.security.oauth2.resourceserver.jwt.audiences

What this server is called in a token’s aud, separated by commas. None unless set, and then aud isn’t checked.

cn1.security.oauth2.client.registration.<id>.*

One provider to sign in through. See Section 41.10, “Signing in through another provider”.

cn1.security.oauth2.client.provider.<id>.*

The endpoints of a provider that isn’t built in.

cn1.security.oauth2.client.cookie-secret

The key that signs the pending sign-in of a provider that answers with a posted form. A key made at start-up unless set.

cn1.security.authorizationserver.issuer

The address clients reach the authorization server at. Required outside a development profile.

cn1.security.authorizationserver.audience

The aud of an access token whose request named no resource. The issuer unless set.

cn1.security.authorizationserver.jwk.keys

The PEM files of the signing keys, the signing one first. Required outside a development profile.

cn1.security.authorizationserver.jwk.key-ids

The kid of each key in jwk.keys, in the same order. An empty entry keeps the ID derived from the public key. See Section 41.19, “Migrating an existing identity store”.

cn1.security.authorizationserver.jwk.verification-keys

Public keys that verify tokens and never sign: PEM files, or .json JWK Sets that keep each key’s kid.

cn1.security.oauth2.client.credentials.NAME.grant

client_credentials, jwt_bearer or google_service_account, for AccessTokenProviders.fromConfig(config, "NAME"). The other keys under the same prefix are token-uri, client-id, client-secret, client-authentication (basic, post or private_key_jwt), key-file, key-id, issuer, subject, audience, google-json, scopes, refresh-skew and max-backoff. See Section 41.11, “Calling other services”.

cn1.security.authorizationserver.device.verificationAttempts, cn1.security.authorizationserver.device.verificationWindowSeconds

How many device codes one user may try, and in how many seconds. 10 and 300 unless set.

cn1.security.mfa.attemptsPerAddress

How many of a user’s wrong one-time codes one client address may use up, and how many wrong recovery codes it may try for that user. Half of cn1.security.mfa.attempts, rounded up, unless set.

cn1.security.mfa.attempts, cn1.security.mfa.attemptsWindowSeconds

How many wrong one-time codes a user has from everywhere, and in how many seconds. 5 and 300 unless set.

cn1.security.mfa.encryptionKey

The key that seals authenticator secrets in the database, 32 bytes in base64. Required outside a development profile.

cn1.server.forwardHeaders

true to believe X-Forwarded-For and X-Forwarded-Proto from a trusted proxy. false unless set.

cn1.server.trustedProxies

The proxies, as addresses and CIDR ranges separated by commas. No trusted peers unless explicitly listed.

41.24. How this differs from Spring Security

  • Packages. The classes live under com.codename1.backend.security, and the annotations in com.codename1.backend.annotations.

  • No security without a chain. Spring Boot secures every route once the starter is on the classpath, and generates a password. Here a server with no SecurityFilterChain bean has no security layer.

  • Sign-out isn’t on every chain. A chain without a way of signing in to a session has no POST /logout until it calls logout.

  • A stateless chain skips CSRF. It has the filter only when it calls csrf.

  • Method security is compiled. The build turns each expression into Java and weaves the check into the method. It applies to self-calls, private methods and objects made with new. Only the subset in Section 41.6, “Method security” is accepted.

  • New passwords use {pbkdf2-sha256}, not {bcrypt}. bcrypt is written in Java here and costs more of a thread, so it’s kept for verifying.

  • {noop} works on a development profile only.

  • The authorization server has no consent page. A client is authorized for the scopes it was registered with, and requireAuthorizationConsent accepts false only.

  • OAuth2AuthorizationService isn’t Spring’s interface. It has no save and findByToken pair. A store uses a secret up in one atomic call.

  • The security context stays on the request’s thread. It isn’t propagated to an @Async method or a @Scheduled job.

  • Passkey endpoints are JSON only. The chain serves no page for them.

41.24.1. What isn’t supported

  • In expressions: hasPermission and ACLs, returnObject, T(…​), property chains such as #order.owner.id, and @PostAuthorize, @PreFilter and @PostFilter. Put the decision in a bean method and call it.

  • Method security on an interface method or an abstract method, and two security annotations on one element.

  • Replaying a request after sign-in. Only the address of a GET is remembered.

  • Concurrent-session control. sessionManagement sets the creation policy and the fixation strategy, and nothing else.

  • SAML and LDAP. The ways of signing in are the ones in this chapter. Anything else is a filter or an AuthenticationProvider of your own.

  • Other password schemes. The delegating encoder knows {pbkdf2-sha256}, {bcrypt}, the two Spring PBKDF2 schemes and {noop}. A password stored under another id, such as {argon2} or {scrypt}, is refused unless you register an encoder for it.

  • Opaque access tokens and token introspection. A resource server verifies JWTs, and the authorization server issues them.

  • In the authorization server: dynamic client registration, private_key_jwt and mutual TLS client authentication, pushed authorization requests, DPoP, encrypted tokens, the implicit and password grants, and back-channel or RP-initiated logout.

  • Passkey attestation beyond none and self-signed packed. Other formats are refused, or accepted unverified when you allow it.

  • Shared in-memory state. InMemoryRateLimiter and the in-memory stores are per process. Use the database stores for a server that runs as several instances, and declare a JdbcRateLimiter bean so the second factor’s attempts and the device page’s tries are counted once for every instance.

42. Backend scheduling and background work

Not everything a server does fits inside a request. A report takes a minute to build, webhooks go out after the response, a cleanup runs every night. This chapter covers the three ways to run work outside a request: @Async methods, which return before their work is done; @Scheduled methods, which run on a timetable; and Tasks, for a one-off piece of work. All three run on named executors, and each chooses between platform and virtual threads.

42.1. Background work

The annotations are Spring’s, on ordinary bean methods:

@Component
public class Reports {
    @Async
    public Future<String> monthly(String month) {
        return AsyncResult.of(render(month));
    }

    @Async(thread = ThreadKind.VIRTUAL)
    public void notifyWebhooks(String event) {
        // outbound calls that mostly wait
    }

    @Scheduled(cron = "0 0 3 * * *", zone = "Europe/Berlin")
    public void nightly() {
        // every day at 03:00 Berlin time
    }

    @Scheduled(fixedDelay = 60000, lock = "purge")
    public void purge() {
        // once a minute, on one instance at a time
    }

The build rewrites each @Async method so that it packages its arguments into a task, hands the task to an executor and returns. Each @Scheduled method is registered with the server’s scheduler, with a literal cron expression already compiled into bit masks. Neither involves a proxy, so both work however the method is called.

42.2. Asynchronous methods

An @Async method returns void or a java.util.concurrent.Future; any other return type is a build error, because the caller returns before there is anything to return. Future, the ExecutionException, TimeoutException and CancellationException its get() throws, and TimeUnit aren’t part of the client’s Java subset: they’re backend API, documented in the backend API reference and tested on the translated runtime. The body returns AsyncResult.of(value), and the caller receives, immediately, a Future that completes with that value when the body has run:

  • get() waits for the body and returns its value. On a virtual thread it yields its host while it waits rather than blocking it, so a request handler can wait for an @Async(thread = VIRTUAL) task without stalling the other connections that host serves.

  • An exception the body throws comes out of get() wrapped in an ExecutionException.

  • cancel() succeeds only before the body starts. A running body is never interrupted.

A void method has no Future to deliver a failure through, so an exception it throws is logged, counted against its executor, and recorded on the task’s span. The task runs in a span of its own whose parent is the caller’s, so background work shows up in a trace under the request that started it.

A synchronized @Async method holds its monitor while the body runs on the executor’s thread, not merely while it hands the task over, so two calls still never run the body at once.

@Async on a @Scheduled method is a build error: it would end the run as soon as the work was queued, so runs could overlap and a lock be released early; @Scheduled already runs off the request thread, on the thread its thread attribute picks. @Async on a request- or session-scoped bean builds with a warning, as it runs in Spring: the task calls the bean itself, which is destroyed when its request or session ends, possibly before the task runs.

Arguments are captured when the method is called, and the body runs later on another thread. Pass values rather than objects the caller goes on changing, and remember that the task runs outside the caller’s transaction and outside its request: a request-scoped bean isn’t available to it.

42.3. Executors

Background work runs on named executors, created on first use:

ExecutorUsed by

default

@Async methods that name no executor, and Tasks.platform.

default-virtual

@Async(thread = VIRTUAL) methods that name none, and Tasks.virtual.

scheduling, scheduling-virtual

@Scheduled methods that name none, by thread kind.

any other name

@Async("reports"), or @Scheduled(executor = "reports").

Each is configured under its own name:

cn1.task.executor.reports.threads=4       # pool size; 8 by default, 2 for scheduling
cn1.task.executor.reports.kind=platform   # platform or virtual; overrides the code

A pool’s threads start with its first task, so an unused executor costs nothing. A task submitted while every thread is busy waits in the executor’s queue, and cn1.task.queue_depth reports how many are waiting, by executor.

An executor’s properties also take queue-capacity, the number of tasks that may wait for a thread before a submission is refused with TaskRejectedException, and thread-name-prefix, which names its threads. Tasks.executor(name) returns the executor itself, and setTaskDecorator on it wraps every task it runs, which is where context such as a logging tag is carried from the submitting thread to the worker.

42.4. Platform or virtual threads

thread on @Async and @Scheduled chooses the kind of thread, from ThreadKind:

ValueRuns on

PLATFORM, the default

A thread of the executor’s pool.

VIRTUAL

A virtual thread of its own on the server’s hosts. Where there are none — the development run on the JVM, a TLS server, Windows — on the executor’s pool instead.

AUTO

A virtual thread where the server runs them, a platform thread otherwise. The choice is logged once at start-up.

VIRTUAL means ParparVM’s own virtual threads, which the native build has, and not the virtual threads of Java 21: the two behave differently, and the JVM development run has neither, so it runs VIRTUAL work on platform threads. The choice matters because of how virtual threads work on this runtime, explained under Section 34.6, “Virtual threads and the request loop”. A virtual thread parks while it waits on a socket, so work that queries PostgreSQL or MySQL or calls another service suits VIRTUAL well: thousands of such waits cost thousands of parked stacks rather than thousands of threads. What it must not do is block outside a socket. SQLite and file access are local calls that hold the host thread running them, and with it every connection that host serves, so work that uses them belongs on PLATFORM. PLATFORM stays the default, as a pool is in Spring.

Tasks runs a single piece of work without a bean method:

public void rebuildLater() {
    Tasks.platform(new Runnable() {
        public void run() {
            // runs once, on the default pool of platform threads
        }
    });
}

Tasks.virtual does the same on a virtual thread.

42.5. Scheduled jobs

A @Scheduled method takes no arguments and gives exactly one of cron, fixedRate or fixedDelay. Any of them can come from configuration:

@Component
public class Digest {
    @Scheduled(cron = "${digest.cron:0 0 7 * * MON-FRI}", zone = "America/New_York")
    public void weekdayMorning() {
        // 07:00 New York time on weekdays, unless digest.cron says otherwise
    }

    @Scheduled(fixedRateString = "${digest.pollMillis:30000}", initialDelay = 5000,
               executor = "polling", thread = ThreadKind.VIRTUAL)
    public void poll() {
        // every 30 seconds after a 5 second start-up delay, on a virtual thread
    }

42.5.1. Cron expressions

A cron expression has Spring’s six fields, seconds first, separated by spaces:

FieldValuesExamples

second

0-59

0, */10

minute

0-59

30, 0,15,30,45

hour

0-23

9-17, */2

day of month

1-31, or L for the last day

1, L, ?

month

1-12, or JAN to DEC

JAN,JUL, */3

day of week

0-7, or SUN to SAT; both 0 and 7 are Sunday

MON-FRI, ?

Each field is (or ? for the two day fields), a value, a range a-b, a step /n, a-b/n or a/n, or a comma-separated list of those. The macros @yearly (or @annually), @monthly, @weekly, @daily (or @midnight) and @hourly stand for the usual expressions.

When both day fields are restricted, a day has to match both. That’s Spring’s rule, and it differs from Unix cron, where matching either is enough: 0 0 12 13 * FRI fires on Friday the 13th and not on every Friday.

A literal expression is parsed by the build, so a mistake — 0 0 25 * * * names an hour that doesn’t exist — fails the build with the field at fault, rather than producing a job that never runs, or runs every second. An expression that reads configuration, ${digest.cron:…​} above, is parsed at start-up instead, and a bad one stops the server.

zone is the time zone the expression is read in: a zone ID such as Europe/Berlin, a fixed offset such as +02:00, or UTC. Without one it’s UTC, which is what a server’s clock should be set to regardless. The build checks the name, and a zone on a job that isn’t a cron job is an error. A zone that comes from configuration is checked when the schedule is made — against the host’s time-zone database where it has one — so a misspelled name stops the server instead of running the job on UTC without a word.

In a zone with daylight saving time, a time the clocks skip doesn’t exist, and a job due then doesn’t run that day: 0 30 2 * * * in America/New_York skips the spring-forward night instead of running at 03:30. A time the clocks pass twice, on the night they go back, runs once, at the first of the two. Once that has passed the day’s run is spent, so a server started inside the repeated hour doesn’t run it that night.

42.5.2. Fixed rate and fixed delay

fixedRate starts runs a fixed number of milliseconds apart, measured from start to start. fixedDelay waits that long after each run ends. initialDelay sets how long after start-up the first run begins; without it the first run starts as soon as the server does. The String forms, fixedRateString, fixedDelayString and initialDelayString, accept a placeholder, so a period can be configured per deployment.

Three timelines of the same job: fixedRate starting every ten seconds, fixedDelay waiting ten seconds after each end, and a slow run that causes two skipped starts
Figure 250. fixedRate, fixedDelay and a run that overruns

42.5.3. Runs never overlap

A run never overlaps the previous run of the same job. A start that finds the previous run still going is skipped, and the job is next due at its following time; it doesn’t queue up and run twice to catch up. A fixed-rate job that falls behind resumes on its own grid, without a burst. Each skipped start is counted, so a job that routinely overruns its period shows up in the job listing rather than running less often than it says with nobody noticing.

The scheduler itself is one platform thread that keeps the timetable. The runs happen on the executors, so a slow job delays nothing but its own next run.

42.5.4. One instance at a time

With several instances of a server behind a load balancer, each runs every job. For a job that should happen once — sending the daily digest, purging old rows — lock names a row it claims first:

@Scheduled(fixedDelay = 60000, lock = "purge")

Before each run the instance tries to claim the named row in a table called cn1_scheduler_lock, in the server’s own database, and skips the run when another instance holds it. The claim expires after lockAtMostFor milliseconds — ten minutes when it isn’t set — so an instance that dies mid-run doesn’t hold the job forever. Set it longer than the job’s longest run, or two instances can end up running it at once. The claim’s times come from the database server’s clock, which every instance shares, so an instance whose own clock runs ahead can’t take a claim another still holds. With SQLite, which runs in the server’s process, it’s that host’s clock. A job with a lock needs a database, which the build checks.

A skipped run isn’t a failure. A lock that can’t be claimed for any other reason — the database refusing the statement — is recorded as one, so a broken lock table doesn’t look like a job that’s always somebody else’s turn.

42.5.5. Watching the jobs

A job is named after its class’s simple name and its method, Cleanup.run. When two classes in different packages share a simple name, both jobs take the qualified name, com.example.billing.Cleanup.run, so each can be listed and started on its own.

GET /manage/jobs lists every job with its schedule, its runs, failures and skipped starts, when it last started, how long that took, the last error, and when it’s next due. The development MCP server has the same as backend_jobs, and backend_run_job starts one immediately. The duration of each run is recorded in the cn1.scheduler.run.duration histogram, by job and outcome.

When the server stops, the scheduler stops first so that no run begins during the drain, and runs that haven’t finished get the same grace period as the requests in flight. A task on a virtual thread keeps running on its host thread through that window. One still running when it ends is abandoned and reported, and its Future never completes.

42.6. Pitfalls

  • SQLite or file work on a virtual thread blocks the host thread under it, because neither waits on a socket. Leave such work on PLATFORM. A PostgreSQL or MySQL query parks instead, and is fine on VIRTUAL.

  • Relying on the caller’s context. An @Async body runs outside the caller’s transaction and request. A transaction it needs, it declares itself.

  • A cron expression read in local time. Without zone it’s UTC, so 0 0 9 * * * fires at 09:00 UTC, which is the middle of the night somewhere.

  • lockAtMostFor shorter than a run. Once the claim expires another instance may start the job while the first is still running it.

  • Several instances without lock. Every instance runs every job.

43. Backend caching and messaging

A server that runs as one process can keep its state in memory: the cache, the sessions, the rate-limit counters and the record of which scheduled job ran. Once a second instance starts behind a load balancer, each of those splits in two. A user signs in on one instance and is a stranger to the other, a limit of five attempts becomes ten, and every instance sends the nightly digest. Work that has to outlive a request — shipping an order, sending a receipt — needs somewhere to wait that survives a restart.

This chapter covers both answers: a shared key/value store, usually Redis, that holds the state instances must agree on, and messaging, which hands work from one part of a system to another through a queue or a topic. The programming model is Spring’s (@Cacheable, @KafkaListener, @RabbitListener), and Spring Boot’s property names work too. What differs is how it’s built: the build finds every cache annotation and listener and writes the code for it, so there are no proxies and no reflection. Each broker protocol is a few hundred lines on the backend’s own network layer, with no client library. A protocol the configuration doesn’t name isn’t compiled into the server.

43.1. Scaling out

Two settings move a server from one process to many:

# One Redis for the cache, sessions, rate limits and scheduler locks...
cn1.kv.url=${REDIS_URL}
cn1.session.store=kv
# ...and a broker for messages.
cn1.messaging.url=kafka://kafka-1:9092,kafka-2:9092

cn1.kv.url names the shared store: redis://user:password@host:6379/0, or rediss:// for TLS. Redis, Valkey and KeyDB all speak the same protocol. Once it’s set:

  • @Cacheable and the rest of the cache annotations keep their entries there, so a value one instance computed is a hit on every other.

  • cn1.session.store=kv keeps sessions there, so any instance can serve any request.

  • KeyValueRateLimiter counts there, so a limit applies across the whole deployment.

  • A @Scheduled job with a lock claims it there when the server has no database. A server with a database keeps its locks in the database, as Chapter 42, Backend scheduling and background work describes.

  • The health endpoint reports whether the store answers.

Without cn1.kv.url, Spring Boot’s spring.data.redis.url is read, and then spring.data.redis.host with its port, username, password, database and ssl.enabled. A configuration written for a Spring application needs no change. With none of them set, everything stays in the process, as it was.

43.2. Caching

@Component
public class OrderLookup {
    @Cacheable(value = "orders", key = "#p0")
    public Order find(long id) {
        return load(id);
    }

    @CacheEvict(value = "orders", key = "#p0.id")
    public void update(Order order) {
        // write the change; the next find() reads it again
    }

@Cacheable answers a call from the cache when the cache holds its key, and otherwise runs the method and keeps the result. @CachePut always runs the method and stores the result, and @CacheEvict removes one key, or every key of the cache with allEntries = true.

The build rewrites each method rather than wrapping it in a proxy, so a call from inside the same class is cached too. Spring’s proxy would skip that call. The key expression is compiled at build time. It can name a parameter by position (#p0, #p1), or by name (#id) when the project compiles with javac’s -parameters; a property of one (#p0.id, read through its getter or a public field); a quoted literal; and #root.methodName, joined with +. An expression the build can’t compile fails the build, instead of failing on the first call in production. An empty key means every parameter, as Spring’s default key generator does.

Values are written as JSON by a codec the build generates for the return type, not by Java serialization. A null result isn’t kept. An entry lives for cn1.cache.<name>.ttl seconds, then cn1.cache.ttl, then Spring’s spring.cache.redis.time-to-live; with none set it lives until evicted.

43.3. Messaging

A message is a payload, an optional key and some string headers, sent to a destination: a queue, a topic or a stream, depending on the broker. Sending goes through MessageTemplate, which a bean receives like any other dependency:

@Component
public class Checkout {
    private final DataSource db;
    private final MessageTemplate messages;

    public Checkout(DataSource db, MessageTemplate messages) {
        this.db = db;
        this.messages = messages;
    }

    @Transactional
    public void place(Order order) throws IOException {
        db.execute("INSERT INTO orders (id, customer) VALUES (?, ?)",
                new Object[] {Long.valueOf(order.id), order.customer});
        // Written to the outbox in this transaction, sent once it commits.
        messages.send("orders.placed", order.customer, order);
    }
}

The payload is written as JSON by a generated codec, unless it’s already a String or a byte[]. The key keeps related messages in order on brokers that partition, such as Kafka: messages with one key are handled in the order they were sent.

Receiving is a method on a bean:

@Component
public class Shipping {
    @MessageListener(value = "orders.placed", group = "shipping", concurrency = 4)
    public void placed(Order order) {
        // runs once per message; throwing has it delivered again later
    }

    @MessageListener(value = "orders.placed.dlq", group = "support")
    public void gaveUp(Message message) {
        String why = message.getHeader(Message.ERROR);
        // the order that failed every attempt, and the last exception
    }
}

The method runs once for each message, on a consumer thread, and the message is acknowledged when the method returns. It takes the payload, decoded by a generated codec, or a String, a byte[], or the whole Message with its headers. concurrency sets how many messages it handles at once. A destination can name a setting, ${orders.topic}, read when the server starts.

Spring’s annotations are accepted as written, so a listener can be moved from a Spring application unchanged:

@Component
class Invoicing {
    @KafkaListener(topics = "orders.placed", groupId = "invoicing")
    public void placed(Order order) {
        // the same listener, written as a Spring Kafka application writes it
    }
}

@RabbitListener(queues = …​) and @JmsListener(destination = …​) work the same way.

43.3.1. Groups

Every listener belongs to a group, group (or groupId). Each group receives every message sent to the destination, and the listeners of one group share the messages between them: shipping and invoicing each see every order, and two instances of the shipping service never ship one order twice. Brokers that have no groups of their own (RabbitMQ and SQS) hand every listener of a queue a share of its messages, whatever its group. Use a destination per consumer there, or a fan-out exchange or SNS topic in front of the queues.

43.3.2. Delivery, retries and dead letters

Delivery is at least once. A message is acknowledged only after its listener returned, so a server that dies halfway through a message has that message delivered again, to itself after a restart or to another instance. A listener should therefore be safe to run twice for one message: check whether the order already shipped before shipping it.

A listener that throws has its message delivered again after a backoff:

SettingDefault

cn1.messaging.retry.max-attempts

3

deliveries before the message goes to the dead-letter destination

cn1.messaging.retry.backoff

1000

milliseconds before the second delivery

cn1.messaging.retry.multiplier

2

how much longer each wait is than the last

cn1.messaging.retry.max-backoff

30000

the longest wait

A message that fails every attempt goes to <destination>.dlq, with two extra headers: the exception that failed it (Message.ERROR) and the destination it came from (Message.ORIGIN). A dead-letter destination is a destination like any other, so a listener can read it, as gaveUp does above, to alert someone or to send the message back after a fix.

43.3.3. Sending inside a transaction

With a broker, a message sent from a @Transactional method isn’t sent straight away. It’s written to a table, cn1_outbox, in the same transaction, and sent once the transaction commits. This is the transactional outbox pattern. A rollback sends nothing, so no message ever announces an order that was never saved. A commit never loses its messages either: a process that dies after the commit but before sending leaves the row behind, and another instance sends it after cn1.messaging.outbox.sweep milliseconds (10 seconds). The message may then be sent twice, which at-least-once delivery already allows. Outside a transaction, send sends at once and throws when the broker doesn’t accept the message.

43.4. Brokers

cn1.messaging.url chooses the transport:

URLTransport

memory:

In the process. Nothing survives a restart, and other instances see nothing. The default without a database.

db:

A queue table, cn1_messages, in the server’s own database. The default when there’s a database, so messaging works with no new infrastructure.

redis://host:6379

Redis Streams, one stream per destination and one consumer group per group.

amqp://user:password@host:5672/vhost

RabbitMQ, one durable queue per destination, with publisher confirms.

kafka://host:9092,host:9092

Apache Kafka, one topic per destination and one consumer group per group.

sqs://eu-west-1

Amazon SQS, one standard queue per destination.

pubsub://project

Google Cloud Pub/Sub, one topic per destination and one subscription per group.

amqps://, rediss:// and kafkas:// are the TLS forms. Spring Boot’s spring.rabbitmq.host (or addresses) selects RabbitMQ when cn1.messaging.url isn’t set, and spring.kafka.bootstrap-servers selects Kafka. cn1.messaging.timeout (5000 milliseconds) limits how long a broker connection or reply may take, and cn1.messaging.lease (60000 milliseconds) is how long a consumer may hold a message before it’s delivered again elsewhere, on the transports that take a lease.

Each broker has its own details:

  • Database. A message sent inside a transaction is a row of that transaction, so it needs no outbox. A consumer claims a row with a compare-and-set on it, safe on every engine, and PostgreSQL claims a batch at once with FOR UPDATE SKIP LOCKED. cn1.messaging.db.poll (500 milliseconds) sets how often an empty queue is polled.

  • Redis Streams. A message a consumer claimed and never acknowledged is claimed again by another after the lease.

  • RabbitMQ. A retry waits in a queue of its own whose messages expire back into the original queue. Nothing needs installing on the broker.

  • Kafka. Partitions are shared among a group’s members as the Java client shares them, so a Codename One server and a Spring one can be members of the same group. Records of a partition are handled one at a time, in order, and the group’s offset moves past a record only after its listener returned. A failed record waits in <topic>.retry.<group> and never holds up the topic itself, which Spring Kafka calls a non-blocking retry. A new group starts at the earliest offset; spring.kafka.consumer.auto-offset-reset=latest starts it at the end. Gzip-compressed records can be read; snappy, lz4 and zstd can’t, and transactions and SASL aren’t supported.

  • SQS. sqs://<region> addresses AWS, and sqs://host:port a compatible service such as ElasticMQ or LocalStack, signed for cn1.messaging.sqs.region. Credentials come from the environment, the container or the instance, as for S3. A failed message stays in its queue, hidden until its retry is due. SQS limits a message to 256 KiB, about 190 KiB of payload after encoding.

  • Pub/Sub. Credentials come from the service-account key file named by GOOGLE_APPLICATION_CREDENTIALS, or from the metadata server on Google Cloud; PUBSUB_EMULATOR_HOST points everything at the emulator. Pub/Sub keeps a message only for subscriptions that exist when it’s sent, so a group that has never run misses earlier messages. Create the subscriptions when you deploy, or call PubSubTransport.declare before the first send.

Destination names that a broker rejects are adjusted: SQS turns the . of orders.dlq into -, for example. Keep destination names to letters, digits, ., - and _ and they stay recognizable on every broker.

43.5. Pitfalls

  • A listener that isn’t idempotent. Every transport redelivers a message whose listener didn’t finish, and the outbox can send a message twice. A listener that charges a card on every delivery charges it twice sooner or later.

  • A memory: transport in production. It’s the default for a server without a database, and it loses every queued message on restart. Name a broker, or give the server a database for db:.

  • Holding a message too long. A listener that runs longer than cn1.messaging.lease has its message delivered again to another consumer while it’s still running. Raise the lease, or hand the slow work to a job of its own.

  • Ordering without a key. Only messages with one key keep their order on Kafka. Messages without a key are spread over the partitions.

  • Caching a mutable object. A cached value is a copy written as JSON. Changing the object a call returned doesn’t change the cache; evict or put instead.

44. Backend email

Most servers send mail before they do much else: a welcome, a receipt, a link to set a new password. This chapter covers sending it. One class describes a message, one bean sends it, and the transport behind the bean is chosen by a property. The transport is SMTP for a provider or a relay, the Amazon SES API, or memory for development and tests.

The names follow Spring where a Spring developer would look for them, and Spring Boot’s spring.mail.* properties are read. The surface is smaller. Mail stands in for SimpleMailMessage, MimeMessage and MimeMessageHelper, and MailSender for JavaMailSender. SMTP is implemented on the backend’s own network layer with no mail library, and the build links only the transport the configuration names. A server that never injects MailSender contains no mail code at all.

44.1. Sending a mail

Two settings are enough:

cn1.mail.url=smtp://${SMTP_USER}:${SMTP_PASSWORD}@smtp.example.com:587
cn1.mail.from=Acme <[email protected]>

cn1.mail.from is the sender of every mail that doesn’t name its own. Inject MailSender like any other bean:

@Component
public class Signup {
    private final DataSource db;
    private final MailSender mail;

    public Signup(DataSource db, MailSender mail) {
        this.db = db;
        this.mail = mail;
    }

    @Transactional
    public void register(String name, String email) throws IOException {
        db.execute("INSERT INTO accounts (name, email) VALUES (?, ?)",
                new Object[] {name, email});
        // Staged in this transaction, sent once it commits.
        mail.send(Mail.to(email)
                .subject("Welcome, " + name)
                .text("Your account is ready. Sign in at https://example.com/login")
                .build());
    }
}

Mail.to(…​) starts a builder, and build() checks everything: an address that isn’t one, a header value with a line break in it, or an attachment with no name throws IllegalArgumentException there. A Mail that exists can be sent, so a malformed address fails in the code that produced it and not at the mail server an hour later. Text built from user input is safe in any field, because a value that would inject a header is refused and never escaped into something else.

send returns as soon as the mail is queued. Delivery happens on a thread of the mail support’s own, for two reasons. An SMTP exchange is several round trips, and a request shouldn’t wait for them. And a mail that fails the first time has to be tried again after the request is long over.

44.2. Sending inside a transaction

When the server has a database, send writes the encoded mail to the table cn1_mail_outbox in the caller’s transaction. In the example above, the account row and the welcome mail commit together. If register throws, the transaction rolls back and no mail goes out. If the server stops right after the commit, the row is still there, and the next server to start sends it.

That’s the transactional outbox Chapter 43, Backend caching and messaging uses for messages, and it gives the same guarantee: a committed mail is sent at least once. In the rare case where a server dies between sending the mail and removing the row, the mail goes out twice. It never goes out zero times.

Without a database the queue is in memory. Mail is retried the same way, and whatever is still queued when the process stops is lost.

44.3. Delivery and retries

A mail the server couldn’t take is tried again with a growing delay: 30 seconds, then four times longer each time, up to an hour, for six attempts in all. What happens next depends on why it failed:

  • A temporary failure, such as a 4xx reply, a timeout or a dropped connection, is retried.

  • A permanent failure, a 5xx reply, isn’t. The server said it will never take this mail, and sending it again only harms the sender’s reputation.

A mail that’s given up on moves to cn1_mail_dead with the reason, and a line in the log says so. Nothing sends from that table. It’s there for an operator to read.

sendNow skips the queue. It delivers on the calling thread and throws MailException when the server refuses, for the few cases where the caller has to know before it answers:

public boolean sendCode(String email, String code) throws IOException {
    try {
        mail.sendNow(Mail.to(email)
                .subject("Your code")
                .text("Your code is " + code)
                .build());
        return true;
    } catch (MailException refused) {
        // isPermanent(): the server will never take this mail.
        return false;
    }
}

A mail sent with sendNow isn’t part of the caller’s transaction and isn’t retried.

KeyDefaultWhat it sets

cn1.mail.retry.max-attempts

6

Attempts before a mail is given up on.

cn1.mail.retry.backoff

30000

Milliseconds before the second attempt.

cn1.mail.retry.multiplier

4

What each later wait is multiplied by.

cn1.mail.retry.max-backoff

3600000

The longest wait.

cn1.mail.outbox.sweep

10000

Milliseconds between looks for mails a stopped server left behind.

44.4. Templates

A mail’s HTML can come from the same templates that render pages, described in Chapter 36, Compiled HTML views. Put the template under templates/mail:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
  <p>Hello <span th:text="${customer}">customer</span>,</p>
  <p>Order <strong th:text="${orderId}">1</strong> is on its way.</p>
</body>
</html>
public void shipped(Order order, String email) throws IOException {
    Model model = new Model()
            .addAttribute("customer", order.customer)
            .addAttribute("orderId", Long.valueOf(order.id));
    mail.send(Mail.to(email)
            .subject("Your order shipped")
            .template("mail/shipped", model)
            .build());
}

The template is compiled by the build like every other, so a property the model doesn’t have fails the build with the file and position, and nothing is parsed when a mail is sent.

Every HTML mail should carry a plain text version too. Mail clients that show text need it, and spam filters score a mail without one. The text is derived from the rendered HTML, with the tags removed and the address of each link kept beside its words. Calling text(…​) on the builder gives your own instead.

A mail is read outside your site. A template for one can’t use a relative link or a stylesheet, and has no request to read. Write absolute URLs and inline styles.

44.5. Attachments and inline images

public void invoice(Order order, String email, byte[] pdf, byte[] logo) throws IOException {
    mail.send(Mail.to(email)
            .cc("[email protected]")
            .replyTo("[email protected]")
            .subject("Invoice " + order.id)
            .html("<img src=\"cid:logo\" alt=\"Acme\"><p>Your invoice is attached.</p>")
            .inline("logo", "image/png", logo)
            .attach("invoice-" + order.id + ".pdf", "application/pdf", pdf)
            .header("X-Order", String.valueOf(order.id))
            .build());
}

attach adds a file the reader can save. inline adds an image the HTML shows in place, referenced as cid: followed by the content id. The builder picks the structure a mail client expects from what the mail contains, so there’s no multipart mode to choose.

Subjects, display names and file names can hold any Unicode text. Bodies are always UTF-8. header sets a header of your own, such as List-Unsubscribe.

44.6. Providers

cn1.mail.urlSends through

smtp://user:password@host:587

SMTP with STARTTLS. Every provider with an SMTP endpoint, and any relay.

smtps://user:password@host:465

SMTP over TLS from the first byte.

ses://eu-west-1

The Amazon SES API in that region.

log:

Nothing. Each mail’s headers and text are written to the log.

memory:

Nothing. Mails are kept for a test to read. The default.

Without cn1.mail.url, Spring Boot’s spring.mail.host, spring.mail.port, spring.mail.username and spring.mail.password select SMTP.

44.6.1. SMTP

A username or password containing @, : or / has to be URL-encoded in the URL, or set apart from it with cn1.mail.username and cn1.mail.password.

smtp:// upgrades the connection with STARTTLS before it says anything else, and refuses a server that doesn’t offer it. A password is never sent over a connection that isn’t encrypted, whatever the settings say. For a relay on the same machine that has no TLS, cn1.mail.smtp.starttls=false sends in the clear, without credentials.

Connections are kept open between mails and reused, and several mails handed to send(Mail…​) in one call go over one connection.

KeyDefaultWhat it sets

cn1.mail.smtp.auth

plain, login or xoauth2. Unset takes what the server offers. With xoauth2 the password is an OAuth 2 access token.

cn1.mail.smtp.helo

localhost

The name the client gives for itself.

cn1.mail.smtp.ca

A PEM file of certificates to trust in place of the system’s.

cn1.mail.timeout.connect

5000

Milliseconds a connection may take to open.

cn1.mail.timeout.read

60000

Milliseconds a reply may take.

cn1.mail.pool.max

2

Idle connections kept for the next mail.

cn1.mail.pool.idle

30000

Milliseconds an idle connection is kept.

44.6.2. Amazon SES

ses:// followed by a region sends through the SES API: one signed HTTPS request for each mail, with no SMTP credentials to issue. The credentials are the machine’s own, read from the environment, a container role or an instance role, as for the other AWS services in Chapter 43, Backend caching and messaging. The sender has to be an identity SES has verified. cn1.mail.ses.configuration-set names a configuration set.

44.7. Testing

A test that names no cn1.mail.url sends nothing. Mails are kept in memory, and MailSender hands them back:

@BackendTest(properties = "cn1.mail.from=Acme <[email protected]>")
class SignupTest {
    @Autowired
    private Signup signup;

    @Autowired
    private MailSender mail;

    @BeforeEach
    void emptyInbox() throws Exception {
        mail.clearSent();
    }

    @Test
    void aNewAccountIsWelcomed() throws Exception {
        signup.register("Ada", "[email protected]");

        assertEquals(1, mail.sent().size());
        Mail welcome = mail.sent().get(0);
        assertEquals("[email protected]", welcome.getTo().get(0));
        assertEquals("Welcome, Ada", welcome.getSubject());
        assertTrue(welcome.getText().contains("https://example.com/login"));
    }
}

sent() returns the mails in the order they were sent, with templates already rendered, so getHtml() and getText() are what a reader would have seen. Mail is captured during the call to send, so there’s nothing to wait for.

During development cn1.mail.url=log: prints each mail. To look at mails in a real client, run a catch-all SMTP server on your machine and point cn1.mail.url at smtp://localhost:1025 with cn1.mail.smtp.starttls=false.

44.8. Observing mail

The counters cn1.mail.sent, cn1.mail.failed, cn1.mail.refused and cn1.mail.retried, and the gauge cn1.mail.outbox.pending, are exported with the metrics Chapter 45, Backend tracing, metrics and management describes. Every hand-over to the mail server is a span named mail send, with the transport, the number of recipients and the size of the message. No address is ever written to a span, a metric or the log.

Once a server has sent a mail, its health endpoint reports the transport under mail. When the transport is down, that’s reported and the server stays in service: mail waits in the outbox, and the server’s requests are no worse served for it.

44.9. What isn’t supported

  • Receiving mail. There’s no IMAP or POP3 client.

  • Signing with DKIM. The provider or the relay signs.

  • S/MIME and PGP.

  • Character sets other than UTF-8.

44.10. Pitfalls

  • No cn1.mail.url in production. The default keeps mail in memory and sends nothing. The server says so in its log the first time a mail is sent.

  • A sender the provider hasn’t verified. Providers refuse mail from a domain that isn’t yours to send from. That’s a permanent failure, so every mail lands in cn1_mail_dead.

  • Waiting on sendNow in a request. It holds the request for the whole SMTP exchange. Use send unless the answer depends on the outcome.

  • Treating accepted as delivered. The server accepting a mail says nothing about the inbox. Bounces and complaints come back through the provider’s webhooks or its bounce address.

  • A handler that isn’t safe to repeat. A committed mail can go out twice after a crash. Put what makes a mail unique, such as an order number, where the reader sees it.

45. Backend tracing, metrics and management

A server in production has to answer three questions for whoever runs it: what did this request do, how’s the server doing, and what can be changed without redeploying. Traces answer the first, metrics the second, and managed beans the third. All three follow the OpenTelemetry conventions, so they reach whatever observability stack a deployment already runs, and all three are linked into the binary only when the build is asked for them.

45.1. Tracing with OpenTelemetry

A server can report every request it serves to any OpenTelemetry collector, and the reporting needs no code in the handlers. Turn it on at build time with the annotation, on any class in the backend module:

@OpenTelemetry(serviceName = "notes")
@RestController
public static class NotesController {
    @GetMapping("/notes/{id}")
    public String note(@PathVariable("id") String id) {
        return id;
    }
}

Without touching the source, set it in application.properties instead:

cn1.otel.enabled=true

Either one makes the generated entry point install a tracer. From then on:

  • every request is a server span, named after the route that matched (GET /notes/{id}), with its status, method and path;

  • every outbound Web call is a client span, and sends the W3C traceparent and tracestate headers so the service it reaches joins the same trace;

  • every Database statement is a client span carrying the SQL as the code wrote it, placeholders and all — the bound values are never recorded;

  • an incoming traceparent makes the request part of the caller’s trace, which is how a Codename One app’s spans connect to the backend’s own (see Chapter 101, Distributed tracing with OpenTelemetry).

A WebSocket connection isn’t a span. It can stay open for hours and carry any number of messages, so it has no single start and end to time, and its upgrade request is answered before tracing begins.

Without the annotation or the property, nothing refers to the tracer and the translator leaves it out of the binary.

cn1.otel.enabled is a build-time setting: the build reads it from the module’s properties files. A server built without the exporters that finds it true at run time, in the environment or a properties file beside it, doesn’t start, and the error says where the key belongs. A server built with them that finds it false at run time exports nothing. See Section 34.8.2, “Build-time settings”.

Spans go out over OTLP/HTTP, as binary protobuf by default, batched on a thread of their own so a slow collector never holds up a request. A queue that fills because the collector is down drops spans and counts them, and HttpServer.getMetrics() reports those counts. The settings are the standard OpenTelemetry environment variables, so a deployment configures this server the same way it configures everything else it runs:

VariablePropertyMeaning

OTEL_EXPORTER_OTLP_ENDPOINT

cn1.otel.endpoint

The collector’s base URL; /v1/traces is appended. Defaults to http://localhost:4318.

OTEL_EXPORTER_OTLP_TRACES_ENDPOINT

cn1.otel.traces.endpoint

The full URL, used as it is.

OTEL_EXPORTER_OTLP_HEADERS

cn1.otel.headers

name=value pairs, comma separated, with each value URL-encoded.

OTEL_EXPORTER_OTLP_TRACES_HEADERS

cn1.otel.traces.headers

Headers for traces only, in place of the shared ones.

OTEL_EXPORTER_OTLP_PROTOCOL

cn1.otel.protocol

http/protobuf or http/json. gRPC isn’t supported.

OTEL_EXPORTER_OTLP_TRACES_PROTOCOL

cn1.otel.traces.protocol

The protocol for traces only.

OTEL_SERVICE_NAME

cn1.otel.service.name

Overrides the annotation’s serviceName.

OTEL_RESOURCE_ATTRIBUTES

cn1.otel.resource.attributes

Extra resource attributes, key=value pairs.

OTEL_TRACES_SAMPLER

cn1.otel.sampler

parentbased_always_on by default; also always_on, always_off, traceidratio and the other parentbased_ forms.

OTEL_TRACES_SAMPLER_ARG

cn1.otel.sampler.arg

The ratio for the ratio samplers.

OTEL_SDK_DISABLED

cn1.otel.disabled

true turns tracing off at start-up without a rebuild.

OTEL_BSP_MAX_QUEUE_SIZE

cn1.otel.queue.size

Spans held for export before new ones are dropped. Defaults to 2048.

OTEL_BSP_MAX_EXPORT_BATCH_SIZE

cn1.otel.batch.size

Spans sent in one export. Defaults to 512.

OTEL_BSP_SCHEDULE_DELAY

cn1.otel.export.delayMillis

Milliseconds between exports. Defaults to 5000.

cn1.otel.attributes.exclude names attributes never to record, for example db.query.text in a code base that builds SQL by concatenating values.

Sending spans to Dynatrace, which accepts OTLP over HTTP as protobuf, is a matter of pointing the endpoint at the environment’s OTLP API and passing an ingest token:

OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=https://abc12345.live.dynatrace.com/api/v2/otlp/v1/traces
OTEL_EXPORTER_OTLP_HEADERS=Authorization=Api-Token%20dt0c01.XXXX

Under Lambda, the invocation continues the trace the host passes in its X-Ray header, and the loop waits for the export before it polls again, because the host freezes the process between invocations.

Tracing.current() returns the request’s span, for adding an attribute of the application’s own, and Tracing.inSpan times a block of work as a child span.

45.1.1. Relaying the app’s spans

A mobile app shouldn’t carry the collector’s credentials: anything inside an app package can be read by whoever installs it. With cn1.otel.relay=true the backend accepts the app’s spans at /otel/v1/traces (cn1.otel.relay.path moves it), adds its own credentials and forwards them to the same collector:

cn1.otel.relay=true
# Optional: a shared secret the app sends in X-CN1-Telemetry-Token.
cn1.otel.relay.token=${RELAY_TOKEN}
# Only for a web app served from another origin.
cn1.otel.relay.corsOrigin=https://app.example.com

The relay takes OTLP/JSON, rebuilds it against the OTLP schema — a field the schema doesn’t name is dropped and a malformed id is refused — and queues it for export in whatever protocol the server exports with. It answers as soon as the spans are queued, and answers 503 when the queue is full so the app backs off. cn1.otel.relay.maxBytes and cn1.otel.relay.maxSpans bound a single export.

45.2. Metrics and management

Traces say what one request did; metrics say how the server is doing. With OpenTelemetry turned on, the server exports metrics over OTLP on the same endpoint and with the same settings as its traces, every minute by default, with cumulative temporality. cn1.otel.metrics.enabled=false turns metrics off while leaving traces on. The management endpoints described below record and serve the same metrics whether anything exports them or not.

45.2.1. The metric schema

The metrics the server records about itself have a published schema. Their names, units and attributes are stable, so a dashboard or an alert written against them keeps working when the server is upgraded, and it works the same against a server running on the JVM and a packaged native one. Each metric has one of three availabilities: always, database (when the server has a database pool), or JVM (the packaged server has no equivalent).

InstrumentKindAttributesMeasuredMicrometer equivalent

http.server.request.duration

histogram, ms

http.route, http.request.method, http.response.status_code

always

http.server.requests

http.server.active_requests

gauge

always

http.server.requests.active

http.server.open_connections

gauge

always

tomcat.connections.current

cn1.server.websocket_connections

gauge

always

none

cn1.server.requests_served

gauge, cumulative

always

none

cn1.server.connections_refused

gauge, cumulative

always

none

db.client.connection.count

gauge

database

hikaricp.connections

db.client.connection.idle

gauge

database

hikaricp.connections.idle

db.client.connection.max

gauge

database

hikaricp.connections.max

db.client.connection.pending_requests

gauge

database

hikaricp.connections.pending

db.client.connection.timeouts

gauge, cumulative

database

hikaricp.connections.timeout

cn1.task.queue_depth

gauge

cn1.executor

always

executor.queued

cn1.task.active

gauge

cn1.executor

always

executor.active

cn1.task.completed

gauge, cumulative

cn1.executor

always

executor.completed

cn1.task.pool_size

gauge

cn1.executor

always

executor.pool.size

cn1.scheduler.run.duration

histogram, ms

cn1.job, cn1.outcome

always

tasks.scheduled.execution

process.runtime.memory.used

gauge, bytes

always

jvm.memory.used

process.runtime.memory.committed

gauge, bytes

always

jvm.memory.committed

process.runtime.memory.limit

gauge, bytes

JVM

jvm.memory.max

process.uptime

gauge, seconds

always

process.uptime

jvm.thread.count

gauge

JVM

jvm.threads.live

jvm.class.count

gauge

JVM

jvm.classes.loaded

jvm.cpu.count

gauge

JVM

system.cpu.count

cn1.jvm.gc.collections

gauge, cumulative

JVM

jvm.gc.pause (count)

cn1.jvm.gc.time

gauge, cumulative, ms

JVM

jvm.gc.pause (total)

The route attribute is the template — GET /notes/{id} is recorded as /notes/{id} — so a server’s metric count doesn’t grow with the ids its clients ask for. A request that fails, whether in a handler or in the session store, is recorded with status 500.

GET /manage/schema returns this table for the running server as JSON: its runtime (jvm or native) and, for each metric, its kind, unit, attributes, temporality, Micrometer name and whether this server measures it.

45.2.2. An unmeasured metric is absent, not zero

A metric a server can’t measure isn’t reported as 0. Its instrument isn’t registered, or reads no value, so it’s absent from the JSON view, the Prometheus scrape and the OTLP export, and /manage/schema lists it with "available": false and the reason. On a packaged server that means the JVM-only rows above; on a server with no database it means the pool rows. A gauge whose source can’t be read at collection time is likewise left out rather than written as zero. An alert on "thread count is 0" therefore never fires on a native server by accident: query the series' absence instead, or read the schema.

The schema also lists, under unmeasured, the Micrometer meters a Spring Boot dashboard commonly reads that neither runtime reports, each with its reason: jvm.gc.pause as a per-pause histogram, jvm.gc.memory.allocated and jvm.gc.memory.promoted, per-pool jvm.memory.used, jvm.buffer.memory.used, jvm.threads.states, process.cpu.usage, system.cpu.usage, system.load.average.1m, process.files.open, hikaricp.connections.usage, hikaricp.connections.acquire and logback.events.

45.2.3. Moving a Spring Boot dashboard

The Micrometer column says which series to switch to. In Prometheus form a name’s dots become underscores, so a panel on hikaricp_connections_active reads db_client_connection_count - db_client_connection_idle, one on http_server_requests_seconds_count reads http_server_request_duration_count, and tomcat_connections_current_connections becomes http_server_open_connections. Two differences to adjust for:

  • Units. Durations are milliseconds, not seconds, so a latency threshold of 0.5 becomes 500, and histogram buckets are in milliseconds.

  • Attribute names. Requests carry the OpenTelemetry attributes http.route, http.request.method and http.response.status_code rather than Micrometer’s uri, method and status.

vm/backend/dashboards/backend-overview.json in the Codename One repository is a Grafana dashboard written against the schema: request rate, latency percentiles, errors, connections, the database pool, executors, scheduled jobs, memory and uptime. Import it and pick the Prometheus data source that scrapes /manage/prometheus. It uses only metrics every runtime measures, so its panels are filled on the JVM and on a packaged server alike.

45.2.4. Managed beans

The application’s own metrics follow the JMX model — attributes to watch and operations to call — with Spring’s annotations for it:

@Component
@ManagedResource(objectName = "prices")
public class PriceCache {
    private final Map<String, Double> prices = new LinkedHashMap<String, Double>();

    @ManagedAttribute(description = "Cached prices", unit = "{entry}")
    public synchronized int getSize() {
        return prices.size();
    }

    @ManagedOperation(description = "Drops every cached price")
    public synchronized void clear() {
        prices.clear();
    }

    @Timed
    @Counted
    public synchronized Double price(String sku) {
        return prices.get(sku);
    }
}

@ManagedResource marks the bean, and objectName names it; without one it’s the simple class name. The name is a segment of the management URL, so it’s made of letters, digits, _, - and . only. Each @ManagedAttribute is an instance getter with no parameters, and a numeric one becomes a gauge named after the resource and the attribute — prices.size here — read each time metrics are collected. Every attribute, numeric or not, appears in the management listing. A @ManagedOperation is a method an operator can call, whose parameters may be strings, numbers, booleans, and enums. An operation’s parameters are named by @McpParam when they carry one, and otherwise arg0, arg1, in order. The build checks each of these rules and refuses a managed method on a class with no @ManagedResource. It also refuses a managed resource that isn’t a singleton, because metrics are read outside any request or session. An operation is invoked by name, so it refuses an overloaded one too.

@Timed records each call’s duration as a histogram, and @Counted counts calls, with a second counter for the failures. Their instruments are named after the class and method unless the annotation’s value names them:

AnnotationInstruments

@Timed

<class>.<method>.duration, a histogram in milliseconds

@Counted

<class>.<method>.calls, and <class>.<method>.calls.failures for calls that threw

<class> is the fully qualified class name. Like @Transactional, they’re woven into the method at build time, so a call through this is measured too.

45.2.5. Instruments of your own

Metrics.counter, Metrics.histogram and Metrics.gauge create an instrument for anything the annotations don’t cover:

public final class OrderMetrics {
    private static final Counter PLACED =
            Metrics.counter("orders.placed", "Orders placed", "{order}");
    private static final Histogram TOTALS =
            Metrics.histogram("orders.total", "Order totals", "USD");
    private static final List<String> QUEUE = new ArrayList<String>();

    static {
        Metrics.gauge("orders.queued", "Orders waiting to ship", "{order}",
                new Gauge.Source() {
                    public double read() {           // read when metrics are collected
                        synchronized (QUEUE) {
                            return QUEUE.size();
                        }
                    }
                });
    }

    public static void placed(String id, double total) {
        PLACED.increment();
        TOTALS.record(total);
        synchronized (QUEUE) {
            QUEUE.add(id);
        }
    }

Asking for the same name twice returns the same instrument, so two classes may declare it, and asking for an existing name as a different kind is refused. Keep instruments in static fields, so recording a value looks nothing up. A gauge is a callback read when metrics are collected, which suits a value that already exists somewhere, such as a queue’s length. A histogram’s second form takes bucket boundaries and up to three attribute keys, recorded with record(value, first, second, third).

A gauge can carry fixed tags, Metrics.gauge(name, description, unit, tags, source), so one callback per queue reports under one name. A histogram also answers in process: getCount, getSum and getMean read what it recorded, for a health check or a log line that needs no exporter.

45.2.6. Exporting

Metrics use the tracing settings from Section 45.1, “Tracing with OpenTelemetry” unless a metrics-specific one is set, which is the precedence the OpenTelemetry specification gives:

VariablePropertyMeaning

OTEL_METRIC_EXPORT_INTERVAL

cn1.otel.metrics.intervalMillis

How often to export, in milliseconds. A minute by default.

OTEL_EXPORTER_OTLP_METRICS_ENDPOINT

cn1.otel.metrics.endpoint

The full URL. By default the tracing endpoint’s base with /v1/metrics appended.

OTEL_EXPORTER_OTLP_METRICS_HEADERS

cn1.otel.metrics.headers

Headers for the metrics requests; by default the tracing ones.

OTEL_EXPORTER_OTLP_METRICS_PROTOCOL

cn1.otel.metrics.protocol

http/protobuf or http/json; by default the tracing protocol.

cn1.otel.metrics.enabled

false exports traces only.

When the server stops, it exports once more so the last interval isn’t lost, bounded by the shutdown timeout.

45.2.7. Management endpoints

The management endpoints make the same information available over HTTP, for a load balancer and for an operator:

GET  /manage/health        public; 503 while starting or draining
GET  /manage/health/liveness   public; 200 while the process serves at all
GET  /manage/health/readiness  public; 503 while starting or draining
GET  /manage/schema        the metric schema, as JSON
GET  /manage/metrics       every metric, as JSON
GET  /manage/prometheus    every metric, in the Prometheus text format
GET  /manage/jobs          the scheduled jobs and their last runs
GET  /manage/managed       the managed beans and their attributes
POST /manage/managed/{bean}/{operation}

An operation’s body is a JSON object of its arguments by parameter name. A body that isn’t one, or an argument the operation refuses, is answered with 400; 404 means only that no managed bean or operation has that name. Two managed resources with the same objectName, or two @McpTool methods with the same name, are a build error, since each is found by that name.

Health reports STARTING until the server has finished starting, including the application’s scheduled jobs and exporters, UP while it serves, and DRAINING once it’s stopping. The listener accepts connections before start-up finishes, so a load balancer that checks health doesn’t send traffic to a server that may still fail to start.

KeyWhat it sets

cn1.management.enabled

Whether the endpoints are served. On by default on a development profile, off everywhere else. Build-time: true in the module’s properties files is what links the endpoints into a packaged server.

cn1.management.token

The bearer token every endpoint but health and the probes requires, sent as Authorization: Bearer <token>. A missing or wrong token is answered with 401, and an operation on a server that has no token set with 403. Outside a development profile the server refuses to start with the endpoints on and no token, since the metrics and managed beans would be readable by anyone who can reach the port.

cn1.management.path

Where the endpoints live, /manage by default.

A packaged server has no management code at all unless its build asks for it. The generated entry point is the only code that names the endpoints, and it names them only when the build sees cn1.management.enabled=true in application.properties or a profile’s file. Without it, the translator leaves the endpoints out of the binary, so there’s no /manage to find or to misconfigure, whatever profile the server later runs under. The development run through cn1:backend always builds them in.
cn1.management.enabled=true
cn1.management.path=/ops

A server built with them can still turn them off at start-up with cn1.management.enabled=false. A server built without them that finds cn1.management.enabled=true at run time doesn’t start, because there’s nothing to turn on, and the error says that the key belongs in the module’s application.properties. See Section 34.8.2, “Build-time settings”.

On a development profile without a token, the read-only views are open to anyone who can reach the port, which is a laptop. An operation needs the token on every profile, because it changes the running server.

45.2.8. Probes and draining

The two probes follow the split Kubernetes and Spring Boot’s /actuator/health/liveness and /actuator/health/readiness make. Liveness says the process is running and answering, and stays 200 while it starts and drains; point a liveness probe at it, so a slow start or a drain never gets the container restarted. Readiness is 503 until start-up finishes and again from the moment the server begins to stop; point a readiness probe or a load balancer health check at it. /manage/health answers as readiness does, with the state in the body.

When the server is told to stop (SIGTERM, or the platform’s equivalent), it turns readiness to 503, stops accepting new connections, lets the requests in flight finish within cn1.server.shutdownTimeoutMillis, runs the exporters' last export, and exits. Give the platform’s termination grace period a few seconds more than that timeout. The probes need no token on any profile, since a load balancer has none to send.

Health answers 503 while the server drains, so a load balancer stops sending it new requests before it stops accepting them. The Prometheus view turns each name into a Prometheus one, replacing the dots with underscores and adding _total to a counter, so http.server.request.duration is scraped as http_server_request_duration.

The management endpoints are served before the application’s routes, so a catch-all route can’t answer them.

45.3. Application caches

Cache keeps values a server would otherwise fetch or compute again, with a bound on how many it holds and how long each one lives. It’s plain Java, so the same cache runs on the JVM and in the packaged native server:

private static final Cache<String, Price> PRICES = Cache.<String, Price>builder("prices")
        .maximumSize(10000)                  // or maximumWeight(bytes, weigher)
        .expireAfterWriteMillis(60000)
        .removalListener((sku, price, cause) -> {
            if (cause == Cache.SIZE) {
                System.out.println("evicted " + sku);
            }
        })
        .build();

public static Price price(String sku) {
    // One load per SKU, however many requests ask at once.
    return PRICES.get(sku, CacheSnippets::fetchPrice);
}

public static void priceChanged(String sku) {
    PRICES.invalidate(sku);
}

A builder sets the bounds, and nothing is bounded unless it’s asked for:

SettingMeaning

maximumSize(n)

At most n entries; the least recently used go first.

maximumWeight(w, weigher)

At most w in total, as the weigher weighs each entry. An entry heavier than the whole bound isn’t kept: it’s reported as a SIZE removal, and the other entries stay.

expireAfterWriteMillis(ms)

An entry lives this long after it’s stored.

expireAfterAccessMillis(ms)

An entry lives this long after it was last read or stored.

expiry(expiry)

Each entry’s lifetime, chosen when it’s stored. It replaces the write lifetime for that entry; the access lifetime still applies. A lifetime of zero or less isn’t stored and removes the key’s old value, so a get of such a value calls its loader every time.

removalListener(listener)

Called for every entry that leaves, with the cause: EXPLICIT, REPLACED, EXPIRED or SIZE.

clock(clock)

Where the cache reads the time. Tests replace it to move time without waiting.

45.3.1. Loading

get(key, loader) returns the entry, or runs the loader on the calling thread when there’s none. Requests asking for a key while its load runs don’t load it again: they wait for that load and get its result. A waiting request on a virtual thread yields, so a slow load holds back only the requests that want its key.

A loader that throws stores nothing. Every request waiting for it gets the same failure: an unchecked exception as it was thrown, a checked one wrapped in Cache.LoadException. The next request loads again. A loader that returns null stores nothing either. When the key is invalidated or put while its load runs, the loaded value goes to the requests waiting for it and isn’t stored over the newer state. A loader can use the cache, but asking for its own key is refused rather than waiting forever for itself.

The loader runs as part of the request that started the load, with that request’s transaction, security context and trace. The others only receive its value, so a loader shouldn’t return anything specific to one user.

45.3.2. Expiry and removal

An expired entry is never returned. It’s removed when a read finds it, by a periodic sweep during writes, or by cleanUp(). size() cleans up first, so it counts live entries only.

The removal listener runs on the thread whose call removed the entry, after the cache has released its lock, so it may use the cache. A listener that throws is reported on standard error and changes nothing else.

45.3.3. Metrics

Every cache publishes its figures to Metrics under its name:

NameKindMeaning

cache.<name>.hits

counter

Lookups answered from the cache.

cache.<name>.misses

counter

Lookups that weren’t.

cache.<name>.loads

counter

Loads that finished, including those that returned null.

cache.<name>.load_failures

counter

Loads that threw.

cache.<name>.evictions

counter

Entries removed for the size or weight bound.

cache.<name>.load.duration

histogram

Time spent in the loader, in milliseconds.

cache.<name>.size, .weight

gauge

Entries held, and their total weight.

The same figures are on the cache itself, from hitCount() to evictionCount(). Give each cache its own name; two caches with one name share the counters.

45.3.4. Scope and memory

A cache belongs to one process. Two instances of a server each hold their own, and invalidating a key in one doesn’t reach the other. Values are held by reference, so treat them as read only.

Each entry costs about a hundred bytes beyond its key and value: a map entry with its links in access order, and a node holding the value, its weight and its timestamps.

46. Backend MCP and the agent loop

The Model Context Protocol lets an AI agent call tools on a server. A Codename One backend serves it at /mcp, for two different readers. In production the agent is a user of the application, and the tools are the ones the application chooses to publish. In development the agent is the one writing the server, and the tools let it look inside the running server and exercise it, the way a developer uses a debugger and a database console.

46.1. Serving MCP

The first reason is the application’s own tools. An @McpTool method becomes a tool an agent can call, with its JSON Schema written by the build from the parameter types:

@Component
public class SupportTools {
    private final Signups signups;

    public SupportTools(Signups signups) {
        this.signups = signups;
    }

    @McpTool(description = "Counts the people who signed up. Use it before "
            + "answering a question about growth.")
    public int signupCount() throws Exception {
        return signups.count();
    }

    @McpTool(description = "Signs someone up, as the form on the site would.")
    public String signUp(@McpParam(value = "email", description = "Their email address")
                         String email) throws Exception {
        signups.register(email);
        return "signed up";
    }
}

The description is what an agent chooses tools by, so it says when to use the tool as well as what it does. A parameter needs @McpParam to name it, since a Java parameter name doesn’t survive compilation. Outside a development profile the endpoint refuses to start without cn1.mcp.token. On a development profile the token is optional, but a server without one listens on 127.0.0.1 only, since its tools reach the database and every handler; set a token to serve other machines, and a server bound to another address refuses to start without one. It also refuses a browser request unless its origin is a loopback address or is listed in cn1.mcp.allowedOrigins, which keeps a web page from driving it. A page the server serves itself has to be listed too. An allowed origin gets the CORS answers a browser needs, the preflight included.

46.1.1. Writing a tool

A tool is an instance method of a bean. Its name is the method’s name unless @McpTool(name = …​) gives one, and a name is letters, digits, _, - and . only. Each parameter carries @McpParam with the argument’s name, which has to be unique within the tool, an optional description that goes into the schema, and required, true by default. A tool can’t also be @Async: the agent gets what the method returns, so the method has to run to the end. A parameter may be a String, a number, a boolean, an enum, a Map or a List; the build writes the matching JSON Schema type, and refuses any other type. A number that doesn’t fit the parameter — too large for an int, or for a float — is refused rather than narrowed.

When an agent calls the tool, the arguments are converted to the parameter types and the method is called directly, with no reflection. A value that doesn’t fit — text where a number belongs, or a number outside the range of a short — is answered as a tool error rather than converted into something the agent didn’t send. The return value is sent as the call’s text: a String unchanged, anything else as JSON.

A method that throws is answered with a result marked as an error, which an agent reads and can correct, rather than with a protocol failure. An IllegalArgumentException sends its message, so that’s the exception to throw for arguments the tool can’t use, with a message saying what would work.

46.1.2. The endpoint

The endpoint speaks JSON-RPC 2.0 over MCP’s Streamable HTTP transport, and negotiates protocol versions 2025-06-18, 2025-03-26 and 2024-11-05. It answers initialize, ping, tools/list and tools/call, and answers the resource and prompt listings with empty lists. It keeps no session and opens no event stream, which the transport allows, so each call is one POST with one JSON answer and a GET is answered 405.

KeyWhat it sets

cn1.mcp.enabled

Whether the endpoint is served. On by default when the application has tools, or when the development tools are available; set false to turn it off. Build-time: true in the module’s properties files links the endpoint into a packaged server that has no tools.

cn1.mcp.token

A bearer token every call must carry. Required outside a development profile; without it a development server listens on 127.0.0.1 only.

cn1.mcp.allowedOrigins

Comma-separated browser origins allowed besides loopback ones, or *.

cn1.mcp.path

Where the endpoint lives, /mcp by default.

cn1.mcp.devTools

Whether a development build serves the development tools. On by default on a development profile.

A server restarted in a test serves the tools its own beans provide and nothing a previous one registered.

A packaged server has no MCP code at all unless its build asks for it: a class with an @McpTool method, or cn1.mcp.enabled, cn1.mcp.path or cn1.mcp.allowedOrigins in a properties file. Without any of those, the generated entry point never names the endpoint and the translator leaves it out of the binary, development tools included; cn1:backend builds the development tools in for the development run only. A server built with the endpoint turns it off at start-up with cn1.mcp.enabled=false. A server built without it that finds cn1.mcp.enabled=true at run time doesn’t start, and the error says that the key belongs in the module’s application.properties; see Section 34.8.2, “Build-time settings”. cn1.mcp.path and cn1.mcp.allowedOrigins set only at run time configure an endpoint that’s there and don’t ask for one.

46.2. Tools for developing the server

The second reason is development. When the server runs through cn1:backend on a development profile, the same endpoint also serves tools for inspecting and exercising it, and the server prints the endpoint’s address when it starts:

ToolUse it to

backend_routes

List every route: method, path and the controller method behind it.

backend_beans

List every bean, its scope and what was injected into it, and which conditional beans are active.

backend_config

See the active profile and every configured key, with values that look secret masked.

backend_call

Send the server a request — method, path, body, headers — and read the status, headers and body.

backend_requests

See the last requests served, newest first, with status and time; failuresOnly shows only the ones that failed, with the exception each threw.

backend_logs

Read the last lines the server printed.

backend_sql

Run SQL against the server’s database. Unless write is true, the statement runs in a read-only transaction the database enforces, one statement at a time, so a statement that writes fails even when it begins like a read.

backend_schema

List the entities and their tables and columns.

backend_jobs, backend_run_job

List the scheduled jobs; start one now.

backend_metrics

Read every metric’s current value, optionally only those with a prefix.

backend_managed, backend_invoke

List the managed beans; call an operation.

Claude Code connects to the endpoint with one command:

claude mcp add --transport http cn1-backend http://127.0.0.1:8080/mcp

A host that only speaks stdio runs com.codename1.backend.mcp.StdioBridge from the backend jar with that address instead, and the bridge relays each message. None of these tools are compiled into a server built with cn1:backend-package, unless -Dcn1.backend.devTools=true asks for them. A Gradle project’s backendPackage task takes the same switch as -Pcn1.backend.devTools=true.

46.3. The loop an agent works in

The development tools are meant to be used in a loop that checks each change against the running server rather than against the code alone:

  1. Start the server on the development profile. It gets an in-memory SQLite database with the entity tables created, so it needs nothing installed:

    CN1_PROFILE=dev mvn -pl backend -Dcodename1.platform=backend cn1:backend
  2. Learn the server with backend_routes, backend_beans and backend_schema.

  3. Change the code, restart the server, and exercise the endpoint with backend_call before touching any UI. A failing endpoint is much cheaper to diagnose here than through a screen.

  4. Check what the server saw with backend_requests, and what it stored with backend_sql.

  5. For a change that spans the app as well, run the app in the simulator and drive it through the simulator’s own MCP server, described in Chapter 89, MCP Headless API, then check the requests and rows the same way.

There is no hot reload: after a change to backend code, stop the server and start it again. That takes seconds, and the build regenerates the wiring on the way.

47. Backend performance, deployment and limits

This chapter is for deciding whether the backend fits a service, and for putting it into production once it does: what it costs in time and memory compared with the alternatives, how the binary ships, and the limits worth knowing first.

47.1. What it costs

Same handler, three ways, plus Go for an outside reference. Two pinned cores, 64 connections, medians of three interleaved runs on the plaintext route:

RuntimeRequests/secp50p99Cold start

Codename One native, musl

595,610

0.090 ms

0.249 ms

0.77 ms

Codename One native, glibc

547,761

0.065 ms

4.06 ms

2.88 ms

Go, fasthttp

496,293

0.104 ms

2.63 ms

2.39 ms

The same handler on the JVM

187,745

0.260 ms

1.60 ms

82.5 ms

Cold start is the interesting column. It’s measured from process spawn to the first accepted connection, and the static binary reaches it in under a millisecond — about a hundred times faster than the same code on a JVM, and three times faster than Go. That number is the whole serverless argument.

Throughput is the least interesting one. Beating a tuned Go server by a fifth on a microbenchmark isn’t a reason to move a service; it’s only evidence that the translation doesn’t cost you anything.

A slope chart showing that the musl build’s tail stays close to its median while the others fan out
Figure 251. Latency at the median against the 99th percentile

The slope chart is the one that matters. Every runtime here has a similar median. What differs is the distance to the 99th percentile, and that distance is garbage collection. With the response pooled the plaintext route allocates about 0.1 bytes per request, the collector never runs, and the tail stays at 2.8 times the median. Give the same server a handler that allocates a map per request and its tail goes to 80 ms, because the collector shares the cores with the server.

The honest rule is that the tail follows your allocation rate, not the runtime badge. The runtime gives you the tools to allocate nothing on the hot path; it doesn’t do it for you.

47.1.1. Memory and size

RuntimeBinary or artifactResident under load

Codename One native, musl

7.95 MB static

10-40 MB

Codename One native, glibc

3.19 MB dynamic

14 MB

Go, fasthttp

5.63 MB static

6.3 MB

The same handler on the JVM

0.13 MB jar, plus a JRE

190 MB

The JVM row is the same handler and the same protocol code. Everything it costs above the native rows is the runtime underneath it.

The resident figures move around more than the latency ones, because the collector keeps a pool of pages sized to the busiest moment the process has seen and gives them back gradually. At rest the native builds sit near 3 MB.

47.1.2. musl or glibc

Both are supported, and they aren’t equivalent. The static musl build starts faster and has a far shorter tail. The glibc build has a better median, because its allocator is better under contention, and a smaller binary, because it links the system libraries instead of carrying them.

The reason to pick musl isn’t the median. It’s that the artifact is one file with nothing underneath it, which is what makes the container the binary and the cold start a process exec.

47.1.3. What isn’t measured here

GraalVM is missing from these tables on purpose. A fair comparison would have to run the same handler, and this handler can’t run on GraalVM: the runtime’s native methods are ParparVM’s, so comparing would mean benchmarking a different server written against a different framework and reporting it as though the toolchains had been compared. That’s a benchmark worth building, and it isn’t this one.

47.2. Deploying it

The musl build is a single static file, so the container that carries it can be empty:

FROM scratch
COPY bench-linux-musl-arm64 /server
ENTRYPOINT ["/server"]

There is no base image to patch, because there is no base image. cn1:backend-package builds for the machine it runs on; the cross-compiled targets (musl-x86_64, musl-arm64, glibc-x86_64, glibc-arm64) are produced by vm/backend/package.sh in the Codename One repository, which drives one builder image per target.

For AWS Lambda, LambdaRuntime implements the custom runtime loop. The Lambda Runtime API is a plaintext poll over loopback, so it needs no listening socket and no TLS, and what it does need is exactly what a translated binary is good at.

47.3. Limits worth knowing

  • The class library is the Codename One runtime, not Java SE. A server dependency that assumes the full JDK won’t translate, and Maven Central isn’t the ecosystem this draws on.

  • Beans, injection, transactions, scheduling and metrics are resolved at build time, so what a runtime container discovers on its own — beans in a jar found by scanning, a proxy created for a class decided at run time — isn’t available. There is no starter ecosystem, and validation and error mapping are written by hand or generated from the REST contract.

  • Native packaging compiles Java sources and checks them against the backend’s class library. Kotlin sources aren’t wired into this packaging path yet. Application sources use Maven’s compiler release or source/target, or Gradle’s compileJava.options.release or sourceCompatibility/targetCompatibility. For example, set maven.compiler.release to 17 or 25, or set compileJava.options.release to the corresponding value in Gradle. Use a JDK that supports the selected level. Maven defaults to its own JDK; Gradle uses compileJava’s Java toolchain. `cn1.backend.jdk can select a different JDK (-D for Maven, -P for Gradle). The legacy JDK_8_HOME override applies only when application and test sources both target Java 8. The backend libraries and generated wiring remain at Java 8 independently of the application’s language level. Records, pattern matching for instanceof, and switch expressions can be used by application code. A newer language level doesn’t add Java SE APIs to the native runtime: unsupported API references fail packaging before translation. Pattern matching in switch needs a bootstrap the native translator doesn’t implement and fails packaging; use instanceof branches for native code instead. Compiled tests likewise honor Maven’s testSource/testTarget/testRelease and Gradle’s compileTestJava settings. Compiler arguments, including --enable-preview, are passed to application and test recompilation. Annotation processors on the class path run during those compilations unless disabled with the compiler’s proc setting.

  • A virtual thread parks on sockets and on nothing else. A PostgreSQL or MySQL query, a Web call and a TLS handshake all park it, and its host serves other connections meanwhile. SQLite, file access, resolving a host name and Object.wait() block the host thread that’s running them, and with one host per core, that many concurrent slow calls of that kind occupy every host while other connections wait. A server whose handlers spend their time in SQLite should size for that, or run the thread pool with CN1_HTTP_POLL_MODE=0.

  • Each virtual thread has 64KB of C stack. That holds a few hundred nested Java frames, well past what a handler usually needs, but deep recursion — a recursive parser, a template nested many levels — can run out, and an overflow ends the connection’s host thread with an empty reply. Put @VirtualThreadStack on any class in the backend module to raise it; the size is read at build time, in bytes or with a KB or MB suffix, and when several classes ask, the largest wins:

    @VirtualThreadStack("1MB")
    @RestController
    public class DeepReports {
        @GetMapping("/reports/depth")
        public String depth() {
            return String.valueOf(nest(200));
        }
    
        private static int nest(int n) {
            return n == 0 ? 0 : 1 + nest(n - 1);
        }
    }

    The CN1_HTTP_VT_STACK environment variable sets it at start-up instead, in bytes, and the larger of the two applies. Memory backs a page of the stack only once it’s touched, so a generous size costs address space rather than memory:

    CN1_HTTP_VT_STACK=1048576 ./server

    A Python backend starts at 1MB and takes its size from a build hint instead; see Section 116.6, “Python backends”.

  • TLS runs on the thread pool, whatever the poll mode says. The TLS layer can’t park a read yet, and a blocking read on a virtual thread holds its host for the duration, so one idle TLS client per core would occupy every one of them. The server says so at startup when it makes that choice.

  • Native builds target Linux. Development happens anywhere a JVM runs.

  • WebSockets are RFC 6455 over HTTP/1.1. There is no permessage-deflate, so messages go out uncompressed no matter how compressible, and no RFC 8441, so a browser that reaches this server over HTTP/2 opens a second connection for its WebSocket rather than carrying it on the first. Both are what every client already falls back to. wss works on the packaged runtime through the same TLS the rest of the server uses, and not in the local loop, which terminates no TLS.

The reasons to choose this are cold start, footprint, deployment shape, and one language across the app and its server. If none of those matter for the service in front of you, use a JVM framework.

47.4. External Programs

Backend applications use the shared com.codename1.io.ProcessBuilder and com.codename1.io.Process API described in Chapter 26, Desktop and Backend Processes. The same API serves JavaSE and native desktop applications. Request-scoped children must be closed on completion or cancellation; long-lived children belong to a managed bean with a @PreDestroy cleanup method. A timed wait doesn’t itself terminate a child. See that chapter for pipe draining, virtual-thread behavior, platform restrictions, and the differences from JavaSE.

47.5. Streaming ZIP archives

ParparVM provides the streaming subset of java.util.zip in its Java runtime. The same API is declared in the mobile compile-time library. It includes ZipEntry, ZipInputStream, ZipOutputStream, Deflater, Inflater, DeflaterOutputStream, InflaterInputStream, GZIPInputStream, GZIPOutputStream, Checksum, CRC32, Adler32, CheckedInputStream, CheckedOutputStream, ZipException, and DataFormatException. Compression uses the existing pure-Java JZlib engine. JVM and Android targets use their platform implementation of the standard classes.

This is a streaming API, not the entire Java SE ZIP package. Random-access ZipFile, reverse compression filters, and the FileTime methods on ZipEntry aren’t provided. Reading a ZIP entry verifies its CRC and sizes when its end is reached; call closeEntry() to consume and verify an entry you have only partly read. Closing the input stream doesn’t drain or verify unread entries. ZIP input doesn’t extract files or interpret Unix permissions.

47.5.1. Executable files in a project download

Java SE’s ZipEntry has no setter for Unix external attributes. Use com.codename1.io.zip.ZipArchiveOutputStream when an extracted launcher must remain executable. It accepts standard ZipEntry objects and adds putNextEntry(entry, permissions). This helper runs with both JVM and ParparVM compression and writes the Unix creator platform and external attributes in the central directory.

public static HttpServer.Response projectDownload() {
    return HttpServer.Response.stream(200, "application/zip", new HttpServer.BodyWriter() {
        public void writeTo(OutputStream destination) throws IOException {
            try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(destination)) {
                ZipEntry directory = new ZipEntry("project/");
                directory.setTime(0);
                zip.putNextEntry(directory, 0755);
                zip.closeEntry();

                ZipEntry launcher = new ZipEntry("project/run.sh");
                launcher.setTime(0);
                zip.putNextEntry(launcher, 0755);
                try (InputStream source = openLauncher()) {
                    byte[] buffer = new byte[8192];
                    int count;
                    while ((count = source.read(buffer)) != -1) {
                        zip.write(buffer, 0, count);
                    }
                }
                zip.closeEntry();
            }
        }
    }).header("Content-Disposition", "attachment; filename=project.zip");
}

The permission argument accepts 0000 through 0777. The writer infers a regular file or directory from the trailing slash; it doesn’t create symlinks or special files. Use 0644 for ordinary files. Names are archive paths with / separators. The writer doesn’t sanitize names for extraction, so choose relative names without .. components.

The runnable example is vm/backend/demo/zipdownload/com/demo/ZipDownload.java. It serves a small, fixed project at http://127.0.0.1:8099/project.zip:

export CN1_BACKEND_DEMO=demo/zipdownload
export CN1_BACKEND_STANDALONE_DEMO=1
export JDK_8_HOME=/path/to/jdk8
export JAVA_HOME="$JDK_8_HOME"
export PATH="$JAVA_HOME/bin:$PATH"
cd vm/backend
./build.sh ZipDownload com.demo /tmp/zipdownload
/tmp/zipdownload

The same binary can generate a file without starting HTTP: /tmp/zipdownload --write /tmp/project.zip. Extract it with unzip, then run project/run.sh. The JVM version can be run with CN1_BACKEND_DEMO=demo/zipdownload ./run-javase.sh com.demo.ZipDownload.

HttpServer.Response.stream invokes the writer when it sends the response. Open sources inside this callback and close them with try-with-resources. HEAD and statuses without a body don’t invoke it, so they don’t open sources. Closing the supplied output flushes it without closing the connection. The server ends the response only after the callback returns successfully.

Generation uses the serving worker and fixed transport buffers: 16 KiB for HTTP/1, plus a 16 KiB receive buffer and a 16 KiB native chunk for HTTP/2. It creates no archive-sized byte array, temporary file, or producer thread. HTTP/1.1 uses chunked framing, HTTP/1.0 closes the connection after the body, and native HTTP/2 respects the client’s flow-control window. A slow client holds the serving worker until it grants credit or the socket deadline expires; other streams on that HTTP/2 connection wait while the callback runs.

A disconnected client, HTTP/2 reset, or socket timeout makes output writes throw IOException. Let that exception propagate so source cleanup runs and archive generation stops. Cancellation is detected on output I/O; a callback doing lengthy computation or waiting on its own source must bound that work itself. A callback failure aborts the response rather than emitting a success terminator. The local JVM transport supports HTTP/1; test HTTP/2 with the packaged backend.

47.5.2. Format limits and ownership

  • The default name/comment encoding is UTF-8, with the ZIP UTF-8 flag set. Charset constructors also accept encodings available in the runtime. Names and comments that can’t be encoded without replacement are rejected.

  • Files may be empty. Directories are explicit entries ending in /. Duplicate entry names and empty entry names are rejected.

  • DEFLATED entries stream with data descriptors. STORED entries require a size and CRC before putNextEntry; actual size and CRC are checked at close.

  • ParparVM’s writer and ZipArchiveOutputStream refuse ZIP64. Each entry size, compressed size, and the complete archive must remain below 0xffffffff bytes. There may be at most 65,534 entries. Caller-supplied ZIP64 extra fields are rejected. A limit discovered while streaming raises ZipException and leaves an incomplete archive; discard that output.

  • Payload memory doesn’t grow with file size. Compression uses a fixed window and output buffer. Central-directory records grow with entry count and encoded names, extras, and comments; the writer caps their serialized total at 16 MiB. Java objects and strings add overhead beyond that serialized limit.

  • ZIP field lengths are limited to 65,535 encoded bytes. The writer reserves nine extra-field bytes for an extended timestamp where representable. It records UTC modification times at one-second precision for signed 32-bit Unix seconds; dates outside that range use the DOS timestamp, with two-second precision and a 1980—​2107 range. Explicit setTime(0) gives stable metadata.

  • For repeatable archives, fix entry order, names, comments, permissions, timestamps, and compression level. JVM and ParparVM archives have equivalent contents and metadata, but compressed bytes need not match between engines.

  • finish() writes the directory and leaves the destination open. close() releases compressor state and closes the destination, including after a write failure. A write failure makes the writer unusable. Source streams belong to the caller; use a separate try-with-resources block for each source. No temporary files are created by the ZIP API.

  • Reading supports STORED and DEFLATED ZIP entries, with or without descriptors for DEFLATED entries. ZIP64, encryption, other compression methods, and STORED descriptors are explicitly rejected. GZIP supports concatenated members and validates header and trailer checksums. By default it probes for another GZIP member only when its entire header can be read from buffered or available bytes, avoiding a blocking header read on an idle open connection. For concatenated members on sources whose available() method doesn’t report readable bytes, call System.setProperty("jdk.util.gzip.tryReadAheadAfterTrailer", "true") before constructing the stream. This follows OpenJDK’s read-ahead option: it reads until the source ends and can block on a persistent connection. ParparVM captures the setting when each GZIP stream is constructed.

These explicit ZIP limits belong to the ParparVM implementation and the CN1 helper. The platform’s own java.util.zip.ZipOutputStream may have broader limits, including ZIP64 support.

48. Command-line applications

A command-line tool is a backend with no server in it. It uses the same runtime, the same build and the same packaging, so a tool written in Java starts in milliseconds as a single native executable, with no JVM to install beside it. The arguments are declared with annotations whose names follow picocli, the most widely used Java library for the job, so a picocli command usually needs nothing more than its imports changed.

The Initializr’s Command-line tool project type creates one, for Maven or for Gradle.

48.1. A command

A command is a class annotated @Command that implements Runnable, or Callable<Integer> when it decides its own exit code. Each field annotated @Option or @Parameters receives an argument:

import com.codename1.cli.CommandLine.Command;
import com.codename1.cli.CommandLine.Option;
import com.codename1.cli.CommandLine.Parameters;

import java.util.concurrent.Callable;

@Command(name = "greet", mixinStandardHelpOptions = true, version = "greet 1.0",
        description = "Prints a greeting.")
public class Greet implements Callable<Integer> {
    @Option(names = {"-c", "--count"}, description = "How many times.", defaultValue = "1")
    private int count;

    @Option(names = {"-l", "--loud"}, description = "Shout it.")
    private boolean loud;

    @Parameters(paramLabel = "<name>", description = "Who to greet.")
    private String name;

    @Override
    public Integer call() {
        String line = loud ? "HELLO, " + name + "!" : "Hello, " + name;
        for (int i = 0; i < count; i++) {
            System.out.println(line);
        }
        return 0;
    }
}

Run it on the JVM while you work on it, with the arguments in a property:

./mvnw cn1:backend -Dcn1.backend.args="--count 2 Ada"
./gradlew runBackend -Pcn1.backend.args="--count 2 Ada"

mixinStandardHelpOptions adds -h/--help and -V/--version, and the help is written from the annotations:

Usage: greet [-hlV] [--count=<count>] <name>
Prints a greeting.
      <name>                  Who to greet.
  -c, --count=<count>         How many times. Default: 1
  -l, --loud                  Shout it.
  -h, --help                  Show this help message and exit.
  -V, --version               Print version information and exit.

Nothing is read by reflection. The build reads the annotations and generates the code that fills each field and the application’s main, so a mistake in a declaration is a build error rather than a surprise at run time: two options with the same name, a field type there is no conversion for, positional indexes that overlap, a command with nothing to run, or a static or final field.

48.2. Options and parameters

The command line is parsed the way picocli and the POSIX conventions parse it:

  • Short options cluster: -lc 2 is -l -c 2, and -c2 is -c 2.

  • A long option takes its value after a space or an equals sign: --count 2, --count=2.

  • -- ends the options; every argument that follows is a positional parameter, even one that starts with a dash.

  • @file reads arguments from a file, one or more per line.

  • A boolean option is a flag. With negatable = true it also has a --no- form, and the help shows --[no-]color.

A field’s type decides how its value is converted: the primitives and their wrappers, String, File, and any enum (an unknown value names the ones it accepts). An array, List, Collection or Set collects every occurrence of an option, and split = "," divides one value into several. Any other type needs a converter, and anything the converter throws is reported as an invalid value:

@Command(name = "listen", description = "Opens a port range.")
public class Ports implements Runnable {
    /// A first and last port.
    public static class Range {
        final int first;
        final int last;

        Range(int first, int last) {
            this.first = first;
            this.last = last;
        }
    }

    /// Turns "8000-8010" into a range; anything it throws becomes a usage error.
    public static class RangeConverter implements ITypeConverter<Range> {
        @Override
        public Range convert(String value) {
            int dash = value.indexOf('-');
            if (dash < 0) {
                int port = Integer.parseInt(value);
                return new Range(port, port);
            }
            return new Range(Integer.parseInt(value.substring(0, dash)),
                    Integer.parseInt(value.substring(dash + 1)));
        }
    }

    @Option(names = "--ports", converter = RangeConverter.class, required = true,
            description = "A port, or a range such as 8000-8010.")
    Range ports;

    @Override
    public void run() {
        System.out.println("ports " + ports.first + " to " + ports.last);
    }
}

defaultValue applies when the argument is absent, and is converted like an argument. It can name an environment variable, with a fallback after :-: defaultValue = "${env:NOTES_FILE:-notes.txt}".

@Parameters takes the arguments that aren’t options. With index it takes one position or a range ("0", "1.."); a collection field with no index takes them all. arity sets how many values an option or parameter takes, as in picocli: "1", "0..1", "2..".

48.3. Subcommands

A tool with several verbs, as in git commit, lists them in subcommands. Each is a command of its own; @ParentCommand hands it the command above it, so options given before the verb are shared, and @Spec hands it its own model:

@Command(name = "notes", mixinStandardHelpOptions = true, version = "notes 1.0",
        description = "Keeps notes in a file.",
        subcommands = {Notes.Add.class, Notes.Show.class})
public class Notes {
    @Option(names = {"-f", "--file"}, paramLabel = "<file>",
            description = "Where the notes live.", defaultValue = "${env:NOTES_FILE:-notes.txt}")
    String file;

    @Command(name = "add", description = "Adds a note.")
    public static class Add implements Runnable {
        @ParentCommand
        Notes parent;

        @Option(names = "--tag", split = ",", description = "Tags, comma separated.")
        List<String> tags;

        @Parameters(paramLabel = "<text>", description = "The words of the note.")
        List<String> words;

        @Override
        public void run() {
            System.out.println("adding to " + parent.file + ": " + String.join(" ", words));
        }
    }

    @Command(name = "show", aliases = "ls", description = "Lists the notes.")
    public static class Show implements Runnable {
        @Option(names = "--sort", description = "NEWEST or OLDEST.",
                defaultValue = "NEWEST")
        Order sort;

        @Spec
        CommandSpec spec;

        @Override
        public void run() {
            System.out.println(spec.qualifiedName() + " sorted " + sort);
        }
    }

    public enum Order { NEWEST, OLDEST }
}

notes -f work.txt add --tag home,urgent buy milk runs add; notes ls runs show by its alias. A subcommand may come anywhere after the parent’s options, and notes --help lists the subcommands.

A module may also declare several top-level commands without a group. They become the subcommands of one command named after the application, which is the cn1.cli.name setting in application.properties, or the project’s name.

48.4. Exit codes and output

The process exits with:

  • 0 when the command finishes;

  • the value call() returns, for a Callable<Integer>, or getExitCode() for a command that implements IExitCodeGenerator;

  • 1 when the command throws; the exception’s message is printed to standard error;

  • 2 when the command line doesn’t parse; the error and the usage are printed to standard error.

48.5. Console output and prompts

The com.codename1.cli package has what a tool needs on a terminal: styled text, tables, trees, progress bars, spinners and interactive questions.

Console.print(new Table("Service", "Status", "Replicas")
        .align(2, Table.Align.RIGHT)
        .addRow("api", Console.style("running", Console.Style.GREEN), 3)
        .addRow("worker", Console.style("degraded", Console.Style.YELLOW), 2)
        .render());

try (ProgressBar bar = new ProgressBar("upload", 40).unit("files")) {
    for (int i = 0; i < 40; i++) {
        upload(i);
        bar.step();
    }
}

Spinner spinner = Spinner.start("waiting for health checks");
waitForHealthy();
spinner.succeed("healthy");

Console answers questions about the terminal. width() and height() come from COLUMNS and LINES when they’re set, then from the terminal itself. isTerminal(), isErrorTerminal() and isInputTerminal() say which standard streams are attached to one. colorEnabled() decides whether escape codes are written: never under NO_COLOR, always under CLICOLOR_FORCE, never on a dumb terminal or when standard output goes to a file or a pipe. colorLevel() reports 16, 256 or true color from COLORTERM and TERM, and Ansi builds styled text with any of them, converting a color the terminal can’t show to the nearest one it can. Ansi also moves the cursor, erases lines, switches to the alternate screen and writes hyperlinks.

A table with green, yellow and red status cells, a colored file tree, a 24-bit color ramp and the text attributes

Table sizes its columns to the terminal and wraps cells that don’t fit; Tree draws a hierarchy. Both measure text by what it looks like on screen, so wide characters, emoji and styled text line up. Without a UTF-8 locale they draw with ASCII.

ProgressBar shows a count, a percentage, the rate and the time left, or a moving bar when the total isn’t known; ProgressBar.track(items, "label") wraps a loop. MultiProgress shows several bars at once, and its println writes a log line above them. A Spinner shows that work is under way and ends with a success, failure, warning or information line. They all redraw in place on a terminal. When the output goes elsewhere they print a few plain lines instead, so a log file or a build server shows what happened without escape codes.

Spinner results marked with a check, a warning and an information sign above three progress bars: one finished in green and two under way in cyan

Prompt asks questions:

String env = Prompt.select("Environment", Arrays.asList("staging", "production"));
List<String> regions = Prompt.multiSelect("Regions", Arrays.asList("us-east", "eu-west", "ap-south"));
String token = Prompt.password("API token");
if (!Prompt.confirm("Deploy to " + env + "?", false)) {
    return 1;
}

On a terminal the questions are interactive. Arrow keys move through a list, typing filters it, space checks an item in a multiple choice, and a text answer can be edited with the usual keys. Prompt.Text, Prompt.Select and Prompt.MultiSelect add defaults, validation, masks and page sizes. When standard input isn’t a terminal, each question reads a line instead: a number or a label for a choice, a comma separated list for a multiple choice. That keeps a tool scriptable with printf 'staging\n1,2\n' | tool. Ctrl-C at a question throws Prompt.Cancelled, and the command exits with 130, as a shell reports an interrupted program. The terminal is restored however the program ends, including on Ctrl-C and kill.

A choice from a list, with the arrow on the second item:

A select prompt after an answered text question, with the arrow and highlight on staging

A multiple choice, with two regions checked:

A multiple choice prompt with two regions checked in green and the arrow on the last region

A masked password, an answered confirmation and a number that failed validation:

A masked token, a confirmation answered Yes and a number prompt showing a red error for 12

48.6. Testing

A command is an ordinary class. The build generates CliApplication, in the package of your top-level command, and its commands() lists the models of every top-level command. The generated class appears after the main sources compile, so your tests can use it. A test runs the command line exactly as the binary would: CommandLine.run("greet", CliApplication.commands(), new String[] {"--count", "2", "Ada"}) returns the exit code, here 0.

48.7. Building the executable

./mvnw cn1:backend-package, or ./gradlew backendPackage, translates the tool to C and compiles it with clang into one executable for the machine it runs on, Linux or macOS. Build on each platform you ship to; a continuous integration matrix with one runner per platform is the usual way. The executable needs no JVM and no other files.

The tool compiles against the backend’s class library, the subset of the JDK that the native runtime provides: collections, strings, java.io files and streams, java.time, and the backend’s own networking, database and cryptography APIs. Packaging the tool reports any class outside that subset.

48.8. Command-line tools in Python

A tool written in Python uses argparse, as it would under CPython. Put the modules in src/main/python of a command-line project, in place of the Java command; main.py runs as __main__, with the command line in sys.argv:

import argparse
import sys


def main(argv=None):
    parser = argparse.ArgumentParser(description="Prints a greeting.")
    parser.add_argument("name", help="who to greet")
    parser.add_argument("-c", "--count", type=int, default=1, help="how many times")
    parser.add_argument("-l", "--loud", action="store_true", help="shout it")
    parser.add_argument("--version", action="version", version="%(prog)s 1.0")
    args = parser.parse_args(argv)
    greeting = "Hello, %s" % args.name
    for _ in range(args.count):
        print(greeting.upper() if args.loud else greeting)
    return 0


if __name__ == "__main__":
    sys.exit(main())

The build transpiles the program to Java and generates the entry point that runs it, so runBackend, cn1:backend and the native executable all work as they do for a Java tool. Usage, help and error messages read as CPython’s do, with the project’s name as the program name, or cn1.cli.name from application.properties. The process exits with the status CPython would give it:

  • 0 when the main module finishes;

  • the value passed to sys.exit;

  • 1 when an exception escapes, after its traceback is printed to standard error;

  • 2 when argparse rejects the command line, after the usage and the error are printed to standard error.

The Python is transpiled to Java 17, so the build runs on JDK 17 or newer; the Maven project switches to that level by itself once src/main/python exists. argparse covers the module as programs use it: positional and optional arguments, every action and nargs, type, choices, defaults, subcommands with add_subparsers, argument groups, mutually exclusive groups, fromfile_prefix_chars and the help formatters. On a terminal that accepts color, the usage line, program name and section headings are colored as in CPython 3.14. parse_intermixed_args isn’t supported.

The console API is available to Python as the cn1console module:

import cn1console as console


def main():
    console.print_table([["api", 3], ["worker", 2]],
                        headers=["Service", "Replicas"], align={1: "right"})
    for name in console.progress(["a.txt", "b.txt", "c.txt"], label="upload"):
        pass  # upload the file
    with console.spinner("waiting for health checks"):
        pass  # poll until healthy
    env = console.select("Environment", ["staging", "production"])
    regions = console.checkbox("Regions", ["us-east", "eu-west", "ap-south"])
    if console.confirm("Deploy to %s?" % env):
        console.echo("deploying to", ", ".join(regions), style="bold")

The standard modules read the same terminal: input(), getpass.getpass(), os.get_terminal_size(), shutil.get_terminal_size() and sys.stdout.isatty() behave as they do under CPython. A question cancelled with Ctrl-C raises KeyboardInterrupt, which ends the program with status 130.

48.9. Commands in a backend

The annotations work in a server too, with no setting to turn them on. A backend whose module also declares @Command classes gets a command line: its administration tasks, such as a data import, a user reset or a report, sit next to the server and share its code.

  • With no arguments the binary starts the server, exactly as it did before.

  • serve starts it as well, and --help lists serve and every command.

  • Any other command runs and exits, and the server never starts.

A backend with no commands still accepts --help, and ignores any other argument, so existing deployments are unaffected.

49. Wayline: A ride-hailing app from three sides

Wayline is a sample app with a server behind it. A rider asks for a ride, the nearest suitable driver is offered it, both follow the trip on a map, the ride is paid for when it ends, and an administrator runs the service. The app and the server are one Maven project, written in Java on both sides, and the Initializr’s ride-hailing template generates it under your own name.

This chapter is the user’s guide: what each of the three kinds of user sees and can do. Chapter 50, Wayline: Building on the sample is the other half. It explains how the project is built and what to change to make it yours.

One app serves all three. The server gives every account a set of roles, and the app opens on the screen that fits them: a rider on the map, a driver on the driving screen, an administrator on the operations console. Someone who holds more than one role switches between them from the menu.

RoleWhat it adds

Rider

Every account is a rider. Search for a destination, compare three kinds of car, choose how to pay, follow the driver, rate the ride, tip and keep the receipt.

Driver

Granted when an administrator approves a driving application. Go online, accept or decline the rides offered, drive them, and see and cash out what they earned.

Admin

Granted by another administrator. See the service in numbers and charts, review driving applications, flag or block accounts, cancel and refund rides, read the payments and set the prices.

49.1. Trying it

Start the server on its development profile and it creates a set of accounts, all with the password wayline-demo, and two weeks of rides so that the charts have something to draw. Section 50.1, “Running it” has the commands.

AccountRole

[email protected], [email protected]

Riders, each with a saved test card.

[email protected]

A rider an administrator has flagged.

[email protected], [email protected]

Approved drivers of the standard kind of car.

[email protected], [email protected]

Approved drivers of the two larger kinds. The last one takes a wheelchair.

[email protected]

Has applied to drive and is waiting for a decision.

[email protected]

Runs the service.

Sign in as the rider in one simulator and as a driver in another to follow a ride from both ends.

No money moves on a development server, which simulates cards unless it’s told to use a payment provider. Four numbers behave in four ways:

Card numberWhat happens

4242 4242 4242 4242

Accepted, and every charge succeeds.

4000 0000 0000 0002

Declined when you try to add it.

4000 0000 0000 0341

Accepted when added, then declined when a ride is charged.

4000 0000 0000 0119

Accepted when added, then every charge fails without an answer, so the ride’s payment stays pending.

4000 0000 0000 7726

Accepted, and every charge succeeds. A refund is pending at first, and shows as refunded about a minute later.

Any expiry date in the future and any security code work with them.

49.2. Getting in

The welcome screen offers to sign in or to create an account. Server address is there for a phone on the same network as a development server: localhost on a phone is the phone, so the app has to be told where the server is. The app in a browser has no such entry: it always talks to the server that hosts it.

The Wayline welcome screen with buttons to sign in, to create an account and to set the server address
Figure 252. The welcome screen

Creating an account takes a name, an e-mail address, a mobile number and a password. The e-mail address is what you sign in with. Under I want to, you say whether you plan to ride or to drive. Choosing Drive doesn’t make you a driver; it takes you to the driving application once the account exists.

The form for a new account with fields for name, e-mail, mobile number and password, and a choice between riding and driving
Figure 253. Creating an account

The app then asks for the six-digit code sent to the mobile number. A code is good for five minutes and five attempts, and a new one can be requested after half a minute. A development server prints the text on its console instead of sending it, so it shows the code on the screen as well. You can skip this step with Not now, but the server refuses a ride request from an account whose number isn’t verified.

The verification screen showing the code on screen because a development server sends no text message
Figure 254. Verifying the mobile number on a development server

Signing in is the app’s own form. Behind it, the app runs an OAuth 2.0 authorization-code flow against the server without opening a browser, and keeps the tokens it gets in the device’s secure storage. Signing out revokes the refresh token at the server.

After the first sign-in the app asks once whether it may share usage statistics: which screens are opened and which features are used, and never a name, an e-mail address, a phone number, a place or a card. Share usage statistics agrees and Not now declines, and the app works the same either way. The answer can be changed at any time in the settings.

The screen that asks whether to share usage statistics, with a button to share them and a button to decline
Figure 255. The question about usage statistics

49.3. The rider

A rider can:

  • Search for a destination by name or address, or pick the saved Home or Work.

  • See the route, its length and how long it takes before asking.

  • Compare three kinds of ride with a price each: the standard car, a more comfortable one, and a larger one for up to six people.

  • See how far the nearest car of each kind is, and the free cars on the map.

  • Pay with a saved card or with cash.

  • Ask for a quiet ride, an accessible vehicle, a car that takes pets, or a woman driver.

  • Follow the driver to the pickup and along the trip.

  • Call or message the driver, share the trip, or cancel before the trip starts.

  • Rate the ride from one to five stars and add a tip.

  • Read the list of past rides and the receipt of each.

The home screen is a map with a search card over it and a sheet at the bottom. The round button at the top opens the menu, and the one at the side puts the map back on where you are.

The rider home screen: a map of the city with a search card at the top and shortcuts for home and work at the bottom
Figure 256. The rider’s home screen
The rider home screen in the dark theme with the map drawn in dark colors
Figure 257. The rider’s home screen in the dark theme

The map starts on where you are. While the device is still finding that, a notice at the top of the map says Looking for your location. If it has no answer after eight seconds, the notice becomes Still looking for your location. Try again. When the device can’t work out its position, the notice is Can’t find your location. Try again, and when the app has no permission to ask, it’s Location is turned off. Try again. Tapping the notice asks again. Until a position arrives the map shows the service’s default city, and you can still search for a pickup and a destination.

Pick a destination and the app draws the route and asks the server for a quote. The sheet lists the three kinds of ride with what each costs, how many it seats and how many minutes away the nearest one is. Under them is the way to pay, which you can change by tapping it. The price shown is the fare with the service fee included.

The quote sheet listing three kinds of ride with their prices and the card that will pay
Figure 258. Choosing a ride

The quote is for information. When you ask for the ride, the server works the fare out again from its own prices and fixes it for that ride. A price change an administrator makes a minute later applies to the next ride, not to this one.

The server offers the ride to the nearest free driver who fits what you asked for. That driver has fifteen seconds to accept. If they decline or let the time pass, the next nearest is offered it, and after a short while the search widens from three kilometers to eight. If nobody takes the ride within a minute and a half the app says so, and nothing is charged.

Once a driver accepts, the sheet shows their name, rating, car and license plate, and the car moves on the map as the driver reports in.

The rider screen while a driver approaches: the car on the route, the time to pickup, and the driver’s name, car and plate
Figure 259. A driver on the way to the pickup

On a phone the app doesn’t have to stay open for any of this. A notification says when a driver accepts, when they arrive, when the trip starts and when it ends, and tapping one opens the ride. While a driver is on the way, the ride also shows outside the app: on the lock screen and on the Dynamic Island of an iPhone, and as an ongoing notification on Android. It names the driver, the car and its plate, counts down the minutes to the pickup and fills a bar as the ride goes from on the way to arrived, the trip and its end. It moves on with every step of the ride and, every minute or so, with the minutes left. It goes when the ride is canceled, and stays a short while to say you’ve arrived when the trip is complete.

Notifications reach a phone only from a server connected to the push service, which Section 50.15, “Push notifications” sets up. A server started for development prints each notification in its output instead.

Table 13. The ride on the lock screen
WhereWhat shows

iPhone

A Live Activity on the lock screen and on the Dynamic Island.

Android

An ongoing notification. The first ride asks for permission to show notifications.

Desktop and the simulator

A small window beside the app, while the app runs.

A browser

Nothing. The page shows the ride while it’s open.

Call and Message open the phone’s dialer and its messaging app, so they’re offered only on a device that can dial. Share opens the device’s share sheet with a sentence naming the destination, the driver and the car. Cancel ends the ride at any point before the trip starts. The sample charges nothing for a cancelled ride.

When the driver completes the trip the server charges the card, and the sheet asks how the ride was.

The sheet shown when a ride ends, with the fare, five stars to rate the driver and a row of tip percentages
Figure 260. The end of a ride

The tip is a percentage of the fare or, from the receipt, any amount. It’s a second charge to the same card, made once, and the whole of it goes to the driver. On a ride paid in cash the tip is recorded on the receipt and in the driver’s earnings, and no card is charged for it.

49.3.1. Wallet and receipts

Wallet in the menu lists the saved cards and cash, which is always there. Tapping a card makes it the one that pays unless you choose otherwise when you ask for a ride. An account holds up to eight cards.

The wallet with one saved card marked as the default, cash, and a button to add a card
Figure 261. The wallet

How a card is added depends on the server. With simulated payments the card is typed into the app. With a real provider the app opens the provider’s own page in the browser, so the card number never reaches the app or the server, and the app picks the result up when you come back to it.

Past rides are listed under Your rides. Pull the list down to load it again. Each ride opens a receipt with the trip, the driver and the fare broken into its parts.

A receipt showing the total paid, the pickup and drop-off, the driver, and the fare split into base fare, distance, time, service fee and tip
Figure 262. A receipt

49.4. The driver

A driver can:

  • Apply to drive, and correct and resend an application that was sent back.

  • Go online and offline.

  • See each ride offered with its pickup, destination, distance and fare, and accept or decline it within the time allowed.

  • See what the rider asked for: a quiet ride, an accessible vehicle, a pet.

  • Mark the arrival at the pickup, the start of the trip and its end.

  • Call or message the rider, or cancel before the trip starts.

  • See today’s and this week’s earnings, the last two weeks day by day, and the list of past trips.

  • Register a bank account and cash out the balance.

49.4.1. Applying to drive

Anyone with an account can apply, from Drive with Wayline in the rider’s menu. The application has five steps, and each is saved as you leave it, so an application can be finished later:

  1. Your legal name, date of birth and gender.

  2. The driving license: its number and when it expires.

  3. The car: make, model, year, color, plate, how many it seats, the kind of ride it suits, and whether it takes a wheelchair or pets.

  4. Five photographs: an identity document, the license, a picture of you, the vehicle registration and the insurance.

  5. A review of the whole application before it’s sent.

Step four of five of a driving application, with a card for each document and buttons to retake a photo or pick one from the gallery
Figure 263. The documents step of a driving application

Each photograph comes from the camera or the gallery. The app shrinks it before sending, and the server accepts JPEG and PNG files of up to 1.5 MB.

Once sent, an application waits for an administrator. Until one decides, the applicant sees where it stands and goes on riding.

The screen an applicant sees while an application is under review, with the steps that follow
Figure 264. An application waiting for a decision

Approval gives the account the driver role, and the app opens on the driving screen from then on. A rejection comes with the administrator’s reason. The applicant can change what was wrong and send the application again.

49.4.2. Driving

The driving screen is a map with the day’s earnings at the top and a badge that reads Offline or Online. A driver starts offline. The sheet says You are offline and, under it, Go online to start taking rides.

The driving screen while offline: the day’s earnings, a badge reading Offline and the round GO button
Figure 265. A driver who is offline

GO puts the driver online. The badge changes to Online, the sheet says Looking for rides, and the app reports the car’s position to the server every few seconds. Go offline stops the offers. A driver who is online and stops reporting for a minute is no longer offered rides either.

A driver doesn’t have to keep the app on the screen. While they’re online the phone goes on reporting where the car is with the app in the background, when the driver switches to a navigation app or locks the phone. It reports when the car has moved about 25 meters, and every twenty seconds when it hasn’t, which spares the battery and keeps the driver well inside the minute. On Android a notification that reads You’re online stays while it does. An iPhone asks the driver whether Wayline may use the location while the app isn’t in use, and the reports from the background need that answer to be yes. Going offline, signing out or switching to the rider’s side of the app stops the reports. The simulator and a browser don’t report from the background.

A new ride request arrives as a notification too, and tapping it opens the driving screen with the offer. The offer is open for fifteen seconds, so the notification is too: one that can’t be delivered within that time may never arrive. A rider who cancels is also announced in a notification.

An offer shows the fare, how far the pickup is and how long the trip is, with a ring counting down the time left to answer.

The driver screen with a ride request: the fare, a countdown ring, the pickup and destination, and buttons to accept or decline
Figure 266. A ride offered to a driver

After accepting, the driver follows the route to the pickup, taps I have arrived, then Start trip when the rider is in the car and Complete trip at the destination. For a ride paid in cash the sheet says how much to collect.

The driver screen during a trip, with the route to the destination, the amount to collect in cash and a button to complete the trip
Figure 267. A trip under way, paid in cash

A driver can cancel after accepting and before the trip starts. A trip that has started can only be completed, or cancelled by an administrator.

49.4.3. Earnings

Earnings in the driver’s menu shows the balance ready to cash out, the totals for today, this week and this month, a chart of the last two weeks, the number of trips, the tips, the rating and the share of offers accepted. Under them are the payouts already made.

The earnings screen with the balance ready to cash out, the totals for today, this week and this month, and a chart of the last two weeks
Figure 268. A driver’s earnings

A driver earns the fare less the service’s commission, and every tip in full. Cash out asks for a bank account the first time: the holder’s name, the bank and the last four digits of the account number.

Cashing out records a payout and sets the balance to zero. The sample moves no money to a bank. Section 50.13, “Billing” says what that takes.

49.5. The administrator

An administrator can:

  • See what’s happening now: rides today, rides under way, drivers online and fares collected.

  • See trends over 7, 14 or 30 days: rides and fares by day, the share completed, the average fare and wait, requests by hour of the day, rides by outcome and by kind, and the drivers with the most rides.

  • Review driving applications with their documents, and approve them or send them back with a reason.

  • Search the accounts, see each one’s rides, spending, earnings and rating, and give or take away the driver and admin roles.

  • Flag an account, which marks it for the other administrators, or block it, which signs it out and refuses it until the block is lifted. Both take a reason, and both are kept in the account’s history with who did it and when.

  • See every ride, cancel one under way, and refund one that was paid by card.

  • See every payment.

  • Set the prices.

  • Watch the cars that are online move on a map.

The same screens are laid out in two ways. On a phone the console is one screen at a time with a menu. In a window at least 165 mm wide, which is a tablet, a desktop or a browser, it’s a console with its sections down the side and a list beside the item picked from it.

49.5.1. On a phone

The dashboard opens with what needs attention, as buttons that lead to it, then the four numbers and the charts.

The admin dashboard on a phone: an alert for one application to review and one flagged account above four numbers describing the service right now
Figure 269. The dashboard on a phone
Two bar charts on the admin dashboard, one of rides per day and one of fares per day
Figure 270. Trends, further down the dashboard

The lists of applications and of rides are loaded again by pulling them down. A desktop window has no such gesture, and its lists load when the section opens.

An application opens with everything the applicant entered and the five documents, each of which opens full size. Approve and Send back are at the end of it.

A driving application as an administrator reads it, with the applicant’s details and the vehicle
Figure 271. A driving application under review

An account opens with its standing, its numbers, its contact details, the two role switches, the moderation buttons and its history.

An account an administrator has blocked, showing the reason, the number of rides taken and cancelled, and the amounts spent and earned
Figure 272. A blocked account

49.5.2. On a wide screen

The desktop build takes the look of the operating system it runs on, in its colors, fonts, and controls.

The admin console in a desktop window with its sections down the left side and the dashboard’s numbers and charts laid out in three columns
Figure 273. The dashboard in a desktop window

Applications lists them by status, and the one picked opens beside the list.

The applications section of the console: a list of waiting applications on the left and the selected application with its documents on the right
Figure 274. Applications, with one open beside the list

People has a search field and filters for riders, drivers, admins, flagged and blocked accounts.

The people section of the console: a searchable list of accounts with their roles, and the selected account’s numbers, roles, moderation buttons and history
Figure 275. People, with an account open

Rides lists the most recent rides with their state: every ride, or only those under way, completed, or cancelled. A ride opens with the trip, the fare and how it was paid. From there an administrator can cancel a ride that hasn’t finished and refund one that was paid by card. A refund returns the fare, the service fee and the tip. A ride paid in cash has nothing to refund. A refund the payment provider hasn’t finished shows as Refund pending until it does. One the provider then fails shows as Refund failed and needs looking up with the provider.

The rides section of the console: filters for all, under way, completed and cancelled rides above a list of rides with their fares and states
Figure 276. Rides

Payments lists what was charged for each ride, by which method and with what result.

The payments section of the console listing each charge with its destination, the rider, the card or cash, the amount and whether it was paid
Figure 277. Payments

Pricing holds the numbers every fare is worked out from: a base fare, a price for each kilometer and each minute, a minimum, the service fee added on top for the rider, the commission kept from the driver, and a multiplier for each of the two larger kinds of ride and for times of high demand. The currency is a setting of the server and isn’t changed here.

The pricing form with the base fare, the price by kilometer and minute, the minimum fare, the service fee and commission, and the multipliers
Figure 278. Pricing

Live map fills the window with a map of the cars that are online, which move as their drivers report in.

The live map section of the console filling the window with a map of the city and a note that no cars are online
Figure 279. The live map

The screens the console doesn’t own, such as the settings, keep their phone layout in a column in the middle of the window. An administrator is a rider too, and Riding under Switch to opens the rider’s map.

The rider home screen filling a desktop window with a wide map and the search card across the top
Figure 280. The rider’s home screen in a desktop window

49.6. Settings

The Settings screen is in every role’s menu and is the same in each. What’s chosen there is stored on the server with the account, so it follows the user to another device.

The settings screen with the account’s profile, verified phone number and password, followed by the ride preferences
Figure 281. Settings
The settings screen in the dark theme
Figure 282. Settings in the dark theme
SectionWhat it holds

Account

The profile, which is the name, gender, an emergency contact and the saved home and work addresses. The mobile number and whether it’s verified. Changing the password, which asks for the current one. Every other device signed in to the account has to sign in again with the new password; the device you changed it on stays signed in.

Ride preferences

Any driver or women only, a quiet ride, an accessible vehicle, and a pet-friendly car. They’re sent with every ride request.

Payment

The wallet, the method that pays by default, and the tip offered first.

Notifications

Switches for ride updates, receipts and offers. With Ride updates off the phone gets no notification of a ride’s steps, and with Receipts off none when a trip ends. The ride on the lock screen goes on either way.

Appearance

The language, the theme, and whether distances are in kilometers or miles.

Privacy and safety

Whether to share trips, the emergency contact, and Usage statistics.

About

The terms of service, the privacy policy, the server address, and deleting the account.

The app is translated into English, Spanish, French, German, and Hebrew. Hebrew is laid out right to left. The theme follows the device, or is fixed to light or dark, and the map changes with it.

The settings screen in Hebrew, laid out from right to left
Figure 283. Settings in Hebrew
The settings screen in a desktop window, kept to a column in the middle and drawn with the operating system’s own controls
Figure 284. Settings in a desktop window

Usage statistics is the answer to the question asked after the first sign-in. Unlike the rest of the screen it’s kept on the device and not with the account, so each device has its own answer. While it’s off the app reports nothing. Deleting the account also resets the anonymous id the statistics carry.

The privacy and safety section of the settings, with the switch for usage statistics
Figure 285. The usage statistics switch

Three of these settings are stored and do little or nothing more in the sample:

  • The Offers switch is saved with the account, but the server sends no offers or promotions to switch off.

  • Share my trips and the emergency contact are saved with the account, and the screen says that no message is sent. Sharing a trip is the Share button during a ride.

  • Women only limits the offer to drivers whose profile says they’re women. The server doesn’t check the gender of the rider who asks.

Deleting the account removes the sign-in, the profile, the saved cards and any driving application, and the record the payment provider keeps of the rider. The app asks for the password again first, and the server refuses while a ride is under way or a card payment for one is still pending. The e-mail address of a deleted account can’t be registered again, because the rides that account took stay in the service’s records under it.

The recent destinations are kept on the device and belong to the account that chose them. When a different account signs in on the same device, the list starts empty, and so do home, work, the emergency contact and the ride options until that account’s own arrive from the server. The language, the theme and the units stay as the device had them.

A past ride shows who drove it and in which car. It doesn’t show where that driver is now.

49.7. In a browser

The server can host the app itself, so that opening the server’s address in a browser is using the app with nothing installed. It’s the same app compiled to JavaScript, with the same screens.

A browser gives a page less than a phone gives an app, and the app says so where it matters. Calling and messaging are offered only where the device can dial. The map opens on a default position when the browser won’t say where it is.

Section 50.1, “Running it” has the commands, and Section 35.1.16, “Hosting the app in the browser” explains how a server hosts an app.

50. Wayline: Building on the sample

Chapter 49, Wayline: A ride-hailing app from three sides shows Wayline from the outside. This chapter is for the developer who wants to build on it. It covers how to run the project, how it’s put together, what to change for two common kinds of service, and the parts a sample leaves for you to finish: taking real money, map data at production volume, native maps, sign-in through another identity provider, real text messages, push notifications, analytics, and the database it’s deployed on.

The Initializr’s ride-hailing template generates the project under your own name and package. Paths in this chapter are relative to the project’s root.

50.1. Running it

The project needs JDK 17 or newer and Maven, and nothing else installed. Start the server on the development profile:

CN1_PROFILE=dev backend/server.sh run

On that profile the database is in memory, verification codes are written to the log and shown in the app in place of a text message, cards are simulated, and the server creates the demo accounts listed in Chapter 49, Wayline: A ride-hailing app from three sides. It listens on port 8080.

Then run the app in the simulator, from another terminal in the same directory:

mvn verify -Psimulator -DskipTests -Dcodename1.platform=javase

Sign in as [email protected] with the password wayline-demo. Start a second simulator and sign in as [email protected] to follow a ride from both ends. A phone on the same network reaches the server through Server address on the welcome screen.

To use the app in a browser, have the server host it. The first command builds the browser version, which takes about a minute and is needed again only when the app changes:

backend/server.sh web
CN1_PROFILE=dev backend/server.sh run

Then open http://localhost:8080/. Section 35.1.16, “Hosting the app in the browser” describes what the server does with the staged files and how to deploy them.

backend/server.sh runs the server on the JVM for development. For a deployment it builds a native binary with one command:

backend/server.sh build --native
backend/server.sh run --native --prebuilt --port 8080

50.2. The modules

ModuleWhat it holds

shared

The contract: the records both sides exchange and the @RestClient interfaces that name every call. It’s plain Java 17 with no Codename One build step of its own.

common

The app: sign-in, the rider, driver and admin screens, the map, the wallet, the settings and the live channel. The styling is in src/main/css/theme.css and the translations in src/main/l10n.

backend

The server: accounts and roles, phone verification, driving applications, moderation, fares, matching, the ride state machine, payments, statistics, push notifications and the WebSocket. The entity classes are in the domain package, the queries in repository, the schema in src/main/resources/db/migration, and the settings in application.properties beside the module’s pom.xml.

There are no platform modules: common builds the app for the simulator, the desktop, Android, iOS and the browser.

50.3. The contract both sides share

Every call the app makes is a method of an interface in shared. This is part of RiderApi:

/// Asking for a ride and following it.
@RestClient
public interface RiderApi {
    @POST("/api/rides/quote")
    void quote(@Body RideRequestDto request, OnComplete<Response<FareQuoteDto>> callback);

    @POST("/api/rides")
    void request(@Body RideRequestDto request, OnComplete<Response<RideDto>> callback);

    /// The ride this rider has under way, or one whose state is NONE.
    @GET("/api/rides/active")
    void active(OnComplete<Response<RideDto>> callback);

    @GET("/api/rides/history")
    void history(OnComplete<Response<List<RideDto>>> callback);

    @GET("/api/rides/{id}")
    void ride(@Path("id") String id, OnComplete<Response<RideDto>> callback);

    @POST("/api/rides/{id}/cancel")
    void cancel(@Path("id") String id, OnComplete<Response<RideDto>> callback);

    @POST("/api/rides/{id}/rate")
    void rate(@Path("id") String id, @Body RatingDto rating, OnComplete<Response<RideDto>> callback);

    /// The free drivers around a point, for the cars on the map.
    @GET("/api/rides/nearby")
    void nearby(@Query("lat") double lat, @Query("lng") double lng,
            OnComplete<Response<List<NearbyDriverDto>>> callback);

    /// Tells the server which Live Activity this phone shows the ride in, so
    /// that it can keep it up to date while the app is in the background.
    @POST("/api/rides/{id}/activity")
    void activity(@Path("id") String id, @Body RideActivityDto activity,
            OnComplete<Response<RideActivityDto>> callback);
}

The data that travels is a record marked @Mapped. This is RideRequestDto:

/// Where a ride starts and ends, and how the rider wants it, for a quote and for
/// the request itself.
///
/// @param distanceMeters The length of the route the app drew, when it has one. The server prices
///     from this and [#durationSeconds()] only while they are plausible for the two points;
///     otherwise it prices from its own estimate.
/// @param durationSeconds How long the app's route takes, when it has one.
/// @param paymentMethodId A saved method's id, or `cash`. Empty means the rider's default method,
///     and cash when there is none.
/// @param product `standard`, `comfort` or `xl`; empty reads as standard.
/// @param driverGender `any` or `women`; empty reads as any.
/// @param quietRide Whether the rider would rather not talk.
/// @param accessibleVehicle Whether the car has to take a wheelchair.
/// @param petFriendly Whether a pet is coming: only drivers who take pets are offered the ride.
/// @param note A few words for the driver: which door, what to look for.
@Mapped
public record RideRequestDto(
        double pickupLat,
        double pickupLng,
        String pickupAddress,
        double dropoffLat,
        double dropoffLng,
        String dropoffAddress,
        double distanceMeters,
        double durationSeconds,
        String paymentMethodId,
        String product,
        String driverGender,
        boolean quietRide,
        boolean accessibleVehicle,
        boolean petFriendly,
        String note) {
}

Two builds read these files. The app’s build writes a client, RiderApiImpl, which the app reaches through Api.rider() in common. The server’s build writes an interface, RiderApiServer, whose methods take the same parameters without the callback and return the value, and a controller that routes each path to it. The server then implements that interface. This is the start of the class that does:

/// The server's half of `RiderApi`. Every method acts as the signed-in user and
/// on that user's rides only: the rider is never a parameter.
@Component
public class RiderEndpoint implements RiderApiServer {
    private final Rides rides;
    private final RidePushes pushes;

    public RiderEndpoint(Rides rides, RidePushes pushes) {
        this.rides = rides;
        this.pushes = pushes;
    }

    @Override
    public FareQuoteDto quote(RideRequestDto request) throws Exception {
        return rides.quote(request);
    }

    @Override
    public RideDto request(RideRequestDto request) throws Exception {
        return rides.request(Caller.name(), request);
    }

A method added to the contract and not implemented on the server is a compile error, and so is a component the app reads that the record no longer has. Chapter 35, Backend controllers, contracts and WebSockets covers the mechanism.

The caller is never a parameter. Caller.name() reads the signed-in user from the request’s security context, so an endpoint acts on the rides of whoever holds the token and can’t be asked to act on someone else’s.

The interfaces are AccountApi, RiderApi, DrivingApi for the application to drive, DriverApi, PaymentApi, GeoApi and AdminApi. Each has one endpoint class on the server that does nothing but call a service: Rides, Payments, Applications, Accounts and the rest. The services hold the rules.

50.4. How the server is put together

Under the endpoints the server has three layers, and a change usually touches one class in each.

LayerWhereWhat it does

Entities

The domain package

One class for each table, with private fields behind getters and setters: Ride, RideEvent, RidePassed, Profile, Preference, PhoneCode, DriverState, DriverApplication, DriverDocument, Payment, PaymentMethod, Payout, Pricing and the rest. They’re never sent to the app. The records in shared are what travels.

Repositories

The repository package: RideRepository, DriverStateRepository, ProfileRepository, PaymentRepository, DriverApplicationRepository and one for each other entity

The queries, and nothing else. Each is an interface, and the build writes its implementation.

Services

Rides, Matcher, Fares, Payments, Earnings, Applications, Accounts, Preferences, PhoneVerification, Statistics

The rules. Each is a @Component whose constructor takes the repositories it uses, and whose methods are @Transactional.

An entity gets no generated key: every id is text the server makes in Ids. It names neither its table nor its columns. They’re the names of the class and its fields in snake case, so Ride is stored in ride and pickupLat in pickup_lat, and a field whose type is an enum, such as state, holds the constant’s name. This is the start of Ride:

/// A ride, from the request to its end.
///
/// `rider` and `driver` are account names and not references: a ride outlives the
/// accounts that took it, and `driver` is empty until one is offered it.
@Entity
public class Ride {
    @Id(autoIncrement = false)
    @Column(nullable = false, type = "VARCHAR(32)")
    private String id = "";

    @Column(nullable = false, type = "VARCHAR(24)")
    private RideState state = RideState.REQUESTED;

    @Column(nullable = false, type = "VARCHAR(190)")
    private String rider = "";

    @Column(nullable = false, type = "VARCHAR(190)")
    private String driver = "";

The annotations are the ones Chapter 39, Backend data access and transactions describes. The entities don’t create the tables. The migrations do, as Section 50.23.2, “The schema” explains, so a field and its column are two edits that go together.

A repository is an interface marked @Repository that extends CrudRepository, which brings findById, insert and the other operations on one entity:

@Repository(entity = Ride.class, key = String.class)
public interface RideRepository extends CrudRepository<Ride, String> {
    /// The ride a rider has in one of `states`, or null.
    Ride findFirstByRiderAndStateIn(String rider, RideState[] states);

    /// The ride a driver has in one of `states`, or null.
    Ride findFirstByDriverAndStateIn(String driver, RideState[] states);

A query that its method’s name can say is derived from the name, as these two are. The rest carry a @Query over the entities, which names Java fields and not columns, as DriverStateRepository.freeInBox does to find the free drivers inside a bounding box. A query that changes rows is also marked @Modifying and answers how many it changed. Section 30.7, “Generated repositories” covers both kinds.

A service method that’s marked @Transactional runs in one transaction, and every repository it calls works inside it, as Section 39.4.8, “The transaction’s session” describes. A change made to an entity the transaction read is written when the method returns, with no call to save it: PhoneVerification.store sets the fields of the PhoneCode it read and returns. Methods that only read are marked @Transactional(readOnly = true), which PostgreSQL and MySQL enforce:

@Transactional(readOnly = true)
public RideDto activeForRider(String rider) throws IOException {
    Ride ride = rides.findFirstByRiderAndStateIn(rider, ACTIVE);
    return ride == null ? none() : toDto(ride, rider, new HashMap<String, Profile>());
}

Two rules shape the services, and both are about what a transaction must not contain:

  • A call that leaves the server isn’t made inside a transaction. Rides.complete is three steps: finish moves the ride to COMPLETED and commits, Payments.settle charges the card with no transaction open, and settled records the result in a second transaction. PhoneVerification.start stores the code, commits, and only then sends the text message. A charge can take seconds, and a transaction held across it would hold a database connection for as long.

  • The app is told of a change only once it’s committed. The public methods of Rides come in pairs for that reason: a private @Transactional method makes the change and returns a Change, and the public method that called it passes that to tell, which publishes it on the live channel. An app that’s told a ride changed asks for the ride at once, on another connection, and must find it changed.

A rider cancelling a ride is one such pair:

public RideDto cancelByRider(String rider, String id) throws IOException {
    Change change = attempt(() -> cancelAsRider(rider, id));
    // The driver it was offered to or who had taken it is told as well.
    return tell(change);
}

@Transactional
private Change cancelAsRider(String rider, String id) throws IOException {
    Ride before = owned(id, RIDER, rider);
    move(id, RideState.CANCELLED_BY_RIDER, rider, RIDER, null, null);
    return new Change(id, RideState.CANCELLED_BY_RIDER, rider, before.getDriver(), "",
            view(id, rider));
}

A private method can carry @Transactional here and be called through this. The build writes the transaction into the method itself, so there’s no proxy for the call to bypass. Chapter 39, Backend data access and transactions covers the rules.

The public method runs the transaction through attempt. Two transactions that change the same ride are meant to be settled by the update itself, as Section 50.6.1, “Two answers at the same moment” describes: the one that comes second changes no rows. MariaDB, as it’s configured out of the box, refuses that second update instead, because the ride it read has changed since, and ends its transaction. attempt runs the transaction again in that case, up to three times. The second run reads the ride as the first one left it, and its update changes no rows, which is the answer the other databases give.

50.5. Who may do what

The server is its own OAuth 2.0 authorization server. SecurityConfig registers one public client for the app, which signs in with the authorization-code flow and PKCE and holds no secret. Accounts, the registered client, tokens and signing keys are kept in the database by the tables the security layer creates. Section 41.12, “The authorization server” documents the pieces.

SecurityConfig declares two filter chains. The first covers the sign-in paths: /login, /oauth2/, /.well-known/, /userinfo and /logout. It keeps a session for the few requests a sign-in takes, answers the sign-in form with a status and JSON, and limits attempts for each client address.

The second chain covers /api/**, has no session, and requires a bearer token on every request. After the rate limits it declares, its rules are the whole of the access policy:

.authorizeHttpRequests(auth -> auth
        .requestMatchers(AntPathRequestMatcher.antMatcher("POST",
                "/api/account/register")).permitAll()
        .requestMatchers("/api/driver/**").hasRole(Roles.DRIVER)
        .requestMatchers("/api/admin/**").hasRole(Roles.ADMIN)
        .anyRequest().authenticated())

Three things about that chain are worth knowing before changing it:

  • The roles are RIDER, DRIVER and ADMIN, in Roles. A token says who the caller is and not what they may do. The chain reads the account’s roles from the database on every request, so a role an admin withdraws and a block an admin places take effect on the next request, not when the token expires. For that reason Accounts.setRoles answers 409 when asked to withdraw the driver role from a driver who is on a ride: without the role they couldn’t finish or cancel it. The admin cancels the ride first, or waits.

  • The application to drive is under /api/driving, not /api/driver, on purpose: someone who isn’t a driver yet has to reach it.

  • The app hides the screens a role can’t use. That’s a courtesy. The chain is what refuses the request.

The same sign-in works from a browser with one difference. An installed app receives the authorization code on a loopback address. A page can’t, so the server registers a second redirect address on its own origin, /signin/code, which SignInCodePage answers with the code as JSON. Because a browser sends a session cookie on its own, the sign-in chain refuses a request that changes something and names another site in its Origin header. Section 35.1.16, “Hosting the app in the browser” explains the reasoning.

50.6. A ride from request to receipt

A ride is a Ride entity, a row in ride, with a state. The states are the RideState enum in shared, so the app and the server name them the same way, and RideStateMachine on the server lists the moves that are allowed:

StateHow a ride gets there

REQUESTED

A rider asked for it, or the driver it was offered to declined or didn’t answer.

OFFERED

The server offered it to a driver.

ACCEPTED, ARRIVED, IN_PROGRESS, COMPLETED

The driver accepted, reached the pickup, started the trip and finished it.

CANCELLED_BY_RIDER

The rider cancelled before the trip started.

CANCELLED_BY_DRIVER

The driver cancelled after accepting and before the trip started.

CANCELLED_BY_ADMIN

An admin cancelled a ride that hadn’t finished.

NO_DRIVERS

Nobody took the ride within the time allowed.

50.6.1. Two answers at the same moment

Two drivers can’t both accept a ride, a rider can’t cancel a ride in the instant a driver accepts it, and an offer can’t be accepted while the server is taking it back. None of it takes a lock. Every change of state is one conditional update in RideRepository, and the number of rows it changed is the whole answer.

Rides.tryMove asks RideStateMachine.sources which states the new one may be reached from, and passes them to the statement for that kind of move: the rider’s, the driver’s, a driver taking an offer, a driver giving one back, an offer being made, or a move the server makes itself:

private boolean tryMove(String id, RideState to, String actor, String ownerField,
        String newDriver, Instant newOfferExpiresAt) throws IOException {
    RideState[] sources = RideStateMachine.sources(to);
    if (sources.length == 0) {
        return false;
    }
    Instant now = Instant.now();
    int moved;
    if (newOfferExpiresAt != null) {
        moved = rides.offer(id, sources, to, now, newDriver, newOfferExpiresAt);
    } else if (RIDER.equals(ownerField)) {
        moved = rides.moveAsRider(id, sources, to, now, actor);
    } else if (!DRIVER.equals(ownerField)) {
        moved = rides.moveByServer(id, sources, to, now);
    } else if (newDriver != null) {
        moved = rides.giveBack(id, sources, to, now, actor, newDriver);
    } else if (RideState.ACCEPTED == to) {
        // An offer that has lapsed cannot be taken, even in the moment
        // before the sweep takes it back.
        moved = rides.takeOffer(id, sources, to, now, actor);
    } else {
        moved = rides.moveAsDriver(id, sources, to, now, actor);
    }
    if (moved != 1) {
        return false;
    }
    event(id, to, actor);
    return true;
}

Each kind is a fixed statement of its own in the repository. This is the one for a driver accepting an offer:

/// Takes an offer made to `driver`: refused once the offer has lapsed, as
/// of `now`, even in the moment before the sweep takes it back.
@Modifying(clearAutomatically = true)
@Query("update Ride r set r.state = :to, r.updatedAt = :now "
        + "where r.id = :id and r.state in :from and r.driver = :driver "
        + "and r.offerExpiresAt >= :now")
int takeOffer(@Param("id") String id, @Param("from") RideState[] from,
        @Param("to") RideState to, @Param("now") Instant now, @Param("driver") String driver);

It names the states the move may start from, the driver the ride was offered to, and the time the offer lapses. It answers 1 for the request that made the move and 0 for every other, because by the time the database runs the second statement the row is no longer in a state the statement names. tryMove records a RideEvent only for the 1, in the same transaction, and Rides.move turns a 0 into a 409 that says where the ride is now.

The service never reads the state and then writes it. Reading first and writing second would let two transactions both read OFFERED and both write ACCEPTED. One statement can’t be interleaved that way on any of the three engines, and nothing is held in the server’s memory, so the rule holds with several server processes on one database.

RideRaceTest is the test that would notice the difference. It calls Rides.accept for one offer from eight threads released together, and requires that exactly one call returns the ride as ACCEPTED, that the other seven are answered 409, and that the ride’s history holds one ACCEPTED event. Two more tests run the acceptances against Rides.tick while it takes back an offer that has lapsed, and require that nobody gets the ride.

Three other places use the same pattern. RideRepository.rate gives a ride its stars only where it has none, so a ride rated twice is rated once. PhoneCodeRepository.takeGuess has the database add one to the count of wrong codes only while the count is under the limit, so of any number of guesses sent together only as many as are left are looked at. RideRepository.claimTip and claimRefund claim a tip and a refund the same way before the payment provider is asked for anything, so of two requests only one charges or refunds. Both claims update the ride’s row, so a refund that arrives while a tip is still being charged sees the tip and answers 409 until the charge has been recorded or given up. A server that stops after claiming a refund leaves the ride marked refunded with no refund recorded. The next request for that ride finds the payment row unchanged and asks the provider again. That’s safe because a refund carries a key made from the charge it returns, so the provider answers a repeat with the refund it made. The same rule lets a second refund through while the first is still at the provider. Whichever of the two fails gives its claim back only while the payment row is still unrefunded, and whichever succeeds writes the ride’s status along with the payment’s. Both write the ride’s row first, so they take turns, and the ride ends up agreeing with its payment in either order. A refunded fare can’t come back as earnings for the driver to cash out.

Accounts.setRoles and Accounts.suspend hold two rows: the profile of the admin who asks and the profile of the account being changed, in the order of their names. The admin’s own role is then read again inside the transaction. Without that, two admins could remove or block each other in the same moment and leave the service with nobody to administer it. Neither blocks an account in the middle of a ride, nor withdraws the driver role from one: every request a blocked account sends is refused, so nobody could end that ride. The admin cancels the ride first, or waits for it to end. A driver taking an offer holds the driver’s profile too and then checks that the account is still allowed, so a block and an accepted offer can’t both land. A live connection that was opening while the change committed reads the account again once it’s registered, so it can’t keep what it read before.

A conditional update settles a race over one row. Two races here are over a row that doesn’t exist yet: a rider asking for two rides at once, and two rides choosing the same free driver. Each transaction reads, finds nothing in its way, and inserts or updates a row of its own. Rides.open and Rides.offer therefore start by writing the rider’s profile row, or the driver’s state row, to the value it already has (ProfileRepository.hold, DriverStateRepository.hold). The database keeps a written row for its writer until the transaction commits, so the second transaction waits there and then reads what the first one left. That write must come first in the transaction: a transaction that reads first may go on seeing the database as it was at that read. That’s why choosing a driver and offering them the ride are two transactions.

The same hold serializes everything else that reads an account and then writes for it. Closing an account, removing a card and choosing the default card hold the profile, so each takes turns with a ride being asked for. Sending a phone code holds it too, so two requests can’t both pass the wait between codes. Changing a password holds it before the old password is checked, so of two changes made together the second is checked against the password the first one set. Approving a driving application holds the applicant’s profile, the row blocking the account holds as well: granting the role rewrites the whole sign-in row, and an approval that read the account before a block would otherwise write it back unblocked. A driver’s position report holds the driver’s state row, so two reports sent together don’t count the same online minutes twice. Cashing out holds the driver’s payout account, so two requests sent together pay the balance once and the second is told there’s nothing left. Saving the payout details holds the driver’s profile, because the first save has no payout row to hold yet. Saving a driving application or uploading one of its documents holds the application, so neither can land on one that was handed in a moment earlier.

Changing a password ends the account’s other sign-ins. A refresh token asks for no password, so account.Grants removes every grant in the authorization server’s table except the one the request came with, and closing an account removes them all. An access token already issued isn’t recalled: it’s checked by its signature and runs out on its own.

A ride’s two parties see each other’s display name, and each other’s phone number while they’re meeting. The e-mail address an account signs in with is its username, and Rides.toDto gives it only to its owner and to an admin. A fare counts toward a driver’s balance once the ride is paid for, in cash or by a card whose charge came back, and a tip paid by card once its charge is recorded. A charge that failed, was refunded or is still pending isn’t money the driver can cash out, and a refund takes the tip back with the fare. The earnings screen’s totals for the day, week and month count the same money as the balance, so a refunded or unpaid ride counts as a trip and earns nothing.

A statement that changes rows in bulk leaves the session unchanged, so an entity read before it keeps the values it had. Every move of a ride is marked @Modifying(clearAutomatically = true), which empties the session after the statement, so a Ride read before a move is read again after it. The services do that wherever they go on to describe the ride.

50.6.2. Fares, matching and the sweep

Rides.request fixes the fare when the ride is created, from the server’s own prices in Fares. The distance the app sends is believed only while it’s plausible for the two points. The driver’s share is fixed at the same moment.

Matcher picks the driver. It selects drivers who are online, reported a position in the last minute, are approved, aren’t blocked, have no ride in hand, drive the kind of car asked for and meet the ride’s options. It takes the nearest one who hasn’t already passed on this ride. The search covers 3 km for the first twenty seconds and 8 km after that.

Rides.tick runs every two seconds as a scheduled job. It takes back offers whose time ran out and searches again for every ride still waiting. Each ride is dealt with in a transaction of its own, so one ride that fails doesn’t cost the others their turn. The job carries a lock name, so with several server processes only one runs it at a time. Chapter 42, Backend scheduling and background work covers scheduled jobs.

When a driver completes a ride, Payments.settle charges it.

50.7. Live updates

LiveEndpoint is a WebSocket at /ws/live. The server pushes a short JSON frame when a ride changes state, when the driver of a ride moves, and, to admins, when any car online moves. LiveChannel in the app receives them.

A WebSocket request from a browser can’t carry a bearer token in a header. The app therefore first asks POST /api/live/ticket, which is a normal call that carries the bearer token, for a ticket: a random value that works once, for thirty seconds. It then opens the socket with the ticket in the address. The server stores only a hash of each ticket.

A phone whose app isn’t open hears of the same changes through push notifications, which Section 50.15, “Push notifications” covers.

The screens don’t depend on the socket. Each also asks the server for the current state every few seconds, so a dropped connection delays an update and doesn’t lose it.

LiveHub keeps the open connections in the memory of one process. With several server processes, a change made on one isn’t pushed to the sockets held by another, and those clients catch up on their next poll. Pushing across processes needs a channel between them, such as PostgreSQL’s LISTEN and NOTIFY or a message broker. The sample has none.

50.8. The app

Wayline is the app’s main class. It applies the look and the language, starts the session and hands over to Nav.

ClassWhat it does

Nav

Chooses the first screen from the roles /api/me returns: AdminForm, DriverForm, ApplyForm for someone who has applied to drive, or RiderForm. It remembers the mode a user with several roles was last in.

net.Session

Signs in and out and keeps the tokens in secure storage. net.Api holds the generated clients, and net.Net adapts their callbacks.

AppConfig

The server’s address. It’s the page’s own origin in a browser, the address saved from the welcome screen otherwise, and http://localhost:8080 when neither is there.

map.MapStage

A map filling the screen with the app’s controls floating over it: a bar at the top, a chip for one short fact, round buttons and a bottom sheet. The rider’s, the driver’s and the live-map screens are all built on it.

map.Maps

Creates the map and draws what goes on it: the pins, the car and the route.

notify.Notifications

Registers for push notifications and tells the server which phone the signed-in user is on. See Section 50.15, “Push notifications”.

rider.RideCard

The ride on the lock screen while a driver is on the way. See Section 50.16, “The ride on the lock screen”.

driver.Shift

Keeps an online driver’s position going to the server with the app in the background. See Section 50.17, “Driving in the background”.

ui.Look, ui.Lang, ui.Layouts

The theme, the language and the layout for the width of the window.

admin.Console

The admin screens side by side, for a wide window.

The colors and the corner radius are CSS variables in the first block of theme.css, each with a dark twin, and every style in the file is written in terms of them. The style names all start with Wl.

The text on every screen is English in the source, and the English text is the key of the translation. src/main/l10n holds one Bundle_<code>.properties for each language.

Layouts.wide() is true in a window at least 165 mm wide. AdminForm shows the phone console below that width and Console above it, and switches when a window is resized across it. Screens that have no wide layout are kept to a column 150 mm wide. On the desktop the nativeTheme=native build hint gives the app the operating system’s own look.

50.9. Tests

mvn -pl shared,backend -Dcodename1.platform=backend test   (1)
mvn -pl shared,backend -Dcodename1.platform=backend test -Dcn1.backend.compiledTests=true   (2)
1The server’s tests on the JVM. They cover access by role, accounts, driving applications, matching, the ride state machine, a whole ride, payments against the simulated provider and against stand-in answers for Stripe, pricing, statistics, moderation, the live socket, the push notifications each step of a ride sends and the browser sign-in.
2The same tests again with the server compiled to a native binary, which is how it ships.

Chapter 38, Backend testing covers the server test support.

50.10. Your project’s names

The Initializr generates the project under the name and package you choose:

  • The Java package becomes yours.

  • wayline in artifact ids and configuration keys becomes your project’s name in lower case. wayline.fare.baseCents is myapp.fare.baseCents in a project called MyApp.

  • WAYLINE in environment variable names becomes the name in upper case.

  • The main class takes the project’s name.

This chapter uses the name Wayline. In your project read wayline as your own.

50.11. Making it yours: A ride-sharing service

Most of a ride-sharing product is already here. What changes is the identity, the prices and the rules.

50.11.1. Name, icon and colors

The name and the package are chosen in the Initializr. After that they’re in common/codenameone_settings.properties, as codename1.displayName and codename1.packageName, and the icon is common/icon.png. Text that names the service on screen, such as the title of the welcome screen, is ordinary translated text: search the bundles in src/main/l10n for it.

The colors are the variables at the top of theme.css. Changing the brand color and its dark twin recolors every button, link and selection:

#Constants {
    --brand: #0f766e;
    --brand-pressed: #115e59;
    --brand-contrast: #ffffff;
    --brand-dark: #5eead4;
    --brand-pressed-dark: #2dd4bf;
    --brand-contrast-dark: #042f2e;
    --radius: 1.5mm;
}

The map’s pins, car and route take their colors from the WlMarkerPickup, WlMarkerDropoff, WlMarkerCar and WlRoute styles in the same file.

50.11.2. Products and prices

The prices start as settings and are the ones in force until an admin saves the pricing screen, which writes them to the database. To start a deployment with your own, set them in backend/application.properties. The amounts are in the currency’s smallest unit:

wayline.currency=EUR
wayline.fare.baseCents=350
wayline.fare.perKmCents=180
wayline.fare.perMinuteCents=40
wayline.fare.minimumCents=700
wayline.fare.serviceFeePercent=0
wayline.fare.commissionPercent=0

The currency is a setting only. Rides already taken are recorded in it, and changing it doesn’t convert them.

A fare is the base fare plus the distance and time charges, multiplied for the kind of ride and for surge, and never less than the minimum. The service fee is a percentage added on top for the rider. The commission is a percentage of the fare kept from the driver. Fares.price is the arithmetic, and it’s the place for a different pricing model, such as fixed prices between zones or a price for each stop.

Surge is one multiplier an admin sets by hand. Nothing raises it when demand is high.

The three kinds of ride are named in several places, and adding or removing one touches each:

  • Fares.PRODUCTS, and the multiplier for each in Fares.price.

  • Rides.PRODUCT_TEXT, the name, description and seats the rider is shown.

  • The comfort and xl fields of the Pricing entity and their columns in pricing, PricingDto and PricingForm, if the new kind has a multiplier an admin can set.

  • The picker in ApplicationForm, where a driver says which kind their car is, and Ui.product.

  • The icon chosen in RiderForm.

50.11.3. Matching rules

How long a driver has to answer and how long the search goes on are settings:

wayline.offer.seconds=30
wayline.search.seconds=300

The search distances and the minute after which a silent driver counts as gone are constants at the top of Matcher. The rule itself is in three places: the query in DriverStateRepository.freeInBox, which finds the free, approved drivers inside a box, Matcher.nearby, which keeps those within the radius who fit the ride and orders them by distance, and Matcher.pick, which takes the nearest who hasn’t passed on the ride. A different rule, such as the driver who has waited longest or the best rated within reach, replaces the ordering there. Nothing else in the server knows how a driver was chosen.

DriverStateRepository.freeInBox compares latitudes and longitudes in a bounding box. That’s right for one city on any of the three databases. A service with tens of thousands of drivers online would move that query to a spatial index.

50.11.4. What a driver has to provide

The five documents are the KINDS array in Applications on the server and the list of cards in ApplicationForm in the app. Add a kind to both, such as a vehicle inspection or a background check, and the review screen shows it. The fields of the form are fields of the DriverApplication entity, columns of driver_application and components of DriverApplicationDto. Section 50.23.3, “Changing the schema later” walks through adding one.

The server checks that an uploaded file is a JPEG or a PNG and under 1.5 MB. It doesn’t read the documents. Whether a license is real is the admin’s judgment, or a verification service you call from Applications.submit.

50.11.5. Text messages

A development server prints verification codes on its console. Any other server sends them through Twilio, Vonage or MessageBird, and needs an account with one of them. The settings, the limits and how to add another provider are in Section 50.14, “Text messages”.

50.11.6. Languages

To add a language, add Bundle_<code>.properties to src/main/l10n, add the code to Lang.CODES in the app, and add it to the LANGUAGES array in Preferences on the server, which refuses a language it doesn’t know. A language written right to left sets the @rtl key in its bundle, as the Hebrew one does.

50.11.7. Before it’s a product

These are things the sample doesn’t have, and a ride-sharing product needs:

  • Real payments, payouts to drivers, and tax. See Section 50.13, “Billing”.

  • An account with a text-message provider. See Section 50.14, “Text messages”.

  • A keyed digest for phone codes. PhoneVerification stores a plain SHA-256 of the account and the code. Somebody who can read the phone_code table can try all million codes within the five minutes a code lasts. Use an HMAC under a server secret that isn’t kept in the database.

  • Sturdier push cleanup. A sign-out that can’t reach the server leaves the phone registered to that account until somebody signs in on it again. A rider who signs out during a ride keeps its Live Activity until the system removes it. One Live Activity is kept per ride, so a rider following a ride on two devices sees the second one updated, and the first one not.

  • Position reports while the driver’s app is in the background.

  • A cancellation fee, scheduled rides, shared rides and promotions.

  • A check that the rider asking for a woman driver is one. Matcher filters the drivers by the gender in their profile and doesn’t look at the rider’s.

  • Statistics by local time. The dashboard’s day and its busy hours are in UTC.

  • TLS. The Android build allows clear-text traffic so that a phone can reach a development server. Remove android.xapplication_attr from codenameone_settings.properties once the server has a certificate.

50.12. Making it yours: A dispatch service for a taxi station

A station with twelve cars and a dispatcher is a smaller service with different rules. The drivers are known, bookings arrive by phone as well as from the app, a person decides who takes which ride, and most rides are paid in cash or put on a company’s account. The sample covers the riders' app, the drivers' app, the fares, the receipts and the console. The rest is described here, with the class each change belongs in.

50.12.1. A fixed fleet

Nobody applies to drive. An admin makes an account a driver directly: the Driver switch on an account in People calls Accounts.setRoles, which gives the role and records an approved application for it. A driver made this way is of the standard kind and has no car details. To record each car, fill in the application’s vehicle fields from an admin screen of your own.

To close the open door:

  • Remove Drive with Wayline from the rider’s menu in RiderForm, the Drive choice from RegisterForm, and ApplyForm from Nav.

  • Decide whether the public may register. If only staff create accounts, take Create an account off WelcomeForm and require the admin role for the registration path, as A dispatcher shows.

50.12.2. A dispatcher

A dispatcher needs more than a driver and less than an admin, which is a fourth role. Add it to Roles, to the role switches in Accounts.setRoles and UsersForm, and give its paths a rule of their own in the API chain that Section 50.5, “Who may do what” shows. Above the rule for /api/driver/, add one that admits the dispatcher and the admin to the dispatcher’s paths: .requestMatchers("/api/dispatch/").hasAnyRole(Roles.DISPATCHER, Roles.ADMIN). If only staff create accounts, the rule for registration changes too, from permitAll() to hasRole(Roles.ADMIN).

Then declare the dispatcher’s calls in a new @RestClient interface in shared, such as DispatchApi, and implement the interface the server’s build generates from it.

50.12.3. Assigning a ride by hand

Automatic matching is two calls to Rides.search: one at the end of Rides.request and one for each waiting ride in Rides.tick. Remove both and a requested ride waits in REQUESTED until somebody assigns it. Keep the part of tick that takes back unanswered offers.

Assigning is the same move the matcher makes, with the driver chosen by a person. This is the transaction in Rides that makes it for the matcher:

/// Offers a ride to the driver chosen for it, unless they were given
/// another in the meantime. Returns what it changed, or null for nothing,
/// in which case [#tick] looks again.
///
/// The driver is held before anything is read, so two rides that chose
/// the same driver come through here one after the other, and the second
/// reads the offer the first one committed. The update of the ride cannot
/// do this on its own: it is conditional on its own ride's row, and each
/// of the two has a row of its own.
///
/// Everything that made the driver the choice is asked again once they
/// are held: a driver who went off line, drove out of reach, lost their
/// approval or was blocked since [#choose] read them would otherwise get
/// the offer and keep the rider waiting for it to lapse. Not private, so
/// that a test can make the offer to a driver who changed in between.
@Transactional
Change offer(String id, String driver) throws IOException {
    if (drivers.hold(driver) == 0
            || rides.findFirstByDriverAndStateIn(driver, WITH_DRIVER) != null) {
        return null;
    }
    Ride ride = find(id);
    if (ride == null || RideState.REQUESTED != ride.getState()) {
        return null;
    }
    Instant now = Instant.now();
    if (!matcher.fits(ride, driver,
            now.toEpochMilli() - ride.getRequestedAt().toEpochMilli())) {
        return null;
    }
    return tryMove(id, RideState.OFFERED, "", null, driver, now.plusMillis(offerMillis))
            ? new Change(id, RideState.OFFERED, ride.getRider(), driver, "", null) : null;
}

An assign method for the dispatcher is a pair, the way the other moves are. Its private @Transactional half does what offer does with the driver the dispatcher picked, holding the driver first and calling tryMove with RideState.OFFERED, the driver and the time the offer lapses. Where offer answers null, assign answers 409, so a dispatcher who picked a busy driver, or a ride that somebody else assigned first or that the rider cancelled, is told. The public half runs it through attempt and passes the Change it returns to tell, as cancelByRider does. tryMove records the event in the ride’s history, and tell has the driver’s screen show the offer at once. The driver’s app needs no change: an offer is an offer whoever made it.

Two settings matter once a person does the matching. wayline.search.seconds is how long a ride may wait before it becomes NO_DRIVERS, and ninety seconds is too short for a dispatcher on the phone. wayline.offer.seconds is how long the driver has to answer.

The dispatcher’s screen is a list of waiting rides beside the live map. Both exist: AdminRidesForm lists rides, FleetForm shows the cars, and Console shows how a list and a detail sit side by side in a wide window.

50.12.4. Bookings taken by phone

Rides.request takes the rider’s account name as its first parameter, and the rider’s endpoint passes the caller. A dispatcher’s endpoint passes the customer instead, so a booking entered by staff is the same ride with the same fare rules. Two checks in that method are written for riders booking for themselves and need a decision:

  • The rider’s phone number must be verified. A customer the dispatcher is speaking to has shown they hold the number, so staff-created accounts can be marked verified.

  • A rider may have one ride under way. That’s right for a customer account and wrong for one shared account that stands for everyone who phones in. Give each caller an account keyed by their phone number, or lift the check for bookings made by staff.

The pickup and the destination come from the same place search the rider’s app uses, GeoApi, so the booking form can reuse PlaceSearchForm.

50.12.5. Cash and accounts

Cash is already a payment method. It’s the default for an account with no saved card, the driver’s screen says how much to collect, and the ride is recorded as paid. A station that takes no cards removes Add a card from WalletForm and never configures a payment provider.

Riding on account, where a company is invoiced at the end of the month, is a method the sample doesn’t have. Cash shows the pattern: Payments.CASH is a method id that Payments.settle records as paid without asking the provider. An account method does the same and records which customer to invoice, which needs a table for the customers and a column on the ride. They go in a new migration, numbered after the last one the project has, with an entity for the table and a field on Ride for the column, as Section 50.23.3, “Changing the schema later” describes:

-- Companies that ride on account and are invoiced at the end of the month.
CREATE TABLE account_customer (
    id VARCHAR(40) NOT NULL PRIMARY KEY,
    name VARCHAR(120) NOT NULL,
    billing_email VARCHAR(190) NOT NULL,
    active SMALLINT NOT NULL,
    created_at BIGINT NOT NULL
);
ALTER TABLE ride ADD COLUMN account_customer VARCHAR(40) NOT NULL DEFAULT '';

Producing the invoice from those rows is yours to write.

Earnings needs a decision too. It credits a driver with the fare less commission for every completed ride, cash rides included, as if the service had collected the money. For drivers who keep the cash they collect, subtract cash fares from the balance, or the ledger says the station owes money it never held. For drivers on a wage, remove EarningsForm from the driver’s menu.

50.12.6. What to switch off

FeatureWhere

The service fee and commission

Set both percentages to zero, in the settings or on the pricing screen.

The larger kinds of ride

Leave one entry in Fares.PRODUCTS and Rides.PRODUCT_TEXT.

Surge

Leave the multiplier at 1, and remove its field from PricingForm.

Tips through the app

Remove the tip row from the end-of-ride sheet in RiderForm and from ReceiptForm.

Driving applications

Remove ApplyForm, ApplicationForm and the Applications section of the console. DrivingEndpoint can stay unused or go with them.

Ratings

Remove the stars from the end-of-ride sheet in RiderForm.

50.13. Billing

50.13.1. What the sample does

Every payment goes through one interface on the server, PaymentProvider:

public interface PaymentProvider {
    /// `simulated` or `stripe`: what the app is told, so it knows how to add a
    /// card.
    String name();

    /// Opens the processor's record of a rider and returns its reference.
    String createCustomer(String username, String displayName) throws IOException;

    /// Deletes the processor's record of a rider, and the cards saved to it
    /// with it. A record that is already gone is deleted: this is asked again
    /// when the first answer was lost.
    void forgetCustomer(String customer) throws IOException;

    /// Begins saving a card to `customer`. `setupId` is the server's own id
    /// for the attempt, for the processor to hand back.
    Setup startCardSetup(String customer, String setupId) throws IOException;

    /// Finishes a setup and returns the card it saved.
    ///
    /// @param reference what [#startCardSetup] returned as the setup's reference
    /// @param typed the card as typed into the app, for a processor whose setup
    ///     is not hosted; ignored by one whose setup is
    /// - `PaymentDeclinedException`: when the card was refused or the setup was
    ///   not finished
    Card finishCardSetup(String customer, String reference, CardDto typed) throws IOException;

    /// Takes a saved card off `customer`, so that it can't be charged again.
    /// A card that is already off, or gone, is detached: this is asked again
    /// when the first answer was lost.
    ///
    /// @param token what [#finishCardSetup] returned as the card's token
    void detachCard(String customer, String token) throws IOException;

    /// Charges a saved card with its owner absent.
    ///
    /// @param key names this charge and no other. A processor asked twice with
    ///     the same key charges once, so a request repeated after a timeout
    ///     cannot take the money twice.
    /// @return the processor's reference for the charge
    /// - `PaymentDeclinedException`: when the card was refused
    /// - `IOException`: when the processor could not be asked
    String charge(String key, String customer, String token, long amountCents, String currency,
            String description) throws IOException;

    /// Returns `amountCents` of a charge to the card it came from.
    ///
    /// A processor may take the refund and only later say whether the bank
    /// returned the money: such a refund comes back [Refund#pending], and is
    /// asked about with [#refundStatus] until it has an answer.
    ///
    /// @return the refund as the processor took it
    /// - `IOException`: when the processor could not be asked, or refused the
    ///   refund outright
    Refund refund(String chargeReference, long amountCents) throws IOException;

    /// What became of a refund that was [Refund#pending]: [#REFUND_SUCCEEDED],
    /// [#REFUND_PENDING] while the processor still does not know, or
    /// [#REFUND_FAILED] when the money did not go back.
    String refundStatus(String refundReference) throws IOException;

The shape is the one card processors share. A rider is a customer of the processor. A card is saved to that customer once and comes back as a token. From then on the server charges the token with nobody present, which is what lets a ride be paid for as it ends. The server stores the token, the brand and the last four digits.

Payments is the service that uses the interface. It keeps the saved methods, charges the fare and the service fee when a ride completes, charges a tip once, refunds, and builds receipts. Every charge carries a key made from the ride’s id, so a request repeated after a timeout can’t charge twice.

A ride completes in one transaction and its payment is written in another, with the charge between them. A server that stops between the two leaves a completed ride whose payment is still pending. Rides.settleLeftBehind runs every minute, finds such rides once they’re two minutes old, and settles them. Because the charge is keyed by the ride, a card that was already charged isn’t charged again.

A charge can also fail without saying whether the card was charged: the provider wasn’t reached, or its answer was lost. Only a PaymentDeclinedException is recorded as a failed payment. Any other failure leaves the ride pending, and the same pass asks again every minute for 23 hours, which is inside the day a provider keeps a charge’s key. After that the ride stays pending for a person to look up. A tip works the same way: a declined card takes the tip off the ride, and any other failure leaves it there with no charge recorded, so the rider can send the same tip again under the same key. The ride can’t be refunded until then.

A refund can also be taken without being finished. Stripe answers some refunds pending and only later says whether the bank returned the money, and a pending refund can still end failed or canceled. PaymentProvider.refund reports such a refund as pending, and the payment and its ride are then REFUND_PENDING, not REFUNDED: the receipt says the refund is pending, and the ride can’t be refunded again. Payments.settleRefunds runs every minute and asks the provider about each one through PaymentProvider.refundStatus. Once the fare’s refund and the tip’s have both succeeded the ride is REFUNDED. If either fails, the ride is REFUND_FAILED and isn’t tried again: part of the money may have gone back, so it takes a person with the provider’s records to settle it. A ride in either state earns its driver nothing.

While a ride’s charge is being asked about, the card it was sent to can’t be removed and the account can’t be closed: Payments.remove and Payments.forget answer 409. The retry looks the card up by its token, so with the card gone it couldn’t ask.

Closing an account also deletes the rider’s record at the provider, through PaymentProvider.forgetCustomer, in the same transaction that deletes the rest. A provider that can’t be reached fails the closure and leaves the account as it was. A record that’s already gone counts as deleted, so closing again finishes a closure that was interrupted.

Removing a card works the same way for that one card. Payments.remove asks PaymentProvider.detachCard to take the card off the rider’s record before it deletes the row, in the same transaction. A provider that can’t be reached leaves the card saved, and a card that’s already detached counts as detached.

Each card setup is a session made at the provider. An account can have five open at once, and a sixth is refused with 429 until one is finished or an hour has passed. Payments.sweepSetups runs every ten minutes and deletes the finished setups and the ones abandoned more than two hours ago.

The limit of eight cards is checked again when a setup finishes, because several setups can start while there’s room for one. By then the provider has already attached the card, so when the limit refuses it, Payments detaches it with PaymentProvider.detachCard after the refused transaction has rolled back. If that detach fails, the server logs the card’s token and still answers 409.

Two implementations come with the sample, and the setting wayline.payments.provider chooses between them:

  • simulated is SimulatedPayments. It accepts any card number that passes the usual checksum, and treats the test numbers listed in Chapter 49, Wayline: A ride-hailing app from three sides specially. The card is typed into the app. No money moves.

  • stripe is StripePayments, a starting point over Stripe’s REST API that hasn’t been run against a Stripe account. Turning on Stripe says what it does and what to check.

Without the setting, a development profile (dev, test or local) gets simulated and any other profile gets stripe. A provider that can’t be set up isn’t replaced with anything. With stripe chosen and its key missing, or with a name that’s neither, the server starts, logs a configuration error that names what to set, and logs it again on every payment call, each of which fails. The rider is told payments are unavailable, and no ride is charged to a card nobody can reach. A production server never falls back to simulated cards.

50.13.2. Turning on Stripe

Choose Stripe, set the key in the server’s environment, not in a file in the repository, and tell the server the address it’s reached at:

wayline.payments.provider=stripe
wayline.payments.stripe.secret=${WAYLINE_PAYMENTS_STRIPE_SECRET}
wayline.public.url=https://rides.example.com

The first line is what a production profile chooses anyway, and a development profile needs it to use Stripe at all. The second reads the key from the environment variable WAYLINE_PAYMENTS_STRIPE_SECRET. The server reads that variable for this setting without the line as well, since every setting is read from the environment under its name in upper case with an underscore for each dot. The third line is the address Stripe sends the browser back to. It’s needed only when that address differs from the issuer, which the server uses otherwise. With the key or both addresses missing, every payment call fails with the configuration error described above.

StripePayments calls Stripe’s REST API directly and uses no SDK:

  • Adding a card creates a Checkout Session in setup mode. The app opens the session’s page in the device’s browser, so the card number is typed into Stripe’s page and never reaches the app or your server.

  • Stripe sends the browser back to /pay/return on your server, a plain page from PayReturnPage that tells the user to return to the app. When the app comes back to the foreground, it asks the server to finish the setup, and the server reads the saved card from the session.

  • A ride is charged with a PaymentIntent that’s confirmed at once and marked off-session, with the ride’s key as the idempotency key.

  • A refund is a Stripe refund of that PaymentIntent. One that Stripe answers pending or requires_action is read again with GET /v1/refunds/{id} until it succeeds, fails or is canceled.

  • Removing a card detaches its PaymentMethod with POST /v1/payment_methods/{id}/detach. If Stripe refuses, the server reads the PaymentMethod, and one that’s no longer attached to the rider counts as detached.

The tests cover this path with stand-in answers in place of Stripe’s. Nothing in the project has run against a Stripe account. Use a test-mode key and Stripe’s test cards, and follow one card from adding it to a charge, a tip and a refund, before a live key goes near it.

50.13.3. What’s left to do

The sample stops well short of a billing system. In rough order of need:

Webhooks

The server learns the result of a charge from the response to its own request and listens for nothing. A dispute, a refund made in Stripe’s dashboard, or a payment that settles later is never seen. Add a controller for Stripe’s events, verify each event’s signature, and update payment from it.

Cards that need the owner’s approval

A bank may require authentication for an off-session charge. StripePayments treats that answer as a decline. A product brings the rider back into the app to approve the payment, and tries again.

Failed payments

When the charge at the end of a ride fails, the ride is marked as failed to pay and the failure is logged. Nothing retries it, asks for another card, or stops that rider from asking for the next ride. Decide the policy and put it in Payments.settle and Rides.request.

Holding the fare first

The sample charges once, at the end. Placing a hold on the card when the ride is requested, and capturing it at the end, catches a card with no funds before the driver has driven.

Paying drivers

Earnings and payouts are a ledger. Cash out writes a row that says the balance was paid, and no money leaves. Paying drivers needs a product built for it, such as Stripe Connect, where each driver is a connected account that passes the processor’s identity checks and receives transfers. The alternative is a payment file for your bank produced from payout. The bank details the sample stores are a holder’s name, a bank’s name and four digits, which is enough to show on a screen and not enough to pay anyone.

Tax and invoices

A receipt lists the fare’s parts and the total. There’s no tax line, no invoice number and no document to download. What a receipt must show depends on where you operate.

50.13.4. Another payment provider

A second processor is a second class that implements PaymentProvider. StripePayments shows what a provider with a page of its own does where the simulated one takes a typed card. Its setup creates a session on the provider’s side and hands back the address of the provider’s page:

@Override
public Setup startCardSetup(String customer, String setupId) throws IOException {
    Map session = ask("POST", "/v1/checkout/sessions", form("mode", "setup",
            "customer", customer, "payment_method_types[0]", "card",
            "client_reference_id", setupId,
            "success_url", returnUrl + "?result=done",
            "cancel_url", returnUrl + "?result=cancelled"), "");
    Setup setup = new Setup();
    setup.hosted = true;
    setup.reference = id(session);
    setup.url = text(session, "url");
    if (setup.url.length() == 0) {
        throw new IOException("The payment processor returned no page to open");
    }
    return setup;
}

The app opens the provider’s page for any setup that says it’s hosted, so it needs no change. Services is where the server picks an implementation from wayline.payments.provider, and a new provider is one more name there:

/// `wayline.payments.provider` is one of:
///
/// - `stripe`: [StripePayments], an untested stub over Stripe's REST API.
///   It needs `wayline.payments.stripe.secret`.
/// - `simulated`: test card numbers, and no money moves.
///
/// Unset, it is `simulated` on a development profile and `stripe` otherwise.
///
/// With Stripe a card is typed into Stripe's own page, which then sends the
/// browser back to `/pay/return` on this server. That address has to be the
/// one a phone can reach, so it is `wayline.public.url` when that is set
/// and the issuer -- the public address of this server, which a deployment
/// sets anyway -- when it is not.
@Bean
public PaymentProvider paymentProvider(Config config,
        @Value("${wayline.payments.provider:}") String chosen,
        @Value("${wayline.payments.stripe.secret:}") String secret,
        @Value("${wayline.public.url:}") String publicUrl,
        @Value("${" + AccountSecurity.ISSUER_KEY + ":}") String issuer) {
    String kind = chosen.trim().length() > 0 ? chosen.trim()
            : config.isDevelopmentProfile() ? "simulated" : "stripe";
    if ("simulated".equalsIgnoreCase(kind)) {
        return new SimulatedPayments();
    }
    if (!"stripe".equalsIgnoreCase(kind)) {
        return new MisconfiguredPayments(kind, "wayline.payments.provider is '" + kind
                + "', which is neither stripe nor simulated");
    }
    String address = publicUrl.length() > 0 ? publicUrl : issuer;
    String missing = missing("", new String[] {"wayline.payments.stripe.secret", secret,
        "wayline.public.url (or " + AccountSecurity.ISSUER_KEY + ")", address});
    if (missing.length() > 0) {
        return new MisconfiguredPayments("stripe", unset("payments", "stripe", missing));
    }
    while (address.endsWith("/")) {
        address = address.substring(0, address.length() - 1);
    }
    return new StripePayments(secret, address + "/pay/return");
}

The name a provider returns from name() is what the app is told, and is how it knows whether to show a card form or open a page.

A provider that takes the card inside the app through its own mobile SDK is a bigger change. The setup then happens in native code in the app, and the server is sent a token, not a typed card.

50.14. Text messages

A phone number is verified with a six-digit code sent by text message. PhoneVerification makes the code and checks it, and hands the sending to an SmsSender, an interface of two methods: send(phone, text) and delivers().

The setting wayline.sms.provider chooses the implementation, and Services.smsSender builds it:

ValueClassSettings it needs

console

ConsoleSmsSender

None. It writes [sms] to, the number and the text to the server’s output, and answers false from delivers(). Only a development profile (dev, test or local) may use it.

twilio

TwilioSmsSender

wayline.sms.twilio.sid, .token and .from: the account SID, the auth token and the number the messages come from.

vonage

VonageSmsSender

wayline.sms.vonage.key, .secret and .from: the API key, the API secret and the sender name or number.

messagebird

MessageBirdSmsSender

wayline.sms.messagebird.key and .originator: the access key and the sender name or number.

Without the setting, a development profile gets console and any other profile gets twilio. The development settings say so outright:

wayline.sms.provider=console
wayline.payments.provider=simulated
wayline.push.provider=console

50.14.1. Turning on a provider

Name the provider and give it its settings, with the secrets read from the environment:

wayline.sms.provider=vonage
wayline.sms.vonage.key=${WAYLINE_SMS_VONAGE_KEY}
wayline.sms.vonage.secret=${WAYLINE_SMS_VONAGE_SECRET}
wayline.sms.vonage.from=Wayline

The server reads every setting from the environment as well, under its name in upper case with an underscore for each dot, so wayline.sms.vonage.secret is also WAYLINE_SMS_VONAGE_SECRET. Keep keys, tokens and secrets there and not in a committed file. Nothing in the app changes when the provider does.

A provider that can’t be set up isn’t replaced with the console. With a setting missing, with console asked for on a production profile, or with a name that’s none of the four, the server uses MisconfiguredSmsSender. It logs a [config] line naming what to set when the server starts and again on every message, and every message fails, which the verification answers with 503. A server whose provider was forgotten verifies nobody, rather than everybody.

On a development profile with the console sender, the server also returns the code to the app, which shows it on the verification screen so a demo needs no phone. With any other sender, or on any other profile, the code is never returned.

50.14.2. What limits a code

These are in PhoneVerification and SecurityConfig:

  • A code is good for five minutes, CODE_SECONDS.

  • Five wrong entries, MAX_ATTEMPTS, spend the code, and the user asks for another. The count is one statement in the database, PhoneCodeRepository.takeGuess, which also applies the limit, so guesses sent together can’t get past it.

  • Another code for the same account within 30 seconds, RESEND_SECONDS, is answered 429.

  • SecurityConfig allows /api/account/phone/** ten requests in ten minutes for each signed-in user.

  • Only a hash of the code is stored, in phone_code. A new code doesn’t void the one before it, which stays good until it would have expired: people ask again when a message is slow, and text messages aren’t delivered in the order they were sent, so the first code can arrive last. At most two codes are good at once, and entering either one uses up both. The earlier code keeps the guesses it had left rather than getting five more.

  • The code is stored and committed before the message is sent. When the provider refuses the message, the code is discarded and the request is answered 503. The code sent before it, while still good, remains the one to enter.

The ten-in-ten-minutes limit uses an InMemoryRateLimiter, so it’s counted in each server process. The other limits are in the database and hold across instances.

50.14.3. Another provider

The interface is all a provider has to implement:

/// Sends a text message. The one place the server touches an SMS provider, so
/// changing provider is one class.
public interface SmsSender {
    /// - `IOException`: when the message could not be handed to the provider
    void send(String phone, String text) throws IOException;

    /// Whether a message really reaches a phone. False for the console sender used in
    /// development, which is what lets a development server hand the code back to the
    /// app in place of the text message nobody is going to receive.
    boolean delivers();
}

Another provider is another class, with delivers() answering true. The three that come with the sample have one shape: a form posted to the provider’s API. VonageSmsSender is the shortest:

/// Sends through Vonage's (formerly Nexmo's) SMS API: a form POST to
/// `https://rest.nexmo.com/sms/json` carrying `api_key`, `api_secret`, `to`,
/// `from` and `text`.
///
/// Vonage answers 200 even for a message it refused; the outcome is the
/// `status` of each entry of `messages`, where `"0"` is success and anything
/// else is an error code. A long text is split into parts and each part has an
/// entry, so every one of them has to be `"0"`.
///
/// Settings: `wayline.sms.vonage.key`, `wayline.sms.vonage.secret` and
/// `wayline.sms.vonage.from` (a virtual number or an alphanumeric sender id).
/// The number is sent without its leading `+`, as Vonage asks.
public class VonageSmsSender implements SmsSender {
    private static final String URL = "https://rest.nexmo.com/sms/json";

    private final String apiKey;
    private final String apiSecret;
    private final String from;

    public VonageSmsSender(String apiKey, String apiSecret, String from) {
        this.apiKey = apiKey;
        this.apiSecret = apiSecret;
        this.from = from;
    }

    @Override
    public void send(String phone, String text) throws IOException {
        String to = phone.startsWith("+") ? phone.substring(1) : phone;
        List headers = new ArrayList();
        headers.add("Content-Type: application/x-www-form-urlencoded");
        Web.Result sent = Web.request("POST", URL, headers, SmsForm.of("api_key", apiKey,
                "api_secret", apiSecret, "to", to, "from", from, "text", text));
        if (sent.getStatus() != 200) {
            throw new IOException("Vonage answered " + sent.getStatus());
        }
        Object messages = Json.parseObject(sent.getBodyAsString()).get("messages");
        if (!(messages instanceof List) || ((List) messages).isEmpty()) {
            throw new IOException("Vonage's answer lists no message");
        }
        for (Object entry : (List) messages) {
            Object status = entry instanceof Map ? ((Map) entry).get("status") : null;
            if (!"0".equals(status)) {
                // The code only; `error-text` can echo the number back.
                throw new IOException("Vonage refused the message with status " + status);
            }
        }
    }

    @Override
    public boolean delivers() {
        return true;
    }
}

send throws an IOException when the provider refuses the message, and PhoneVerification turns that into the 503. Services.smsSender then needs one more name for wayline.sms.provider, built the way the Vonage one is:

if ("vonage".equalsIgnoreCase(kind)) {
    String missing = missing("wayline.sms.vonage.", new String[] {"key", vonageKey,
        "secret", vonageSecret, "from", vonageFrom});
    return missing.length() > 0 ? new MisconfiguredSmsSender(unset("SMS", "vonage",
            missing)) : new VonageSmsSender(vonageKey, vonageSecret, vonageFrom);
}

A message costs money and a number can be anyone’s, so before going live decide which countries you send to and add that check to Accounts.phone, which accepts any number of seven to fifteen digits.

50.15. Push notifications

The live channel tells an app that’s open. A push notification is for the phone in a pocket: the rider whose driver has arrived, the driver who has been offered a ride. The server sends them through the Codename One push service, which delivers to Firebase, APNs and Huawei, and the app receives them with PushClient. Codename One Push Notifications covers the push service and the Console, and Section 35.5, “Sending push notifications” the server’s side of the API.

50.15.1. The app registers

Each phone registers with its platform’s push service when the app comes to the foreground, and hands the token it gets to the server for whoever is signed in. Signing out takes it back first, so the next person to use the phone isn’t told about the last one’s rides. That’s Notifications in the notify package:

/// Asks the platform for a push token. Called every time the app comes to
/// the foreground; registering is idempotent, and the platform answers
/// with the token it already gave when nothing has changed.
public static void start() {
    if (!available()) {
        return;
    }
    if (client == null) {
        client = PushClient.builder(AppConfig.PUSH_APP_KEY)
                .listener(new Listener())
                .build();
    }
    client.register();
}

/// Someone has signed in: the server learns where to reach them.
public static void signedIn() {
    PushDeviceDto device = device();
    if (device != null && Session.user() != null) {
        Api.account().registerPush(device, Net.to(saved -> { }, QUIET));
    }
}

/// Someone is signing out: the server forgets this phone for them, and
/// then `then` runs. It runs whether or not the server could be reached;
/// signing out never waits on a notification.
public static void signingOut(Runnable then) {
    PushDeviceDto device = device();
    if (device == null || Session.user() == null) {
        then.run();
        return;
    }
    // A failure is not kept for retrying. The row it would remove names
    // this phone's token, and the next sign-in on the phone takes that row
    // over for whoever signs in, as the server keeps a phone on the
    // account that signed in on it last. What is lost to an outage is
    // the window until then, on the phone of the account that signed out
    // -- noted in the implementor's guide among the hardening a
    // production deployment adds, not worth a durable queue in a sample.
    Api.account().unregisterPush(device, Net.to(gone -> then.run(),
            (status, message) -> then.run()));
}

The two calls are part of AccountApi:

/// Records a device the signed-in account is to be sent notifications on.
/// Registering the same token again moves it to this account: a phone
/// belongs to whoever signed in on it last.
@POST("/api/account/push")
void registerPush(@Body PushDeviceDto device, OnComplete<Response<PushDeviceDto>> callback);

/// Forgets a device, on signing out: the next person to use the phone is
/// not to be told about this account's rides.
@POST("/api/account/push/remove")
void unregisterPush(@Body PushDeviceDto device, OnComplete<Response<PushDeviceDto>> callback);

A token is the provider’s own, so the server stores it with the provider’s name. PushDevices keeps one row per phone: a phone that changes hands moves to the account that signed in on it last, and an account keeps its eight most recent phones. Closing an account removes them all.

/// The devices each account is sent notifications on.
///
/// The app registers its token when somebody signs in and removes it when they
/// sign out. A token registered by a second account moves to it: the phone
/// belongs to whoever signed in on it last, and the one before is not to be
/// told about the new owner's rides.
@Component
public class PushDevices {
    /// How many devices one account keeps. A new one past this replaces the
    /// one heard from longest ago: a token the platform has replaced is never
    /// removed by its app, and would otherwise be sent to for good.
    static final int MAX_PER_ACCOUNT = 8;

    private final PushDeviceRepository devices;
    private final ProfileRepository profiles;

    public PushDevices(PushDeviceRepository devices, ProfileRepository profiles) {
        this.devices = devices;
        this.profiles = profiles;
    }

    @Transactional
    public PushDeviceDto register(String username, PushDeviceDto device) throws IOException {
        PushTarget target = target(device);
        String id = key(target);
        Instant now = Instant.now();
        // Before anything is read, the account's profile row is held: a no-op
        // update that answers 0 when the profile is gone and otherwise keeps
        // the row locked until this commits. It settles two races.
        //
        // Against closing the account: Accounts.erase holds the same row
        // first and deletes it before it commits, so a registration either
        // runs first (and erase's cleanup then deletes the device with the
        // rest) or waits, finds no profile and is refused. Without it, a
        // registration authorized just before the closure could insert its
        // device after erase removed the account's, leaving a device of an
        // account that no longer exists and that nobody can unregister.
        //
        // Against itself: two devices registering at once for an account one
        // short of the cap would both count the same rows in makeRoom(), both
        // skip the eviction and both insert, one past the cap. Behind the hold
        // the second counts after the first committed, and evicts.
        if (profiles.hold(username) == 0) {
            throw new ResponseStatusException(404, "No such account");
        }
        // The device row itself is not locked. Two accounts registering one
        // token at the same moment -- a registration of the account that
        // signed out still in flight as the next one signs in -- can leave it
        // with the earlier account, but not for long: the app registers again
        // each time it comes to the foreground, for whoever is signed in then.
        PushDevice row = devices.findById(id);
        if (row == null || !username.equals(row.getUsername())) {
            // A device new to this account, whether its token is new or moves
            // here from another account, takes a place under the cap.
            makeRoom(username);
        }
        if (row == null) {
            row = new PushDevice();
            row.setId(id);
            row.setProvider(target.getProvider());
            row.setToken(target.getToken());
            fill(row, username, device, now);
            devices.insert(row);
        } else {
            fill(row, username, device, now);
        }
        return new PushDeviceDto(target.getProvider(), target.getToken(), row.getPlatform());
    }

    /// Removes `username`'s devices heard from longest ago until one more fits
    /// under [#MAX_PER_ACCOUNT].
    private void makeRoom(String username) {
        List<PushDevice> held = new ArrayList<PushDevice>(devices.findByUsername(username));
        while (held.size() >= MAX_PER_ACCOUNT) {
            PushDevice oldest = held.get(0);
            for (PushDevice each : held) {
                if (each.getUpdatedAt().isBefore(oldest.getUpdatedAt())) {
                    oldest = each;
                }
            }
            devices.deleteById(oldest.getId());
            held.remove(oldest);
        }
    }

    /// Forgets a device, if it is this account's. Somebody else's is left alone.
    @Transactional
    public PushDeviceDto unregister(String username, PushDeviceDto device) throws IOException {
        PushTarget target = target(device);
        devices.deleteByIdAndUsername(key(target), username);
        return new PushDeviceDto(target.getProvider(), target.getToken(), "");
    }

    /// Where to reach `username`: every device they registered.
    @Transactional(readOnly = true)
    public List<PushTarget> targets(String username) {
        return targetsOf(username);
    }

    /// [#targets] for a caller already inside a transaction.
    List<PushTarget> targetsOf(String username) {
        List<PushTarget> out = new ArrayList<PushTarget>();
        if (username == null || username.length() == 0) {
            return out;
        }
        for (PushDevice each : devices.findByUsername(username)) {
            out.add(PushTarget.of(each.getProvider(), each.getToken()));
        }
        return out;
    }

A tapped notification opens the app on the screen that shows the ride, which then reads the ride from the server as it does when it’s opened any other way:

/// Called on the event thread. A message is about a ride: the app opens
/// the screen that shows it, which reads the ride from the server. The
/// message's own words are for the notification shade, not for the app.
private static final class Listener implements PushListener {
    @Override
    public void onRegistration(PushSubscription registered) {
        subscription = registered;
        signedIn();
    }

    @Override
    public void onMessage(PushMessage message) {
        Object ride = message.getData().get("rideId");
        Object role = message.getData().get("role");
        // A message with no title is a silent one: the Live Activity
        // moving on, which the push client has already applied.
        String title = message.getTitle();
        if (ride != null && title != null && title.length() > 0
                && Session.user() != null) {
            Nav.showRide(role == null ? Nav.RIDER : String.valueOf(role));
        }
    }

    @Override
    public void onError(PushError error) {
        // Nothing to tell the user: the app works without notifications,
        // and asks again the next time it comes to the foreground.
        System.out.println("Push registration failed: " + error.getCode() + " "
                + error.getMessage());
    }
}

The app registers only on Android and iOS devices, and only with its push key set. The simulator has no push service to register with, and a page in a browser hears everything over the live channel while it’s open.

/// The app's push key, from the Push section of the Codename One console.
/// Empty, the app registers for no notifications: everything still works,
/// and a phone in a pocket simply hears nothing until it is opened.
public static final String PUSH_APP_KEY = "";

50.15.2. What the server sends

Rides tells RidePushes of every change to a ride once the change is committed, at the same moment it tells the live channel:

/// Tells the people concerned about a change to a ride that has been
/// committed. Called after the transaction, so what it reads is the ride as
/// it now is, and a phone that opens the app at once finds it so.
public void rideChanged(String id, RideState state, String rider, String driver) {
    try {
        send(compose(id, state, rider, driver));
    } catch (IOException | RuntimeException err) {
        System.err.println("[push] nothing was sent for ride " + id + " (" + state + "): "
                + err);
    }
}

A notification is a courtesy on top of what the app reads from the server, so nothing that goes wrong sending one fails the change it’s about. RidePushes decides who hears what:

switch (state) {
    case OFFERED:
        toDriver = message(id, state, DRIVER, "New ride request",
                "Pickup at " + ride.getPickupAddress() + ". Open Wayline to accept.")
                .ttlSeconds(offerSeconds);
        break;
    case ACCEPTED:
        toRider = message(id, state, RIDER, "Your driver is on the way",
                name + " is coming" + (car.length() > 0 ? " in a " + car : "") + ". About "
                + eta(ride, driver, false) + " min.");
        break;
    case ARRIVED:
        toRider = message(id, state, RIDER, "Your driver is here",
                car.length() > 0 ? "Look for " + car + "." : name + " is waiting for you.");
        surface = update(activityId, state(state, name, who, 0));
        break;
    case IN_PROGRESS:
        toRider = message(id, state, RIDER, "Your trip has started",
                "Arriving at " + ride.getDropoffAddress() + " in about "
                + eta(ride, driver, true) + " min.");
        surface = update(activityId, state(state, name, who, eta(ride, driver, true)));
        break;
    case COMPLETED:
        toRider = message(id, state, RIDER, "You've arrived",
                "Thanks for riding with Wayline. Your receipt is in the app.");
        surface = endOf(activityId, state, name, who);
        break;
    case CANCELLED_BY_DRIVER:
        toRider = message(id, state, RIDER, "Your driver canceled",
                "Sorry about that. Request again to find another driver.");
        surface = endOf(activityId, state, name, who);
        break;
    case CANCELLED_BY_ADMIN:
        toRider = message(id, state, RIDER, "Your ride was canceled",
                "Wayline support canceled this ride.");
        toDriver = driver == null || driver.length() == 0 ? null
                : message(id, state, DRIVER, "Ride canceled",
                "Wayline support canceled this ride.");
        surface = endOf(activityId, state, name, who);
        break;
    case CANCELLED_BY_RIDER:
        toDriver = driver == null || driver.length() == 0 ? null
                : message(id, state, DRIVER, "Ride canceled",
                "The rider canceled. You're available for new requests.");
        surface = endOf(activityId, state, name, who);
        break;
    case NO_DRIVERS:
        toRider = message(id, state, RIDER, "No drivers available",
                "Nobody could take your ride right now. Try again in a few minutes.");
        break;
    default:
        break;
}

Every message carries the ride’s id, its state and whether it’s for the rider or the driver, so the app knows which screen to open. Each ride and role has its own collapse key, so a phone that was out of reach shows the latest step and not every one. An offer to a driver lives only as long as the offer, fifteen seconds by default: one delivered later would offer a ride that’s gone.

The switches under Notifications in the app’s settings decide what’s said. A switch that’s off silences the notification and nothing else, so the lock screen still follows the ride:

/// Whether `username` asked to be told: of receipts when `receipt`, of
/// ride updates otherwise. An account that never saved its settings gets
/// both, as the settings screen shows it.
private boolean wants(String username, boolean receipt) throws IOException {
    Preference row = preferences.findById(username);
    if (row == null) {
        return true;
    }
    return receipt ? row.isNotifyReceipts() : row.isNotifyRides();
}

50.15.3. Turning on the push service

wayline.push.provider chooses how notifications leave the server, and Services.pushSender builds the sender:

ValueClassWhat it does

cloud

CloudPushSender

Sends through the Codename One push service. It needs wayline.push.app, the application UUID of the push application, and wayline.push.key, a server API key with the push scope. Both come from the Push section of the Console.

console

ConsolePushSender

Writes [push], the number of devices and the message to the server’s output. Only a development profile may use it.

recording

RecordingPushSender

Keeps every message for the tests to read. Only a development profile may use it, and the test profile does.

Without the setting, the test profile gets recording, the other development profiles get console and any other profile gets cloud:

/// `wayline.push.provider` is one of:
///
/// - `cloud`: the Codename One push service. It needs `wayline.push.app`,
///   the app's push id, and `wayline.push.key`, a server key with the push
///   scope; both are in the Push section of the Codename One console.
/// - `console`: prints each notification, on a development profile only.
/// - `recording`: keeps each notification for the tests to read, on a
///   development profile only.
///
/// Unset, it is `recording` on the `test` profile, `console` on the other
/// development profiles and `cloud` otherwise. A server whose push settings
/// are missing still starts and still serves rides: it logs a configuration
/// error at start-up and again for every notification it could not send.
@Bean
public PushSender pushSender(Config config,
        @Value("${wayline.push.provider:}") String chosen,
        @Value("${wayline.push.app:}") String app,
        @Value("${wayline.push.key:}") String key,
        @Value("${wayline.push.url:}") String url) {
    String kind = chosen.trim().length() > 0 ? chosen.trim()
            : "test".equals(config.getProfile()) ? "recording"
            : config.isDevelopmentProfile() ? "console" : "cloud";
    if ("console".equalsIgnoreCase(kind) || "recording".equalsIgnoreCase(kind)) {
        if (!config.isDevelopmentProfile()) {
            return new MisconfiguredPushSender("wayline.push.provider=" + kind
                    + " sends nothing and is refused on the '" + config.getProfile()
                    + "' profile; set it to cloud");
        }
        return "console".equalsIgnoreCase(kind) ? new ConsolePushSender()
                : new RecordingPushSender();
    }
    if (!"cloud".equalsIgnoreCase(kind)) {
        return new MisconfiguredPushSender("wayline.push.provider is '" + kind
                + "', which is none of cloud, console or recording");
    }
    String missing = missing("wayline.push.", new String[] {"app", app, "key", key});
    if (missing.length() > 0) {
        return new MisconfiguredPushSender(unset("push", "cloud", missing));
    }
    try {
        CloudPush push = new CloudPush(app.trim(), key.trim());
        return new CloudPushSender(url.trim().length() > 0 ? push.withEndpoint(url.trim())
                : push);
    } catch (IllegalArgumentException err) {
        return new MisconfiguredPushSender("push provider 'cloud' is misconfigured: "
                + err.getMessage());
    }
}

To turn it on, give the server the two values, with the key read from the environment:

wayline.push.app=3f0c2a4e-8b1d-4c7a-9e55-2d6b1f0a7c19
wayline.push.key=${WAYLINE_PUSH_KEY}

Then put the push key the Console shows for the app in AppConfig.PUSH_APP_KEY, and configure each platform’s credentials in the Console as Codename One Push Notifications describes.

Push on Android starts switched off, so the generated project builds for Android before you have a Firebase project. An app that uses PushClient needs google-services.json from Firebase, agconnect-services.json from Huawei, or both, in the Android native files as Codename One Push Notifications describes, and the build stops with an error without them. Until then codenameone_settings.properties carries codename1.arg.android.messagingService=none, which builds the app without push. Add the file and delete that line, and Android gets notifications too.

A server that’s missing a setting still starts and serves rides; the sender it gets instead, MisconfiguredPushSender, logs a [config] line naming the setting when the server starts and again for every notification it can’t send. Both come from the Codename One app kit (com.codename1.appkit.server.push). CloudPushSender sends on a thread of its own, so a ride’s request never waits on the push service, and it logs a refusal rather than throwing it:

/// Sends through the Codename One push service, which delivers to Firebase,
/// Apple, Huawei and the browsers on the app's behalf.
///
/// The call to the service is made on a thread of its own, so the request that
/// changed something answers without waiting for it, and a refusal is logged and
/// not thrown: the user still learns of the change the next time the app
/// reads it.
public class CloudPushSender implements PushSender {
    private final CloudPush push;

    /// @param push the client for the service, holding the app's id and the
    ///     server key
    public CloudPushSender(CloudPush push) {
        this.push = push;
    }

    @Override
    public void send(List<PushTarget> targets, final PushNotification message,
            final Runnable delivered) {
        if (targets == null || targets.isEmpty()) {
            return;
        }
        final List<PushTarget> to = new ArrayList<PushTarget>(targets);
        Tasks.platform(() -> deliver(to, message, delivered));
    }

    private void deliver(List<PushTarget> to, PushNotification message, Runnable delivered) {
        boolean accepted = false;
        try {
            PushResult result = push.send(message, to);
            accepted = result.isAccepted();
            if (!accepted) {
                System.err.println("[push] the push service refused a notification: "
                        + result.getStatus() + " " + result.getError());
            }
        } catch (IOException | RuntimeException err) {
            System.err.println("[push] a notification was not sent: " + err);
        }
        if (accepted && delivered != null) {
            try {
                delivered.run();
            } catch (RuntimeException err) {
                System.err.println("[push] a notification was sent, and what follows it failed: "
                        + err);
            }
        }
    }
}

To send through another service, implement PushSender, one method, and return it from Services.pushSender:

/// Sends push notifications to devices.
///
/// The application chooses the implementation, normally from a property, when
/// it builds its beans. A notification is a courtesy on top of what the
/// app reads from the server, so sending one never fails the change it is about:
/// an implementation logs what went wrong and returns.
public interface PushSender {
    /// Sends `message` to every one of `targets`. Returns at once; the sending
    /// itself may happen later, on another thread.
    ///
    /// @param delivered run once the push service has taken the message, on
    ///     whatever thread learnt it; never when it was refused or could not be
    ///     sent. Null when nobody needs to know.
    void send(List<PushTarget> targets, PushNotification message, Runnable delivered);
}

50.16. The ride on the lock screen

While a driver is on the way, the rider’s ride shows outside the app: a Live Activity on the lock screen and on the Dynamic Island of an iPhone, an ongoing notification on Android, and a small window on the desktop and in the simulator. A browser shows none. Chapter 69, External Surfaces: Widgets and Live Activities covers the API.

RideCard in the rider package starts it when a driver accepts, moves it on with every change the rider screen sees and ends it with the ride. A finished ride stays on the lock screen for a while with its last state; a canceled one goes at once. Starting one is a round trip to the system, so it runs off the event thread, and the activity’s id goes to the server:

/// The rider screen has `ride` as it now is. Called on the event thread.
static void follow(final RideDto ride) {
    if (ride == null || busy) {
        return;
    }
    boolean meeting = RideState.ACCEPTED == ride.state() || RideState.ARRIVED == ride.state()
            || RideState.IN_PROGRESS == ride.state();
    if (activity != null && !ride.id().equals(rideId)) {
        // A ride this screen no longer shows: its activity goes.
        final LiveActivity stale = activity;
        activity = null;
        rideId = null;
        shown = "";
        CN.scheduleBackgroundTask(() -> stale.end(null, true));
    }
    final boolean ours = activity != null;
    if (!meeting) {
        if (ours) {
            final LiveActivity ending = activity;
            final boolean done = RideState.COMPLETED == ride.state();
            activity = null;
            rideId = null;
            shown = "";
            // A finished ride stays on the lock screen a little while, as
            // the platform decides; a cancelled one goes at once.
            CN.scheduleBackgroundTask(() -> ending.end(done ? state(ride) : null, !done));
        }
        return;
    }
    final Map<String, Object> now = state(ride);
    String key = ride.id() + ":" + now;
    if (ours ? key.equals(shown) : ride.id().equals(tried)) {
        return;
    }
    if (!ours) {
        tried = ride.id();
    }
    shown = key;
    busy = true;
    final LiveActivity current = ours ? activity : null;
    // Off the event thread: on a phone starting and updating an activity
    // is a round trip to the system.
    CN.scheduleBackgroundTask(() -> {
        if (current != null) {
            current.update(now);
            CN.callSerially(() -> busy = false);
            return;
        }
        final LiveActivity started = LiveActivity.start(descriptor(), now);
        CN.callSerially(() -> {
            busy = false;
            if (!started.isActive()) {
                return;
            }
            activity = started;
            rideId = ride.id();
            Api.rider().activity(ride.id(), new RideActivityDto(started.getId()),
                    Net.to(saved -> { }, QUIET));
        });
    });
}

The layout is data. The app sends it once when the activity starts, with ${key} placeholders the platform fills from the state, so an update is a few short strings and a number. The keys are constants in RideActivityKeys in shared, because the server writes the same state:

/// The layout, filled in from the state on the device: an update sends the
/// state alone.
private static LiveActivityDescriptor descriptor() {
    return new LiveActivityDescriptor(RideActivityKeys.KIND)
            .setContent(content())
            .setCompactLeading(new SurfaceText("${driver}").setFontSize(13)
                    .setMaxLines(1))
            .setCompactTrailing(new SurfaceText("${eta}").setFontSize(13)
                    .setColor(SurfaceColor.ACCENT))
            .setMinimal(new SurfaceText("${eta}").setFontSize(11))
            .setExpandedCenter(new SurfaceText("${status}").setFontSize(16)
                    .setFontWeight(SurfaceFontWeight.SEMIBOLD))
            .setExpandedBottom(content())
            .setTint(SurfaceColor.rgb(ACCENT));
}

private static SurfaceNode content() {
    return new SurfaceColumn().setSpacing(6).setPadding(12)
            .add(new SurfaceRow().setSpacing(10)
                    .add(new SurfaceColumn().setSpacing(2).setWeight(1)
                            .add(new SurfaceText("${status}").setFontSize(15)
                                    .setFontWeight(SurfaceFontWeight.SEMIBOLD)
                                    .setMaxLines(1))
                            .add(new SurfaceText("${driver} - ${car}").setFontSize(13)
                                    .setColor(SurfaceColor.SECONDARY_LABEL)
                                    .setMaxLines(1))
                            .add(new SurfaceText("${plate}").setFontSize(13)
                                    .setFontWeight(SurfaceFontWeight.BOLD)
                                    .setMaxLines(1)))
                    .add(new SurfaceText("${eta}").setFontSize(22)
                            .setFontWeight(SurfaceFontWeight.BOLD)
                            .setColor(SurfaceColor.ACCENT)))
            .add(new SurfaceProgress(SurfaceProgress.STYLE_LINEAR)
                    .setValueState(RideActivityKeys.PROGRESS)
                    .setColor(SurfaceColor.rgb(ACCENT)));
}

Once the app is in the background the server keeps the activity current. It records the activity’s id against the ride, but only the rider’s own ride and only while a driver is bringing or carrying them:

/// Records the Live Activity the rider's phone shows `rideId` in. Only for
/// the ride's rider, and only while a driver is bringing or carrying them:
/// that is when the activity is on screen.
@Transactional
public RideActivityDto attach(String rider, String rideId, RideActivityDto activity)
        throws IOException {
    String activityId = Text.required(activity == null ? null : activity.activityId(), 190,
            "the activity");
    Ride ride = rides.findById(rideId);
    if (ride == null || !ride.getRider().equals(rider)) {
        throw new ResponseStatusException(404, "No such ride");
    }
    // The state check and the insert have to be one step against the ride
    // ending: checked from the ride read above, a driver completing it or
    // an admin cancelling it could commit in between, its compose() would
    // find no activity to end, and this one would be inserted after it and
    // stay on the lock screen. holdWhile checks the state in the database
    // and keeps the ride's row locked until this commits, so an ending
    // either happened first (409 here) or waits and then finds the row.
    if (rides.holdWhile(rideId, rider, MEETING) == 0) {
        throw new ResponseStatusException(409, "That ride has no driver on the way");
    }
    // One activity per ride, the last one attached. A rider following
    // their own ride on two phones at once is not a case the sample
    // serves: the earlier phone's activity stops moving and the system
    // removes it. A row per device is listed in the implementor's guide
    // among what a product adds.
    RideActivity row = activities.findById(rideId);
    if (row == null) {
        row = new RideActivity();
        row.setRideId(rideId);
        row.setUsername(rider);
        row.setActivityId(activityId);
        row.setSentAt(Instant.now());
        activities.insert(row);
    } else {
        row.setActivityId(activityId);
        row.setSentAt(Instant.now());
    }
    return new RideActivityDto(activityId);
}

Each change of state then carries the activity’s new state in the same notification that announces it, and the end of the ride ends the activity. In between, the driver’s position reports move the minutes on in a silent message, no more often than wayline.push.activity.seconds, 45 by default. A conditional update of the ride’s row decides whether one is due, so two servers receiving reports at once send one update between them.

The app’s push client applies such a message when the Codename One runtime receives it, before the listener runs. Where the platform doesn’t start the app for a push in the background, the message waits and is applied when the app next starts or resumes. Apple’s own route for a server to update a Live Activity, the ActivityKit push token, isn’t used, so on an iPhone the activity of an app iOS has suspended is only as current as the last message the app received. While the app is open, the rider screen keeps it exact itself.

The app declares the Live Activity in surfaces.json, in src/main/resources of common:

{
  "liveActivities": true
}

ios.surfaces.frequentUpdates among the build hints below asks iOS for the frequent updates a moving car needs.

50.17. Driving in the background

A driver who switches to a navigation app or locks the phone is still driving, and the server stops offering rides to a driver it hasn’t heard from for a minute. While a driver is online, Shift in the driver package keeps the position going to the server with the app in the background:

/// A driver's time on line, as far as the phone is concerned: the position
/// keeps going to the server while the app is in the background.
///
/// In the foreground the driver screen reports every few seconds itself. Put
/// away -- the driver switched to a navigation app, or locked the phone -- that
/// screen stops, and this takes over: it follows the position in the
/// background and reports it when the car has moved [#MIN_METERS], and at
/// least every [#KEEP_ALIVE_MILLIS] even when it has not, because a driver who
/// goes quiet for a minute stops being offered rides.
///
/// - On iOS the `location` background mode keeps the app running while it
///   tracks, and each new position is the moment to report.
/// - On Android a foreground service keeps it running, with the notification
///   the system requires, and wakes it for the reports a parked car would not
///   send.
/// - The simulator and the browser stand still and report nothing here.
public final class Shift {
    /// How far the car moves before the server hears of it again.
    static final double MIN_METERS = 25d;
    /// The longest the server goes without hearing, well inside the minute
    /// after which it stops offering this driver rides.
    static final long KEEP_ALIVE_MILLIS = 20000L;
    private static final String CHANNEL = "wayline-driving";
    private static final Net.Failed QUIET = (status, message) -> { };

    private static boolean on;
    private static boolean background;
    private static long sentAt;
    private static LatLng sentFrom;
    private static ForegroundService service;
    /// Read by the service's own thread, so not a plain field.
    private static final AtomicBoolean RUNNING = new AtomicBoolean();
    private static final Locator.Watcher WATCHER = (state, where) -> {
        if (state == Locator.FOUND && background) {
            report(where);
        }
    };

    private Shift() {
    }

    /// The driver went on line.
    public static void begin() {
        if (on) {
            return;
        }
        on = true;
        sentFrom = null;
        Locator.track(true);
        Locator.watch(WATCHER);
        if (ForegroundService.isSupported() && "and".equals(CN.getPlatformName())
                && !CN.isSimulator()) {
            RUNNING.set(true);
            service = ForegroundService.start(CHANNEL, "You're online",
                    "Wayline shares your location with riders while you drive.", null,
                    Shift::keepAlive);
        }
    }

    /// The driver went off line, signed out or left the driver's side of the
    /// app. Nothing goes on following where the phone is.
    public static void end() {
        if (!on) {
            return;
        }
        on = false;
        Locator.unwatch(WATCHER);
        Locator.track(false);
        RUNNING.set(false);
        if (service != null) {
            service.stop();
            service = null;
        }
    }

    /// Leaving the driver's side of the app, with the session still there:
    /// the server is told this driver is off line before the phone stops
    /// reporting. Otherwise it would go on offering rides to a phone that is
    /// no longer listening until the reports went stale, a minute, and each
    /// rider would wait out an offer nobody sees. One request, not waited
    /// for; if it is lost the minute is the fallback.
    public static void leave() {
        if (on) {
            LatLng where = Locator.here();
            Api.driver().status(new DriverStatusDto(false, where.getLatitude(),
                    where.getLongitude(), Locator.heading()), Net.to(me -> { }, QUIET));
        }
        end();
    }

    public static boolean isOn() {
        return on;
    }

    /// The app went to the background, and the reports are this class's.
    public static void paused() {
        background = true;
    }

    /// The app is back, and the driver screen reports again.
    public static void resumed() {
        background = false;
    }

DriverForm begins the shift when the server says the driver is online and ends it when they go offline; signing out and switching to the rider’s side end it too. Reports go through the same call the driver screen makes in the foreground, so the server needs nothing new. They’re spaced by distance and time, 25 meters or twenty seconds, which is what keeps the battery cost down: the car’s position changes far more often than the server needs to hear of it.

Locator asks the platform for the precise, frequent fixes a driver needs only while a shift is on, and lets go of location altogether when the app is in the background without one:

/// Asks for the position precisely, often, and on in the background, or
/// goes back to the ordinary search. A driver on line tracks: riders follow
/// the car on a map, and the server offers rides by distance.
///
/// The platform decides what "in the background" allows. With the
/// `location` background mode an iPhone goes on reporting after the app is
/// put away; Android does while the app runs a foreground service, which is
/// what [com.codenameone.examples.wayline.driver.Shift] starts.
public static void track(boolean on) {
    if (tracking == on) {
        return;
    }
    tracking = on;
    if (started && !simulated()) {
        LocationManager.getLocationManager().setLocationListener(null);
        start(true);
    }
}

/// The app went to the background. Unless a driver is tracking, the
/// platform is told to stop looking: an app with a background location
/// mode is otherwise kept running, and draining the battery, for a map
/// nobody is looking at.
public static void paused() {
    if (!started || tracking || simulated()) {
        return;
    }
    paused = true;
    search++;
    LocationManager.getLocationManager().setLocationListener(null);
}

/// The app is back: whatever [#paused] put down is taken up again.
public static void resumed() {
    if (!paused) {
        return;
    }
    paused = false;
    if (started && !simulated()) {
        start(true);
    }
}
PlatformHow it keeps running

iOS

The location background mode. iOS asks the driver for permission to use the location while the app isn’t in use, with the text of the NSLocationAlwaysAndWhenInUseUsageDescription build hint.

Android

A foreground service of the location type, with the You’re online notification Android requires while it runs.

The simulator, the desktop and a browser

None. Reports stop while the app isn’t in front.

These are the build hints the three features need. The project already has them in common/codenameone_settings.properties:

codename1.arg.ios.background_modes=location
codename1.arg.ios.locationUsageDescription=Your location is where a ride picks you up, and where riders find you while you drive.
codename1.arg.ios.NSLocationAlwaysAndWhenInUseUsageDescription=While you are online as a driver, Wayline keeps sharing your location with riders and dispatch, even with the app in the background.
codename1.arg.android.foregroundServiceType=location
codename1.arg.ios.includePush=true
codename1.arg.ios.surfaces.frequentUpdates=true

Both app stores review background location. Apple asks what the location is used for while the app is in the background, and Google Play asks for a declaration and a video of the feature in use. A driver app has a good answer, and the usage description should give it in the driver’s terms.

50.18. Signing in through another identity provider

Out of the box the server is its own authorization server: accounts and passwords are in its database, and the tokens the API accepts are the ones it signs. A product often wants people to sign in with an account they already have, at Google, Microsoft Entra ID, Auth0 or a Keycloak of its own. There are two ways to do it, and they differ in who issues the token the API sees.

Beside the built-in serverInstead of it

Who signs the user in

The provider, or Wayline’s own password form

The provider only

Whose token the API accepts

Wayline’s, as now

The provider’s

Where the roles are

Wayline’s database, as now

Wayline’s database, or a claim in the token

What changes

The sign-in chain, and how the app starts a sign-in

The API chain, the app’s sign-in, registration and the password screens

The first is the smaller change and keeps password accounts working. Choose the second when the organization already manages its people, and their roles, in the provider.

50.18.1. Beside the built-in server

The server keeps issuing its own tokens and leaves it to the provider to identify the user. On the server that’s oauth2Login on the sign-in chain, with the provider’s client id and secret in the configuration:

cn1.security.oauth2.client.registration.google.client-id=your-google-client-id
cn1.security.oauth2.client.registration.google.client-secret=your-google-client-secret

cn1.security.oauth2.client.registration.github.client-id=your-github-client-id
cn1.security.oauth2.client.registration.github.client-secret=your-github-client-secret

cn1.security.oauth2.client.registration.acme.client-id=web
cn1.security.oauth2.client.registration.acme.client-secret=your-acme-client-secret
cn1.security.oauth2.client.registration.acme.scope=openid,profile,email
cn1.security.oauth2.client.registration.acme.provider=acme-id
cn1.security.oauth2.client.provider.acme-id.issuer-uri=https://id.example.com

A registration called google or microsoft needs only the id and the secret. Auth0 and Keycloak are described by a provider block with their issuer-uri, as the acme registration is. The secret belongs in the environment.

Wayline’s accounts are named by e-mail address, which is what LinkingOAuth2UserService matches on: a person whose provider vouches for the address of an existing account signs in as that account, with its roles.

@Bean
FederatedIdentityRepository identities(DataSource dataSource) {
    return new JdbcFederatedIdentityRepository(dataSource);
}

@Bean
SecurityFilterChain web(HttpSecurity http, FederatedIdentityRepository identities,
                        UserDetailsService users) {
    LinkingOAuth2UserService linking = new LinkingOAuth2UserService(identities, users);
    linking.setCreateUsers(true);

    http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
        .oauth2Login(oauth2 -> oauth2
                .userService(linking)
                .oidcUserService(linking.oidc()));
    return http.build();
}

In Wayline the oauth2Login call goes on the signIn chain in SecurityConfig, beside formLogin. Section 41.10, “Signing in through another provider” covers the registration keys and the linking rules. Two things are particular to Wayline:

  • An account has a row in profile as well as a sign-in, and Accounts.register writes both. With setCreateUsers(true) the linking service creates the sign-in alone. Either leave it false and send new people through the app’s registration first, or create the profile for a user who arrives without one.

  • The redirect address to register with the provider is the server’s: /login/oauth2/code/ and the registration’s name, on the issuer’s https address. It’s one address for every platform, because the provider only ever redirects to the server.

In the app, Session.authenticate posts the e-mail address and password to /login and then asks for the code itself, with no browser. A provider’s sign-in page has to be shown, so that path changes to the browser flow of OidcClient. Session already builds the client with OidcClient.create. The sign-in becomes a call to authorize():

OidcClient.discover("https://api.example.com").ready(discovered -> {
    client = discovered
            .setClientId("notes-app")
            .setRedirectUri("com.example.notes:/oauth2redirect")
            .setScopes("openid", "profile", "notes.read")
            .setTokenStore(new SecureStorageTokenStore());
    client.authorize()
            .ready(tokens -> showNotes())
            .except(err -> showSignInFailed(err));
});

The redirect address of that flow is the app’s, and it differs by platform:

Where the app runsRedirect address

iOS and Android

An address in a scheme of the app’s own, such as com.example.rides:/oauth2redirect. Declare the scheme with the ios.urlScheme and android.xintent_filter build hints, as Section 95.10, “Signing in against a Codename One backend” shows.

The hosted browser app

/signin/code on the server’s own origin, AppConfig.WEB_REDIRECT_PATH, which the server already registers.

The simulator and the desktop app

An https address. The browser window closes when it reaches it.

Each address the app uses has to be on the registered client. Add the scheme address with another redirectUri call where SecurityConfig.clients builds the RegisteredClient, and return it from AppConfig.redirectUri() on a device. The client is saved only when the database has none with that id, so a database that already holds the registration keeps the old list until the stored client is updated.

50.18.2. Instead of the built-in server

With this approach the provider issues the tokens and the server only validates them.

The app. Build the client from the provider’s metadata instead of from Wayline’s endpoints, with the client id the provider issued:

OidcClient.discover("https://accounts.google.com").ready(new SuccessCallback<OidcClient>() {
    public void onSucess(OidcClient client) {
        client.setClientId("YOUR_CLIENT_ID")
              .setRedirectUri("com.example.app:/oauth2redirect")
              .setScopes("openid", "email", "profile");
        client.authorize().ready(new SuccessCallback<OidcTokens>() {
            public void onSucess(OidcTokens tokens) {
                // tokens.getAccessToken() -- bearer for API calls
                // tokens.getIdToken()      -- JWT with user identity claims
                // tokens.getEmail()        -- convenience accessor
            }
        }).except(new SuccessCallback<Throwable>() {
            public void onSucess(Throwable err) {
                System.out.println("Sign-in failed: " + err.getMessage());
            }
        });
    }
});

OidcClient.discover works with any provider that publishes OpenID Connect metadata. Keep the OidcRequestAuthorizer that Session installs on the API’s address. It attaches the token and refreshes it whatever the issuer is. The redirect addresses are the ones in the table above, registered with the provider this time: the scheme address for the installed apps and the https address of the hosted app. Register the app as a public client, with no secret.

The server. The API chain stops building a decoder from its own keys and validates the provider’s tokens:

cn1.security.oauth2.resourceserver.jwt.issuer-uri=https://id.example.com
cn1.security.oauth2.resourceserver.jwt.audiences=orders-api

Set audiences to the identifier the provider puts in the access token’s aud for your API. In SecurityConfig.api, drop the DefaultJwtDecoder built from the signing keys and the decoder call, and the chain uses the one these properties describe. The signIn chain, the clients bean and SignInCodePage are no longer used. Section 41.7, “A JWT resource server” covers the keys, what’s verified and a server that trusts several issuers.

The API needs an access token that’s a JWT the server can verify with the provider’s published keys. Check what your provider issues for an API of your own before choosing this approach. A provider whose access tokens are opaque, or meant only for its own APIs, fits the first approach.

What goes with it. Registration, the password change and the password check before deleting an account all work on Wayline’s own user store. With a provider in charge of the accounts, a person’s first request has to create their profile, and the password screens go.

50.18.3. From claims to roles

The API rules ask for RIDER, DRIVER and ADMIN. Where those come from is the JwtAuthenticationConverter on the API chain, and there are two choices.

Keep the roles in Wayline’s database. The converter in SecurityConfig ignores the token’s claims and loads the account named by the token’s subject on every request. A provider’s subject is an opaque id and not an e-mail address, so tell the converter which claim names the account with setPrincipalClaimName, and use a claim the provider has verified. Driver approval, an admin’s grant and a block all keep working as they do now, and they take effect on the next request.

Read the roles from the token. Have the provider put the roles in a claim and map the claim:

JwtGrantedAuthoritiesConverter roles = new JwtGrantedAuthoritiesConverter();
roles.setAuthoritiesClaimName("roles");     // ["ADMIN", "USER"]
roles.setAuthorityPrefix("ROLE_");          // so hasRole("ADMIN") matches

JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
converter.setJwtGrantedAuthoritiesConverter(roles);
converter.setPrincipalClaimName("preferred_username");

http.oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt ->
        jwt.jwtAuthenticationConverter(converter)));

With the ROLE_ prefix, a claim holding RIDER, DRIVER or ADMIN matches the rules unchanged. JwtGrantedAuthoritiesConverter reads a claim holding a flat list of names. Each provider has its own way to add such a claim to a token and its own name for it, so configure the provider to send one and check a token from your own tenant.

The cost of this choice is timing. A role withdrawn at the provider is still in every token already issued and holds until the token expires, and the same is true of a blocked account. Wayline’s flows also grant roles themselves: approving a driving application makes a driver, and the admin screens grant and withdraw admin. With roles in the provider, those two steps have to change the roles there, or the driver role has to stay in the database. A reasonable split is ADMIN from the provider and RIDER and DRIVER from the database, which a converter of your own can combine.

50.19. Analytics

The app reports how it’s used through the framework’s analytics API, which Chapter 100, Analytics documents. Everything it does is in one class, Telemetry, so that’s the file to read and the file to change.

Nothing is reported until the user agrees. After the first sign-in, ConsentForm asks once, with Share usage statistics and Not now. The answer is kept on the device, not with the account, and the Usage statistics switch under Privacy and safety in the settings changes it at any time. Telemetry passes the answer to Analytics.setConsent with analytics and crash reporting set to the answer and personalization and advertising storage always off. Section 100.2, “Consent and privacy” describes what each of those gates.

Deleting the account calls Telemetry.forget, which resets the anonymous id the reports carry.

50.19.2. What’s reported

Every screen reports a screen view. Beyond that the app reports these events:

AreaEventParameters

Account

login, sign_up, logout, phone_verified

The method, whether the person meant to ride or drive, and why a session ended: the user, expiry or deletion

Rides

ride_quoted, ride_requested, ride_cancelled, ride_completed, rating_given

The product, the payment kind, a distance bracket, a fare bracket, who cancelled and in which state, the number of stars

Payments

tip_added, card_added, card_removed

Where the tip was added and its share of the fare

Driving

driver_application_started, driver_application_submitted, driver_online, driver_offline, offer_accepted, offer_declined, payout_requested

Whether an application is a resubmission, and an amount bracket

Administration

admin_application_approved, admin_application_rejected, admin_user_flagged, admin_user_unflagged, admin_user_blocked, admin_user_unblocked, admin_ride_refunded, admin_pricing_changed

Which screen a refund was made from

Settings

language_changed, theme_changed

The language and the theme

Two user properties go with them, the role and the language. An uncaught error is reported with Analytics.crash and carries the exception’s class name alone.

No event carries a name, an e-mail address, a phone number, a street address, a position, a card number or a ride’s id. Money and distance are reported as brackets and never as amounts. Keep to that when you add an event: add a method to Telemetry and call it from the screen, so the list of what leaves the device stays in one file.

50.19.3. Where the reports go

Telemetry.start registers LoggingAnalyticsProvider in the simulator and CodenameOneAnalyticsProvider everywhere else. A run in the simulator writes its events to the console and sends nothing. The Codename One provider identifies the app from properties the build puts into it, which a local run doesn’t have. A built app reports to Codename One, and the reports are shown in the developer console.

To send the events somewhere else, register another provider in Telemetry.start. Chapter 100, Analytics lists the ones the framework has and how to write one.

50.20. Maps, search and routes

50.20.1. What the sample uses

WhatWhere it comes fromCalled by

The map

Vector tiles of OpenStreetMap data from OpenFreeMap, drawn by MapView. No key and no account.

The app, directly.

Routes

The OSRM project’s public demo server, through the Routing class.

The app, directly.

Place search

A public Photon server, which searches OpenStreetMap data.

The server, at /api/geo/search and /api/geo/reverse.

Place search goes through your server so that the app never sends what a user types to a third party directly, and so that you can change the service without shipping a new app.

When a route can’t be fetched, the app draws a straight line between the two points and estimates the time from the distance. The server prices from its own estimate whenever the app’s figures aren’t plausible, so a failed route changes what the rider sees and not what they pay.

50.20.2. What these services are good for

All three are run by other people at no charge. They’re the right choice for development, a demo and a pilot, and they need a decision before a launch:

  • The OSRM demo server has no service guarantee and limits how often it can be asked. It exists for trying OSRM out.

  • The public Photon server is shared by everyone who uses it and is meant for light use.

  • OpenFreeMap asks for no key. Read its terms of use, and plan for what your app does when a service you don’t control is slow or gone.

None of them knows about traffic. The time the app shows and the time part of the fare come from distances and typical speeds.

50.20.3. Pointing at your own

Tiles and routes are chosen in the app. Maps.create builds the map, and Routing.setService replaces the route service for the whole app:

/// Tiles from a server of your own, in place of the keyless default.
public static MapView create(LatLng center, int zoom) {
    MapView map = new MapView(
            new MvtTileSource("https://tiles.example.com/planet/{z}/{x}/{y}.pbf", 0, 14),
            dark ? MapStyle.dark() : MapStyle.light());
    map.setName("map");
    map.moveCamera(center, zoom);
    return map;
}

/// Routes from your own OSRM instance. Call it once, as the app starts.
public static void useOwnRouting() {
    Routing.setService(new OsrmRouteService("https://osrm.example.com"));
}

A keyed tile provider takes its key with setApiKey, and a provider that isn’t OSRM-compatible is an implementation of RouteService. The Maps chapter covers both.

Place search is chosen on the server:

wayline.geocoder=photon
wayline.geocoder.url=https://photon.rides.example.com

That points PhotonGeocoder at a Photon server you run. A different search service is another implementation of the Geocoder interface, chosen in Services.

50.20.4. Where the app starts

A device that reports its position opens the map there. Until it does, and in a browser that won’t say, the map opens on AppConfig.DEFAULT_LAT and DEFAULT_LNG, which is San Francisco’s northern waterfront. Change them to your city.

50.21. Demo data

Everything a development server shows on first start is made by two classes.

DemoAccounts creates the accounts when the server starts. On a development profile, which is dev, test or local, it creates the riders, the drivers, the applicant and the admin, gives the drivers approved applications with cars and placeholder documents, and saves a simulated card for some riders. On any other profile it creates one account and no more: the first admin, from wayline.admin.email and wayline.admin.password.

DemoRides stores two weeks of rides as entities, already finished: three to six a day between ten places in San Francisco, about three quarters of them completed, with their events, payments and ratings, and a payout of the first week’s earnings. The sequence is fixed, so every start produces the same fortnight ending today. That’s what the dashboard’s charts draw on a fresh server.

The cars a rider sees are real drivers who are online. Nothing on the server invents traffic. To see a car move, sign in as a driver in a second simulator and go online. In the simulator the app has no position, so it stands at the default one, and the driver’s screen drives the car along the route itself at 25 meters a second.

To use your own data:

  • For your own city, change the ten places in DemoRides and in StubGeocoder, and the default position in AppConfig.

  • For a demo with your own cast, edit the list in DemoAccounts.

  • For a production database, do nothing. Neither class writes demo data outside a development profile.

  • To load real history, such as rides from a system you’re replacing, write a one-off job that stores Ride, RideEvent and Payment entities through their repositories the way DemoRides does, or a migration that inserts into ride, ride_event and payment. The statistics read those tables and don’t care who wrote the rows.

The app’s tests use 24 vector tiles of the same waterfront, stored in common/src/test/resources. They aren’t part of the app. Maps.useTiles is the hook that swaps them in.

50.22. Native maps

The sample draws its map with MapView, the vector map that Codename One renders itself. It looks the same on every platform, the app’s bottom sheet and buttons float over it, and its light and dark styles follow the app.

NativeMap shows the platform’s own map instead: Apple MapKit on iOS, and Google Maps or Huawei Map Kit on Android. It has the same MapSurface operations as MapView, and it falls back to a MapView where no provider is available, which includes the simulator, the desktop and the browser. Native maps and providers documents it.

Three changes move Wayline to it.

First, select a provider for each platform with build hints in common/codenameone_settings.properties:

codename1.arg.ios.maps.provider=apple
codename1.arg.android.maps.provider=google

Apple MapKit needs no key. Google Maps needs an API key for each platform, supplied through the build hints the Maps chapter lists.

Second, create the map as a NativeMap in Maps.create. The tile source and style passed to it are what the fallback uses:

/// The platform's own map where the build selected a provider, and the
/// vector map everywhere else.
public static NativeMap createNative(LatLng center, int zoom) {
    NativeMap map = new NativeMap(center, zoom, MvtTileSource.openFreeMap(),
            dark ? MapStyle.dark() : MapStyle.light());
    map.setName("map");
    return map;
}

MapStage.map, the CarMarker constructor and the helper methods of Maps are declared with the type MapView. Change them to MapSurface, which has the camera, marker and line methods they call. The few calls that treat the map as a component, such as repaint and getHeight, go through asComponent().

Third, change how the car moves. CarMarker glides a marker by setting its position twenty times a second. A native provider is told about a marker when it’s added and isn’t told when its position changes, so on a native map the marker has to be taken off and put back:

/// Moves a marker on a map that may be native. A native provider is told
/// about a marker when it is added and not again, so a marker that moved
/// is taken off and put back.
static Marker move(MapSurface map, Marker marker, EncodedImage icon, LatLng position) {
    if (!(map instanceof NativeMap) || !((NativeMap) map).isNativeMap()) {
        marker.setPosition(position);
        return marker;
    }
    map.removeMarker(marker);
    return map.addMarker(new MarkerOptions(position).icon(icon).anchor(0.5f, 0.5f));
}

Do that a few times a second, not twenty: every move is a call into the platform’s map.

The sample hasn’t been built with a native provider, so treat this as the route to take and test it on devices. What you gain and give up:

MapView, as shippedNativeMap with a provider

Keys and accounts

None.

None for Apple MapKit. A key and a billing account for Google Maps, and Huawei’s onboarding for Map Kit.

Look

One style on every platform, in the app’s light and dark colors, with the pins and car drawn from theme.css.

The platform’s map, which users know. Its colors are the provider’s, and a dark app doesn’t make the map dark.

Data

OpenStreetMap, as good as its coverage of your city.

The provider’s data, which often includes more businesses and addresses.

Layering

An ordinary component. The bottom sheet, the chip and the buttons are drawn over it.

A native view embedded in the screen. Test every screen that floats controls over the map, on both platforms.

Offline and tests

Tiles can be bundled with the app, which is how the tests run.

The provider decides what’s cached. In the simulator and in tests you see the fallback, not the native map.

50.23. The database

50.23.1. Engines and where the address comes from

The server runs on SQLite, PostgreSQL, MySQL and MariaDB with the same code. It reads one setting, cn1.datasource.url:

ValueWhat it opens

:memory:

A SQLite database that lives as long as the process. It’s what backend/application-dev.properties and application-test.properties set.

A file path, such as ./target/app.db

A SQLite database in that file.

postgres://user:password@host/database

PostgreSQL.

mysql://user:password@host/database

MySQL, or MariaDB. Which of the two answered is read from the server and not from the URL.

The setting is also read from the environment, as CN1_DATASOURCE_URL and as DATABASE_URL, which is the name a hosting platform usually sets for a database it attaches. backend/application.properties sets the key to ${DATABASE_URL}, so a deployment supplies the address in its environment and no address is committed.

To keep data between restarts while developing, give the dev profile a file:

cn1.datasource.url=./target/app.db

To run against PostgreSQL or MySQL, give the server a URL. Nothing else changes, and there’s no driver to add:

DATABASE_URL=postgres://wayline:[email protected]/wayline backend/server.sh run

The server holds a pool of connections. cn1.datasource.pool.size sets how many: eight for PostgreSQL and MySQL unless set, four for a SQLite file and one for an in-memory database. A request that finds no free connection waits cn1.datasource.pool.borrowTimeoutMillis, ten seconds unless set, and then fails. Every server process has a pool of its own, so the processes times the pool size has to stay under the number of connections the database allows. Chapter 39, Backend data access and transactions covers the pool, and the table of settings in Configuration and profiles lists these keys with the rest.

The sample’s own tests run on the test profile, which is an in-memory SQLite database. Run the server tests against the engine you deploy on before you rely on it there.

50.23.2. The schema

The tables are created by the migration scripts in backend/src/main/resources/db/migration, which run in order when the server starts. Section 39.3, “Schema migrations” describes the rules.

ScriptWhat it creates

V1__accounts.sql

The profile, the preferences, the pending phone codes, the live-channel tickets, the moderation history and the hashed addresses of closed accounts.

V2__drivers.sql

A driver’s state and position, the driving applications and the hours driven.

V3__driver_documents.sql

The photographs behind a driving application.

V4__rides.sql

The rides, their events, and the drivers who passed on each.

V5__payments.sql

Payments, the provider’s customers, saved methods and setups, payout accounts, payouts and the prices.

V6__pricing_row.sql

The one row of prices, marked as not yet set, so that saving prices always updates it and two admins saving at once can’t both try to create it.

The sign-in tables are separate. The security layer creates them because cn1.security.schema.enabled is set, as Section 41.18, “Keeping it in the database” describes.

Five of the six scripts are written once, in SQL that all three engines accept. They use no generated keys and no boolean or timestamp types: an id is text the server makes, a yes or no is a SMALLINT of 0 or 1, and a time is milliseconds in a BIGINT. That’s also how the ORM stores a boolean and a long field, so the entities and the columns agree on every engine.

V3__driver_documents.sql is the exception, and it shows what the per-engine directories are for. A document is stored as text, and it outgrows the 64 KB of MySQL’s TEXT. MySQL needs LONGTEXT, a type the other two don’t have. For that reason the script isn’t in db/migration itself. It exists three times under the same name, in db/migration/sqlite, db/migration/postgresql and db/migration/mysql, and the server runs the one for the engine it’s connected to. MariaDB reads the mysql directory. A version is either one common script or one script for each engine, never both.

50.23.3. Changing the schema later

A change to the schema is a new script with the next version number. The next one is V6, and the two underscores before the description are part of the name. A child seat a rider can ask for is V6__child_seat.sql:

-- V6__child_seat.sql
-- A rider may ask for a child seat. No ride has one until someone asks.
ALTER TABLE ride ADD COLUMN child_seat SMALLINT NOT NULL DEFAULT 0;

A column added to a table that already has rows needs a default, as child_seat has here. ADD COLUMN with a NOT NULL default is accepted by all three engines, so a script that sticks to it stays a common script. When the SQL has to differ, put the script in the three engine directories under one name, as V3 does, and leave it out of db/migration itself.

Add the field to the entity in the same change. The migrations create the columns and the entities read them, and neither is derived from the other. The option to bring a pet is the column of ride the child seat would sit beside, and in Ride it’s one private field:

@Column(nullable = false)
private boolean pets;

The child seat is a childSeat field written the same way, with an isChildSeat and a setChildSeat beside the getter and setter pets has. The field’s name in snake case is the column’s, so childSeat reads child_seat with nothing more said.

A new table gets an entity class of its own in domain as well, as the customers of Cash and accounts do. The server tests start from an empty database and run every migration, so RideFlowTest and the others fail on an entity and a script that disagree.

What happens when the new build starts:

  • Before it accepts a request, the server compares the scripts in the build with the history the database keeps and applies the ones the database hasn’t had, in order.

  • On SQLite and PostgreSQL each script runs in a transaction with the row that records it, so a script that fails leaves nothing behind and the server doesn’t start. MySQL and MariaDB commit each schema change as it runs. A script that fails there is recorded as failed, and the server refuses to migrate until what it left has been removed and repair has been called.

  • Several server processes starting together take a lock in the database, so the script runs once.

  • A database that’s already at the newest version isn’t touched.

Never edit a script that has been applied. The server checks the applied scripts against the ones in the build before it migrates, and refuses to start on a difference. A mistake in V6 that has reached a database is corrected in V7. Before a script has left your own machine, delete the development database and start again. An in-memory database starts from nothing every time.

A script that removes a column should ship one release after the build that stopped reading it. While a deployment replaces its instances one at a time, the old build runs against the new schema.

50.23.4. A column, end to end

The script and the entity field above are the first two of the places a piece of data touches. The option to bring a pet is already in the sample and shows every one, so follow it for the child seat, a flight number or a cost center.

The schema. pets is a SMALLINT column of ride, in V4rides.sql, and of driver_application, in V2drivers.sql. For new data it’s a new script, as V6__child_seat.sql is.

The entities. Ride.pets and DriverApplication.pets are private boolean fields with a @Column, as childSeat is.

The services. Rides.open, the transaction of Rides.request, copies petFriendly from the request to Ride.pets, and Rides.toDto copies it into the ride the app is sent. Because the pet option also decides who is offered the ride, Matcher.pick passes Ride.isPets to Matcher.nearby, which drops every driver whose application doesn’t take pets.

The contract. The value is a component of the record in shared that carries it, petFriendly in RideRequestDto, and of RideDto so the driver sees it. A child seat is a boolean childSeat component beside it in each, with a line for it in the record’s comment. Every place that builds one of those records then passes the new value, and the compiler lists each place that doesn’t.

A component needs nothing else. Both builds regenerate the JSON code for the record.

The endpoint. A new field on an existing call changes no endpoint. A new call is a method on the @RestClient interface and its implementation on the server, and the server’s build fails until the two match.

The app. SettingsForm has the switch, Prefs keeps its value, RiderForm copies it into the request, and DriverForm shows it on the offer. The label is a key in each of the five bundles in src/main/l10n.

The tests. MatchingTest on the server checks that a ride with a pet is offered only to a driver who takes pets.

More data about a person follows the same path through Profile, profile and ProfileDto, about a driver’s car through DriverApplication, driver_application and DriverApplicationDto, and about the service’s prices through Pricing, pricing and PricingDto. A new kind of record gets a table, an entity, a repository, a class in shared, and a service.

50.23.5. Hosting it: A managed database and one binary

A deployment that suits a new service is a managed PostgreSQL and the server’s native binary in a small container or virtual machine, behind the platform’s HTTPS proxy. The steps are the same on any platform that runs a container or a process and attaches a database to it.

Build. backend/server.sh build --native --web runs cn1:backend-package, which writes the binary to backend/target/wayline-server, and cn1:backend-webapp, which stages the browser app in backend/target/webapp. The binary is built for the machine the build runs on, so build on the architecture you deploy to, or use the cross-compiled targets Chapter 47, Backend performance, deployment and limits describes.

Lay it out. The server reads its settings and looks for the browser app in its working directory. Put the binary, application.properties and the webapp directory side by side, as Section 35.1.16, “Hosting the app in the browser” shows, and start the binary from that directory. Leave webapp out and the server is the API alone.

Create the database. Create an empty PostgreSQL database and a user that owns it. The server creates every table at its first start, which takes a user that may create tables. Don’t create anything by hand: a database that has tables and no migration history is refused.

Set the environment. Nothing secret belongs in application.properties, which is committed. A setting is read from the environment under its name in upper case with an underscore for each dot.

VariableWhat it holds

DATABASE_URL

The postgres:// address of the database. Many platforms set it themselves when a database is attached.

PORT

The port to listen on. A platform that sets it wins over cn1.server.port.

CN1_SECURITY_AUTHORIZATIONSERVER_ISSUER

The public https address of the server, without a trailing slash. It goes into every token, and it’s the only origin the browser app may sign in from.

CN1_SECURITY_AUTHORIZATIONSERVER_JWK_KEYS

The files holding the key that signs the tokens. Mount them as secret files. They’re required outside a development profile. Section 41.12, “The authorization server” covers the keys and their rotation.

WAYLINE_ADMIN_EMAIL, WAYLINE_ADMIN_PASSWORD

The first administrator, created at the first start. That account grants the admin role to the rest.

WAYLINE_SMS_PROVIDER, then WAYLINE_SMS_TWILIO_SID, WAYLINE_SMS_TWILIO_TOKEN, WAYLINE_SMS_TWILIO_FROM or the settings of another provider

The text-message provider. twilio when unset. See Section 50.14, “Text messages”.

WAYLINE_PAYMENTS_PROVIDER, WAYLINE_PAYMENTS_STRIPE_SECRET

The payment provider. stripe when unset. See Section 50.13, “Billing”.

The same settings as properties, for a platform that mounts a file instead:

cn1.datasource.url=${DATABASE_URL}
cn1.security.authorizationserver.issuer=https://rides.example.com
wayline.admin.email=[email protected]
wayline.admin.password=${WAYLINE_ADMIN_PASSWORD}
wayline.sms.provider=twilio
wayline.sms.twilio.sid=${WAYLINE_SMS_TWILIO_SID}
wayline.sms.twilio.token=${WAYLINE_SMS_TWILIO_TOKEN}
wayline.sms.twilio.from=+15555550100
wayline.payments.provider=stripe
wayline.payments.stripe.secret=${WAYLINE_PAYMENTS_STRIPE_SECRET}

Leave TLS to the proxy. The platform’s proxy holds the certificate and forwards plain HTTP to the port. Two things follow. The issuer is the address users reach, which is the proxy’s https address and not the container’s. And the server sees every connection coming from the proxy, so the limit on sign-in attempts for each client address would count all users as one. Set cn1.server.forwardHeaders to true and list the proxy’s addresses in cn1.server.trustedProxies, as Section 41.9.2, “Client addresses behind a proxy” describes. A server with no proxy in front terminates TLS itself with cn1.server.tls.certificate and cn1.server.tls.key.

Give the platform a health check. GET /manage/health answers without a token, with 503 while the server is starting or draining. The management endpoints are linked into a packaged server only when cn1.management.enabled is true in backend/application.properties at build time, and outside a development profile they also need cn1.management.token set. Chapter 45, Backend tracing, metrics and management covers both.

Start it. The first start applies the five migrations, creates the sign-in tables, registers the app as a client and creates the first administrator. No demo accounts and no demo rides are written outside a development profile.

Point the apps at it. The hosted browser app uses the page’s own origin and needs nothing. An installed app takes the address from Server address on the welcome screen. To build an app that needs no such step, change the address AppConfig falls back to, and remove the Android clear-text attribute listed in Before it’s a product.

What’s rate limited. SecurityConfig limits registration, the phone codes, the password change, the document uploads, the card setups and the address search under /api/geo. Each search is a request the server makes of the geocoder you configured, so the limit protects that service’s allowance and not only this server.

Before a second instance. A change of ride state, the matching job and the migrations are each safe with several processes on one database. Two things are held in one process’s memory: the open sockets in LiveHub, and the counters of the InMemoryRateLimiter that SecurityConfig gives each rate limit, so every instance allows the full number of attempts.

51. Savor: A food-delivery app from four sides

Savor is a sample app with a server behind it. A customer browses the restaurants that deliver to them, fills a cart and pays. The restaurant accepts the order and cooks it, the nearest courier is offered the delivery, collects it and brings it to the door while the customer follows it on a map, and an administrator runs the service. The app and the server are one Maven project, written in Java on both sides, and the Initializr’s food-delivery template generates it under your own name.

This chapter is the user’s guide: what each of the four kinds of user sees and can do. Chapter 52, Savor: Building on the sample is the other half. It explains how the project is built and what it does differently from Wayline, the ride-hailing sample it grew from.

One app serves all four. The server gives every account a set of roles, and the app opens on the screen that fits them: a customer on the restaurants, a merchant on the restaurant’s order queue, a courier on the delivery screen, an administrator on the operations console. Someone who holds more than one role switches between them from the menu.

RoleWhat it adds

Customer

Every account is a customer. Choose where to deliver to, browse and search the restaurants, build an order, pay, follow it to the door, rate it, tip and keep the receipt.

Merchant

Granted when an administrator approves a restaurant. Accept or reject the orders that arrive, say how long the kitchen needs, mark them ready, pause the restaurant, edit the menu and read the sales.

Courier

Granted when an administrator approves an application to deliver. Go online, accept or decline the deliveries offered, collect and deliver them, and see and cash out what they earned.

Admin

Granted by another administrator. See the service in numbers and charts, approve restaurants and couriers, flag or block accounts, cancel and refund orders, read the payments, and set the prices and the promo codes.

51.1. Trying it

Start the server on its development profile and it creates a set of accounts, all with the password savor-demo, twelve restaurants with their menus, and two weeks of orders so that the charts have something to draw. Section 52.1, “Running it” has the commands.

AccountRole

[email protected], [email protected]

Customers.

[email protected]

A customer an administrator has flagged.

[email protected]

Runs the kitchen of Ember & Crust, one of the twelve restaurants.

[email protected], [email protected]

Approved couriers.

[email protected], [email protected]

Approved couriers who carry the two weeks of past orders.

[email protected]

Has applied to deliver and is waiting for a decision.

[email protected]

Runs the service.

A customer alone can watch an order come all the way. On the development profile a simulated kitchen accepts and cooks the orders of every restaurant that has no merchant, and a simulated courier takes the delivery while no real courier is online. Sign in as the merchant and as a courier in other simulators to play those parts yourself.

No money moves on a development server, which simulates cards unless it’s told to use a payment provider. An order’s total is held on the card when it’s placed and taken when the food arrives. Five numbers behave in five ways:

Card numberWhat happens

4242 4242 4242 4242

Accepted, and every hold and charge succeeds.

4000 0000 0000 0002

Declined when you try to add it.

4000 0000 0000 0341

Accepted and held, then declined when the order arrives.

4000 0000 0000 0119

Accepted and held, then taking the money fails without an answer, so the order’s payment stays pending.

4000 0000 0000 7726

Accepted, and every charge succeeds. A refund is pending at first, and shows as refunded about a minute later.

Any expiry date in the future and any security code work with them. The codes WELCOME10 (10% off an order of $15 or more) and SAVOR5 ($5 off an order of $25 or more) work once per account.

51.2. Getting in

The welcome screen offers to sign in or to create an account. Server address is there for a phone on the same network as a development server: localhost on a phone is the phone, so the app has to be told where the server is. The app in a browser has no such entry: it always talks to the server that hosts it.

The Savor welcome screen with buttons to sign in, to create an account and to set the server address
Figure 286. The welcome screen

A new account asks for a name, an e-mail address, a mobile number and a password, and whether the person also wants to deliver. The mobile number is verified with a code sent as a text message before the first order, because the courier calls it from the door. A development server prints the code on its console and the app shows it.

The form for a new account with fields for name, e-mail, mobile number and password
Figure 287. Creating an account
The verification screen showing the code on screen because a development server sends no text message
Figure 288. Verifying the phone number

The first sign-in on a device asks whether the app may share usage statistics. The answer can be changed in the settings at any time.

The screen that asks whether to share usage statistics, with a button to share them and a button to decline
Figure 289. The usage statistics question

51.3. The customer

The home screen starts with where the food goes. The address under Deliver to is the device’s position until another is chosen, and tapping it searches for a street, a place or a saved address. Under a greeting that follows the time of day are the cuisines, the order to list the restaurants in (nearest, top-rated, lowest fee or fastest) and the restaurants themselves: the ones that deliver to the address, each with its rating, its time to the door and its delivery fee. A restaurant that’s closed or paused says so and still shows its menu.

The customer home screen: the address to deliver to, a greeting, a row of cuisines, the sort choices and the list of restaurants
Figure 290. The home screen
The customer home screen in the dark theme
Figure 291. The home screen in the dark theme

Search finds restaurants by their name, their cuisine or a dish on their menu. Orders lists what’s on its way and what came before, with a button to order a past one again, and Favorites keeps the restaurants marked with a heart.

A restaurant’s page shows its menu by section. A dish with choices — a size, a sauce, extra toppings — opens on a page of its own, which says which choices are required and how many of each may be picked, and adds the dish with a quantity. The cart button at the bottom follows the order’s total. A cart holds the dishes of one restaurant: adding a dish from another asks first and starts again.

The checkout lists the dishes, takes a note for the kitchen, the card or cash that pays, a promo code and a tip for the courier, and shows the total as the server prices it: the food, the delivery fee, the service fee, a small-order fee for a small order, the tax, the discount and the tip. The tip chosen is remembered for the next order.

The checkout with the dish, a note, the card that pays, a promo code field, the tip choices and the total broken into fees
Figure 292. The checkout

Place order holds the total on the card and opens the order on a map. The steps across the bottom follow it: waiting for the restaurant, being prepared, ready, on its way and delivered. Until the restaurant accepts it the order can be cancelled, and the hold on the card is let go. Once a courier has it the map shows the courier’s position and the time to the door, and the courier can be called or texted.

The order screen just after placing it: the restaurant and the door on a map, the step reading Waiting for the restaurant, and a button to cancel
Figure 293. Waiting for the restaurant
The order screen while the courier rides to the door, with the courier on the map and the time left
Figure 294. On its way

When the food arrives the order asks for a rating and offers the receipt. The card is charged then, for the total that was held.

The order screen once it’s delivered, with five stars to rate it and a button for the receipt
Figure 295. Delivered

51.3.1. Wallet and receipts

The wallet holds the account’s cards and cash. Tapping one makes it the default, which the checkout starts from. A card is added on a form of its own, or on the payment provider’s page when the server uses one, so its number never reaches the app or the server.

The wallet with one saved card marked as the default, cash, and a button to add a card
Figure 296. The wallet

A receipt shows what was paid, part by part, and takes a tip for the courier afterward, once.

51.4. The merchant

A merchant opens on their restaurant’s queue. A new order arrives with a sound and a vibration, without the screen being reloaded, and the queue keeps the orders that still need the kitchen at the top. On a tablet or a desktop the order opens beside the queue; on a phone it opens on a screen of its own.

The restaurant’s order queue with a new order at the top, its dishes summarized and a badge reading New
Figure 297. The order queue

An order shows its dishes with their choices, the customer’s note and the total of the food. Accept takes it with the time the kitchen needs, which the customer sees, and sends for a courier at once, so that one is on the way while the food cooks. Reject asks for a reason, which the customer reads, and lets the hold on the card go. Mark ready tells the courier to collect it: a courier can’t take an order the kitchen hasn’t finished.

An order on the merchant’s screen with its dishes, the note No onions, a choice of preparation time and buttons to accept or reject it
Figure 298. An order as the kitchen sees it

The switch at the top pauses the restaurant: customers still see it, and can’t order. The menu editor adds and renames sections, adds dishes with a photograph, a price and choices, and marks a dish sold out for the day. Sales totals what the restaurant earned, after the service’s commission.

Anyone can ask for a restaurant to be listed, from the menu of the customer’s home screen. It waits, unseen by customers, until an administrator approves it, and the account that asked then becomes its merchant.

51.5. The courier

Anyone can apply to deliver, from the menu of the customer’s home screen.

51.5.1. Applying to deliver

The application asks for the courier’s details, the vehicle, and five photographs: an identity document, the driving license, a selfie, the vehicle registration and the insurance. Each can be taken with the camera or picked from the gallery, and the application can be left and finished later.

A step of the application to deliver, with a card for each document and buttons to retake a photo or pick one from the gallery
Figure 299. The documents of an application

Once sent, it waits for an administrator. A rejection carries a reason, and the applicant can correct the application and send it again.

The screen an applicant sees while the application is under review, with the steps that follow
Figure 300. Waiting for a decision

51.5.2. Delivering

An approved courier opens on the delivery screen. Go online makes them one of the couriers the server offers deliveries to: those near the restaurant, as soon as its kitchen accepts an order.

The delivery screen while offline: the day’s earnings, a badge reading Offline and the button to go online
Figure 301. Offline

An offer shows what the courier is paid — the delivery fee and the tip — the restaurant, the distance and a countdown. Declined or left to run out, it goes to the next courier.

The courier screen with a delivery request: the pay, a countdown, the restaurant and the door, and buttons to accept or decline
Figure 302. An offer

An accepted delivery is two legs. The first leads to the restaurant, where a button tells the kitchen the courier is waiting. Collecting the food works once the kitchen has marked the order ready, and the second leg leads to the door, with the customer’s name, the address, the note and, for an order paid in cash, the amount to collect. Delivered ends it.

The courier screen on the second leg, with the route to the door and a button reading Delivered
Figure 303. On the way to the door

51.5.3. Earnings

The earnings screen shows the balance that can be cashed out, the totals for today, this week and this month, and a chart of the last two weeks.

The earnings screen with the balance ready to cash out, the totals for today, this week and this month, and a chart of the last two weeks
Figure 304. Earnings

51.6. The administrator

The operations console starts on a dashboard: what needs an answer — restaurants and couriers waiting for approval, flagged accounts — above the service as it’s now, and charts of orders and their value over the last two weeks.

The admin dashboard on a phone: alerts for applications to review above numbers describing the service right now
Figure 305. The dashboard
Two bar charts on the admin dashboard, one of orders per day and one of their value per day
Figure 306. The trends

Restaurants lists them by status: waiting, approved, suspended, or rejected. A waiting one is approved or rejected with a reason; an approved one can be suspended, which takes it off the customers' lists, and let back later. Couriers holds the applications to deliver, each with its documents.

An application to deliver as an administrator reads it, with the applicant’s details and the vehicle
Figure 307. An application to deliver

People finds any account. An account can be flagged or blocked with a reason that’s kept in its history, and a blocked account can neither sign in nor be offered a delivery.

An account as an administrator sees it, with its numbers, its roles, the moderation buttons and the history
Figure 308. An account

Orders lists every order with its state. One that hasn’t arrived can be cancelled, which lets the hold go; one that has can be refunded in full or in part. Payments lists each charge, Pricing sets the delivery fee and its price by distance, the small-order fee, the service fee, the commission and the tax, and Promos creates and ends promo codes. The live map shows the couriers who are online.

On a tablet or a desktop the console lays its sections down the left side and opens what’s picked beside its list.

51.7. Settings

The settings hold the account — its name, phone number and password — the cards, the language, the theme, notifications and the usage statistics. The app is in English, Spanish, French, German and Hebrew, and in Hebrew it’s laid out from right to left.

The translations are machine-generated samples, and no native speaker has reviewed them. Have them checked before you ship the app in those languages.
The settings screen with the account’s profile, verified phone number and password
Figure 309. The settings
The settings screen in the dark theme
Figure 310. The settings in the dark theme
The settings screen in Hebrew, laid out from right to left
Figure 311. The settings in Hebrew
The privacy section of the settings, with the switch for usage statistics
Figure 312. Usage statistics

51.8. In a browser

The server can host the app itself: open the server’s address in a browser and the same app loads there, signs in against that server and opens its live channel to it. A browser gives a page less than a phone gives an app, and the app says so where it matters. Calling and texting a courier are offered only where the device can dial, and the restaurants listed are those near a default address when the browser won’t say where it is.

52. Savor: Building on the sample

Savor began as a copy of Wayline and kept most of what isn’t about rides: the module layout, the accounts and sign-in, the cards and the payment provider, text messages, push notifications, the live channel, the map, the operations console and hosting the app in a browser. This chapter covers what a food-delivery service changes. For the parts the two share, it points at the Wayline chapter, which is true of Savor with the names swapped.

52.1. Running it

The project is in scripts/savor, and the Initializr generates it under your own package and name. Start the server on the development profile, which seeds the demo accounts and restaurants and simulates the cards, the kitchens and a courier:

CN1_PROFILE=dev backend/server.sh run

Then run the app in the simulator, from the project’s directory:

mvn verify -Psimulator -DskipTests -Dcodename1.platform=javase

backend/server.sh run --web builds the app for a browser as well and serves it at http://localhost:8080/. Running on a device, and the compiled server, work as Section 50.1, “Running it” describes.

52.2. The modules

The three modules are Wayline’s: shared holds the contract, the data transfer objects and the @RestClient interfaces both sides compile against; common is the app; backend is the server. The backend’s packages follow the domain:

PackageWhat it holds

catalog

Restaurants, their menus and photographs, the search that lists the restaurants that deliver to a point, and applications to list a restaurant.

order

Carts priced into quotes, orders and their state machine, promo codes, saved addresses, the order history and the simulated kitchen.

delivery

Deliveries and their state machine, offers to couriers and the simulated courier.

courier, onboarding

Couriers' shifts and earnings, and applications to deliver with their documents. Wayline’s driver code under new names.

pay, sms, push, live, account, geo, admin

Taken from Wayline and adapted where an order differs from a ride.

52.3. An order and its delivery

A ride is one thing that moves from requested to finished. An order is two. The order is what the customer bought and the kitchen cooks, the delivery is what a courier carries, and each has its own states:

OrderDelivery

PLACED, then ACCEPTED or REJECTED by the kitchen, READY, PICKED_UP, DELIVERED; or cancelled by the customer or an administrator, or NO_COURIERS

REQUESTED, OFFERED to a courier, ACCEPTED, ARRIVED at the restaurant, IN_PROGRESS to the door, COMPLETED; or cancelled, or NO_COURIERS

The delivery is Wayline’s ride, almost unchanged: it picks up at the restaurant and drops off at the door. Keeping it that way let the whole courier side — offers, shifts, the moving marker, earnings, the guards on two answers at once — come across without being rewritten.

What couples the two is when a delivery starts. A customer places an order, and the card is held:

/// Places an order: prices it from the menu, holds the total on the card,
/// and writes it. A hold whose order could not be written is let go.
public OrderDto place(String customer, CartDto cart) throws IOException {
    String id = attemptOf(cart);
    CustomerOrder already = find(id);
    if (already != null) {
        return placedBefore(customer, already);
    }
    Quotes.Priced priced = quotes.quote(customer, cart);
    Restaurant restaurant = priced.restaurant;
    if (!Quotes.open(restaurant, quotes.minuteOfDay(System.currentTimeMillis()))) {
        throw new ResponseStatusException(409, restaurant.getName()
                + " is not taking orders right now");
    }
    if (priced.quote.subtotalCents() < restaurant.getMinimumCents()) {
        throw new ResponseStatusException(400, restaurant.getName()
                + " needs a bigger order");
    }
    if (cart.promoCode() != null && cart.promoCode().trim().length() > 0
            && priced.promo == null) {
        throw new ResponseStatusException(400, priced.quote.promoMessage());
    }
    // The same refusals store() makes under its locks, asked first without
    // them so an order that could never be accepted puts no hold on the
    // card and costs no call to the payment processor. store() still asks
    // again: two orders placed at once both pass here.
    eligible(customer);
    String[] method = payments.choose(customer, cart.paymentMethodId());
    String hold = payments.authorize(id, customer, method[0], priced.quote.totalCents(),
            priced.quote.currency());
    try {
        attempt(() -> store(id, customer, cart, priced, method, hold));
    } catch (IOException | RuntimeException failed) {
        CustomerOrder raced = find(id);
        if (raced != null && customer.equals(raced.getCustomer())) {
            // The same checkout sent twice at once: the other one wrote the
            // order. Its hold was asked for under the same key and may be
            // this very one, so it is not let go.
            return view(customer, false, id);
        }
        // Nothing was written, so the hold is let go by its reference.
        payments.releaseHold(id, hold);
        throw failed;
    }
    CustomerOrder order = find(id);
    tell(order);
    return view(customer, false, id);
}

/// The order's id: the checkout's own attempt id when the app sent one, so
/// a placement sent again after its answer was lost finds the order it
/// wrote instead of writing and charging another. Anything not shaped like
/// a server id gets a fresh one.
private static String attemptOf(CartDto cart) throws IOException {
    String attempt = cart.attemptId();
    if (attempt == null || attempt.length() != 32) {
        return Ids.next();
    }
    for (int iter = 0; iter < attempt.length(); iter++) {
        char c = attempt.charAt(iter);
        if (!(c >= '0' && c <= '9' || c >= 'a' && c <= 'f')) {
            return Ids.next();
        }
    }
    return attempt;
}

/// The answer to a checkout placed again: the order it already wrote. An
/// id another customer's order holds is refused without saying whose.
private OrderDto placedBefore(String customer, CustomerOrder order) throws IOException {
    if (!customer.equals(order.getCustomer())) {
        throw new ResponseStatusException(409, "Start the checkout again");
    }
    return view(customer, false, order.getId());
}

/// The refusals [#store] makes, without its locks. See [#place].
@Transactional(readOnly = true)
private Void eligible(String customer) {
    if (!enabled(customer)) {
        throw new ResponseStatusException(403, "This account is blocked");
    }
    if (orders.countByCustomerAndStateIn(customer, ACTIVE) >= MAX_ACTIVE) {
        throw new ResponseStatusException(409, "You already have " + MAX_ACTIVE
                + " orders on the way");
    }
    Profile profile = profiles.findById(customer);
    if (profile == null || !profile.isPhoneVerified()) {
        throw new ResponseStatusException(403, "Verify your phone number before you order");
    }
    return null;
}

@Transactional
private Void store(String id, String customer, CartDto cart, Quotes.Priced charged,
        String[] method, String hold) throws IOException {
    Quotes.Priced priced = charged;
    // Held first, so two orders placed at once count each other and not
    // just what had committed before either began.
    profiles.hold(customer);
    // The card was held with no transaction open, and that can take a
    // while: the account may have been blocked, or the restaurant paused
    // or suspended, since the checks before it. Asked again under the
    // locks those changes take, a refusal here lets the hold go.
    if (!enabled(customer)) {
        throw new ResponseStatusException(403, "This account is blocked");
    }
    Restaurant restaurant = restaurants.hold(priced.restaurant.getId()) == 0 ? null
            : restaurants.findById(priced.restaurant.getId());
    if (restaurant == null
            || !Quotes.open(restaurant, quotes.minuteOfDay(System.currentTimeMillis()))) {
        throw new ResponseStatusException(409, priced.restaurant.getName()
                + " is not taking orders right now");
    }
    if (orders.countByCustomerAndStateIn(customer, ACTIVE) >= MAX_ACTIVE) {
        throw new ResponseStatusException(409, "You already have " + MAX_ACTIVE
                + " orders on the way");
    }
    Profile profile = profiles.findById(customer);
    if (profile == null || !profile.isPhoneVerified()) {
        // The courier calls this number from the door.
        throw new ResponseStatusException(403, "Verify your phone number before you order");
    }
    // The menu was read before the card was held. Priced again under the
    // restaurant's lock, which every dish edit takes too (Restaurants.editing):
    // a dish now sold out or gone throws, a price that moved refuses, and either
    // way the hold is let go rather than charging for a menu that has changed.
    Quotes.Priced again = quotes.quote(customer, cart);
    if (again.quote.totalCents() != charged.quote.totalCents()) {
        throw new ResponseStatusException(409, "The menu changed while you were paying."
                + " Check your cart and try again");
    }
    // The minimum may have been raised while the card was held, and it
    // leaves the total alone, so the comparison above does not see it.
    if (again.quote.subtotalCents() < restaurant.getMinimumCents()) {
        throw new ResponseStatusException(400, restaurant.getName()
                + " needs a bigger order");
    }
    // The card may have been removed while it was held: Payments.remove
    // takes the profile lock held here and found no active order then.
    // Asked again, a card that is gone refuses with 400.
    payments.choose(customer, method[0]);
    priced = again;
    QuoteDto quote = priced.quote;
    long now = System.currentTimeMillis();
    CustomerOrder order = new CustomerOrder();
    order.setId(id);
    order.setCustomer(customer);
    order.setRestaurantId(priced.restaurant.getId());
    order.setRestaurantName(priced.restaurant.getName());
    order.setState(OrderState.PLACED);
    order.setSubtotalCents(quote.subtotalCents());
    order.setDeliveryFeeCents(quote.deliveryFeeCents());
    order.setServiceFeeCents(quote.serviceFeeCents());
    order.setSmallOrderCents(quote.smallOrderCents());
    order.setTaxCents(quote.taxCents());
    order.setDiscountCents(quote.discountCents());
    order.setTipCents(quote.tipCents());
    order.setTotalCents(quote.totalCents());
    order.setCommissionCents(priced.commissionCents);
    order.setCurrency(quote.currency());
    order.setPromoCode(priced.promo == null ? "" : priced.promo.getCode());
    order.setDropoffLat(cart.dropoffLat());
    order.setDropoffLng(cart.dropoffLng());
    order.setDropoffAddress(Text.required(cart.dropoffAddress(), 255, "the address"));
    order.setNote(Text.optional(cart.note(), 255, "the note"));
    order.setMethodId(method[0]);
    order.setMethodLabel(method[1]);
    order.setAuthorizationRef(hold);
    order.setPaymentStatus(Payments.CASH.equals(hold) ? Payments.PENDING : Payments.AUTHORIZED);
    order.setPrepMinutes(priced.restaurant.getPrepMinutes());
    order.setPlacedAt(Instant.ofEpochMilli(now));
    order.setUpdatedAt(Instant.ofEpochMilli(now));
    order.setReason("");
    orders.insert(order);
    for (int iter = 0; iter < priced.lines.size(); iter++) {
        OrderLineDto dto = priced.lines.get(iter);
        OrderLine line = new OrderLine();
        line.setId(Ids.next());
        line.setOrderId(id);
        line.setDishId(dto.dishId());
        line.setName(dto.name());
        line.setOptions(dto.options());
        line.setQuantity(dto.quantity());
        line.setUnitCents(dto.unitCents());
        line.setLineCents(dto.lineCents());
        line.setPosition(iter);
        lines.insert(line);
    }
    if (priced.promo != null) {
        // Keyed by code and account, so a second order racing this one
        // with the same code fails its insert and is rolled back.
        if (promoUses.existsById(Identifier.of(priced.promo.getCode(), customer))) {
            throw new ResponseStatusException(409, "You have already used that code");
        }
        PromoUse use = new PromoUse();
        use.setCode(priced.promo.getCode());
        use.setUsername(customer);
        use.setOrderId(id);
        promoUses.insert(use);
    }
    events.record(id, OrderState.PLACED, customer);
    return null;
}

No courier is looked for yet. A courier sent to a restaurant that then turns the order down has wasted a trip, so the delivery is created when the kitchen accepts, in the same transaction:

/// The kitchen takes an order: it says how long it needs, and the order's
/// delivery starts looking for a courier in the same transaction.
public OrderDto accept(String actor, String restaurantId, String id, int prepMinutes)
        throws IOException {
    if (prepMinutes < 1 || prepMinutes > 180) {
        throw new ResponseStatusException(400, "Say how many minutes it needs");
    }
    attempt(() -> accepted(actor, restaurantId, id, prepMinutes));
    tell(find(id));
    // Once committed, as an offer is always made: a courier asked from
    // inside the transaction could be shown an order that then rolled back.
    deliveries.search(id);
    return view(actor, false, id);
}

@Transactional
private Void accepted(String actor, String restaurantId, String id, int prepMinutes)
        throws IOException {
    CustomerOrder order = kitchens(restaurantId, id);
    if (orders.accept(id, OrderStateMachine.sources(OrderState.ACCEPTED),
            OrderState.ACCEPTED, prepMinutes, Instant.now()) != 1) {
        throw new ResponseStatusException(409, "That order is "
                + describe(order.getState()));
    }
    events.record(id, OrderState.ACCEPTED, actor);
    deliveries.dispatch(find(id), restaurants.findById(restaurantId));
    return null;
}
/// Creates the delivery for an order the kitchen has just accepted, with the
/// order's id, from the restaurant to the order's door. Runs inside the
/// transaction that accepts the order, so the two commit together; [#tick]
/// finds the delivery a courier from then on, while the kitchen cooks.
///
/// The courier is paid the delivery fee and the tip, so that is the fare a
/// courier is offered.
public void dispatch(CustomerOrder order, Restaurant restaurant) throws IOException {
    long now = System.currentTimeMillis();
    Delivery delivery = new Delivery();
    delivery.setId(order.getId());
    delivery.setState(DeliveryState.REQUESTED);
    delivery.setCustomer(order.getCustomer());
    delivery.setCourier("");
    delivery.setPickupLat(restaurant.getLat());
    delivery.setPickupLng(restaurant.getLng());
    delivery.setPickupAddress(address(restaurant.getName() + ", " + restaurant.getAddress()));
    delivery.setDropoffLat(order.getDropoffLat());
    delivery.setDropoffLng(order.getDropoffLng());
    delivery.setDropoffAddress(address(order.getDropoffAddress()));
    double meters = Quotes.roadMeters(restaurant.getLat(), restaurant.getLng(),
            order.getDropoffLat(), order.getDropoffLng());
    delivery.setDistanceMeters(meters);
    delivery.setDurationSeconds(meters / Quotes.METERS_PER_SECOND);
    delivery.setFareCents(order.getDeliveryFeeCents());
    delivery.setFeeCents(order.getDeliveryFeeCents());
    // A tip given at checkout is part of the order's total, taken with it,
    // so it is in the courier's share. The delivery's own tip is the one
    // given after it arrives, charged on its own: counting the checkout
    // tip there too would pay it to the courier twice.
    delivery.setTipCents(0L);
    delivery.setCourierCents(order.getDeliveryFeeCents() + order.getTipCents());
    delivery.setCurrency(order.getCurrency());
    delivery.setMethodId(order.getMethodId());
    delivery.setMethodLabel(order.getMethodLabel());
    delivery.setPaymentStatus(order.getPaymentStatus());
    delivery.setNote(order.getNote());
    delivery.setRequestedAt(Instant.ofEpochMilli(now));
    delivery.setUpdatedAt(Instant.ofEpochMilli(now));
    delivery.setSearchUntil(Instant.ofEpochMilli(now + searchMillis));
    deliveries.insert(delivery);
    event(order.getId(), DeliveryState.REQUESTED, "");
}

The delivery shares the order’s id, so either side can find the other without a join table. From then on the couriers are asked while the kitchen cooks, and the order follows its delivery: the courier collecting the food moves the order to PICKED_UP, and only from READY, so nobody leaves with an order the kitchen has not finished; the delivery completing moves the order to DELIVERED. A delivery that finds no courier ends the order with NO_COURIERS and lets the hold go.

Every move of either state is a conditional update that names the states it may come from, so two answers at the same moment can’t both win — a customer cancelling while the kitchen accepts, or two couriers taking one offer. It’s the pattern Section 50.6.1, “Two answers at the same moment” explains:

private boolean tryMove(String id, DeliveryState to, String actor, String ownerField,
        String newCourier, Long newOfferExpiresAt) throws IOException {
    DeliveryState[] sources = DeliveryStateMachine.sources(to);
    if (sources.length == 0) {
        return false;
    }
    Instant now = Instant.now();
    int moved;
    if (newOfferExpiresAt != null) {
        moved = deliveries.offer(id, sources, to, now, newCourier,
                Instant.ofEpochMilli(newOfferExpiresAt.longValue()));
    } else if (CUSTOMER.equals(ownerField)) {
        moved = deliveries.moveAsCustomer(id, sources, to, now, actor);
    } else if (!COURIER.equals(ownerField)) {
        moved = deliveries.moveByServer(id, sources, to, now);
    } else if (newCourier != null) {
        moved = deliveries.giveBack(id, sources, to, now, actor, newCourier);
    } else if (DeliveryState.ACCEPTED == to) {
        // An offer that has lapsed cannot be taken, even in the moment
        // before the sweep takes it back.
        moved = deliveries.takeOffer(id, sources, to, now, actor);
    } else {
        moved = deliveries.moveAsCourier(id, sources, to, now, actor);
    }
    if (moved != 1) {
        return false;
    }
    event(id, to, actor);
    return true;
}

52.4. Hold now, charge on arrival

A rider pays at the end of a ride, for a fare known by then. A customer pays for food before anyone cooks it, but shouldn’t be charged for an order that never arrives. The card is therefore authorized for the total when the order is placed and captured when it’s delivered:

/// Holds an order's total on the customer's card as the order is placed,
/// with no transaction open. Nothing is taken until the order arrives
/// ([#settle]); an order that never does lets the hold go ([#release]).
///
/// @return the hold's reference, or [#CASH] for an order paid in cash
/// - `ResponseStatusException` 402: when the card was refused
public String authorize(String orderId, String username, String methodId, long amountCents,
        String currency) throws IOException {
    if (CASH.equals(methodId)) {
        return CASH;
    }
    String[] references = chargeable(username, methodId);
    if (references == null) {
        throw new ResponseStatusException(402, "The card is no longer on the account");
    }
    try {
        return cut(provider.authorize("order-" + orderId, references[0], references[1],
                amountCents, currency, "Savor order"), 64);
    } catch (PaymentDeclinedException declined) {
        throw new ResponseStatusException(402, declined.getMessage());
    } catch (IOException unknown) {
        throw unavailable("card check", unknown);
    }
}

The provider interface Wayline’s billing chapter describes gained the two calls that make it possible, authorize and capture, and a release for a hold that is let go:

public interface PaymentProvider {
    /// `simulated` or `stripe`: what the app is told, so it knows how to add a
    /// card.
    String name();

    /// Opens the processor's record of a customer and returns its reference.
    String createCustomer(String username, String displayName) throws IOException;

    /// Deletes the processor's record of a customer, and the cards saved to it
    /// with it. A record that is already gone is deleted: this is asked again
    /// when the first answer was lost.
    void forgetCustomer(String customer) throws IOException;

    /// Begins saving a card to `customer`. `setupId` is the server's own id
    /// for the attempt, for the processor to hand back.
    Setup startCardSetup(String customer, String setupId) throws IOException;

    /// Finishes a setup and returns the card it saved.
    ///
    /// @param reference what [#startCardSetup] returned as the setup's reference
    /// @param typed the card as typed into the app, for a processor whose setup
    ///     is not hosted; ignored by one whose setup is
    /// - `PaymentDeclinedException`: when the card was refused or the setup was
    ///   not finished
    Card finishCardSetup(String customer, String reference, CardDto typed) throws IOException;

    /// Takes a saved card off `customer`, so that it can't be charged again.
    /// A card that is already off, or gone, is detached: this is asked again
    /// when the first answer was lost.
    ///
    /// @param token what [#finishCardSetup] returned as the card's token
    void detachCard(String customer, String token) throws IOException;

    /// Charges a saved card with its owner absent.
    ///
    /// @param key names this charge and no other. A processor asked twice with
    ///     the same key charges once, so a request repeated after a timeout
    ///     cannot take the money twice.
    /// @return the processor's reference for the charge
    /// - `PaymentDeclinedException`: when the card was refused
    /// - `IOException`: when the processor could not be asked
    String charge(String key, String customer, String token, long amountCents, String currency,
            String description) throws IOException;

    /// Returns `amountCents` of a charge to the card it came from.
    ///
    /// A processor may take the refund and only later say whether the bank
    /// returned the money: such a refund comes back [Refund#pending], and is
    /// asked about with [#refundStatus] until it has an answer.
    ///
    /// @return the refund as the processor took it
    /// - `IOException`: when the processor could not be asked, or refused the
    ///   refund outright
    Refund refund(String chargeReference, long amountCents) throws IOException;

    /// What became of a refund that was [Refund#pending]: [#REFUND_SUCCEEDED],
    /// [#REFUND_PENDING] while the processor still does not know, or
    /// [#REFUND_FAILED] when the money did not go back.
    String refundStatus(String refundReference) throws IOException;
    /// Holds `amountCents` on a saved card without taking it, for an order
    /// that is paid for only once it arrives. Keyed as [#charge] is.
    ///
    /// @return the processor's reference for the hold, for [#capture] or [#release]
    /// - `PaymentDeclinedException`: when the card was refused
    String authorize(String key, String customer, String token, long amountCents,
            String currency, String description) throws IOException;
    /// Takes `amountCents`, at most what was held, from a hold. A hold that was
    /// already captured is captured: this is asked again when the first answer
    /// was lost.
    void capture(String reference, long amountCents) throws IOException;
    /// Lets a hold go, so the money is the cardholder's again. A hold that is
    /// already let go is released.
    void release(String reference) throws IOException;
  • Placed: Payments.authorize holds the total. A refused card answers 402 and nothing is written. An order that couldn’t be written lets its hold go at once.

  • Rejected or cancelled: Payments.release lets the hold go. Nothing was taken, so there is nothing to refund.

  • Delivered: Payments.settle captures the hold. A capture can still fail — a hold expires, or a bank declines then — and the receipt then says so, for an administrator to follow up.

  • After delivery: a tip is a charge of its own; a refund, full or partial, is made against the captured payment.

The receipt is kept with the delivery. Before a delivery exists, a customer’s receipt is built from the order itself and shows the hold.

With Stripe, a hold is a PaymentIntent created with manual capture. Card holds expire after about seven days, far longer than any meal takes. Turning Stripe on, and the hosted page that keeps a card number away from the server, are exactly as Section 50.13, “Billing” describes.

52.5. Restaurants near the door

A rider is matched to the nearest driver. A customer chooses a restaurant, from the ones that deliver to their door. The search takes a box around the point from the database and then measures each restaurant in it, as Wayline does to find the drivers near a pickup:

/// The approved restaurants that deliver to a point, filtered by cuisine and
/// by a word in the name, the cuisine or a dish, and sorted.
@Transactional(readOnly = true)
public List<RestaurantSummaryDto> nearby(String viewer, double lat, double lng,
        String cuisine, String text, String sort) throws IOException {
    if (!Geo.isPoint(lat, lng)) {
        throw new ResponseStatusException(400, "Choose where to deliver to");
    }
    double straight = Quotes.MAX_METERS / Quotes.ROAD_FACTOR;
    double dLat = straight / Geo.METERS_PER_DEGREE;
    double dLng = dLat / Math.max(0.01d, Math.cos(Math.toRadians(lat)));
    List<Restaurant> box = restaurants.inBox(APPROVED, lat - dLat, lat + dLat, lng - dLng,
            lng + dLng);
    String word = text == null ? "" : text.trim();
    Set<String> dishMatches = word.length() == 0 ? Collections.<String>emptySet()
            : dishMatches(box, word);
    Set<String> kept = favoriteIds(viewer);
    PricingDto pricing = quotes.pricing();
    int minute = quotes.minuteOfDay(System.currentTimeMillis());
    List<RestaurantSummaryDto> out = new ArrayList<RestaurantSummaryDto>();
    for (int iter = 0; iter < box.size(); iter++) {
        Restaurant restaurant = box.get(iter);
        if (cuisine != null && cuisine.length() > 0
                && !cuisine.equalsIgnoreCase(restaurant.getCuisine())) {
            continue;
        }
        if (word.length() > 0 && !contains(restaurant.getName(), word)
                && !contains(restaurant.getCuisine(), word)
                && !dishMatches.contains(restaurant.getId())) {
            continue;
        }
        double meters = Quotes.roadMeters(restaurant.getLat(), restaurant.getLng(), lat, lng);
        if (meters > Quotes.MAX_METERS) {
            continue;
        }
        out.add(summary(restaurant, meters, pricing, minute,
                kept.contains(restaurant.getId())));
    }
    sort(out, sort);
    return out;
}

Couriers are found the same way, near the restaurant rather than the customer, because the restaurant is where they go first.

52.6. Prices

order/Quotes prices a cart, and does so on the server alone: the app shows the quote it’s given and sends only the dishes, their choices, the promo code and the tip. The total is:

  • The food, from the menu as it’s when the order is placed, with each dish’s choices checked against its groups' minimum and maximum.

  • The delivery fee, a base plus a price per kilometer by road from the restaurant, times a surge an administrator can raise.

  • A service fee, a percentage of the food.

  • A flat small-order fee for food under a threshold.

  • Tax, a percentage of the food after the discount.

  • A promo code’s discount, once per account.

  • The tip.

An administrator sets the fees, the commission and the tax under Pricing. The commission is what the service keeps of the food; the merchant’s sales show the rest.

52.7. Merchants

Applying to list a restaurant creates it waiting for approval, owned by the account that asked:

/// Asks for a restaurant to be listed. It waits, unseen by customers, for
/// an admin to approve it; the applicant then joins its staff and gets the
/// merchant role. One application at a time per account.
@Transactional
public RestaurantDto apply(String username, RestaurantEditDto form) throws IOException {
    // Two submissions at once would both find no application below and
    // both insert one; holding the profile first makes the second wait
    // and then see the first.
    profiles.hold(username);
    Restaurant last = restaurants.findFirstByApplicantOrderByCreatedAtDesc(username);
    if (last != null && !Catalog.REJECTED.equals(last.getStatus())) {
        throw new ResponseStatusException(409, Catalog.PENDING.equals(last.getStatus())
                ? "Your application is waiting for review" : "You already have a restaurant");
    }
    Restaurant restaurant = new Restaurant();
    restaurant.setId(Ids.next());
    restaurant.setStatus(Catalog.PENDING);
    restaurant.setApplicant(username);
    restaurant.setReason("");
    restaurant.setPhotoId("");
    long now = System.currentTimeMillis();
    restaurant.setCreatedAt(Instant.ofEpochMilli(now));
    restaurant.setUpdatedAt(Instant.ofEpochMilli(now));
    fill(restaurant, form);
    restaurants.insert(restaurant);
    return catalog.detail(restaurant, username, 0d, 0d, true);
}

Approving it grants the account the merchant role. Everything a merchant does is under /api/merchant/restaurants/{id}/…​, and each request checks that the account is a merchant of that restaurant, so one restaurant’s staff can’t read another’s orders. The rules are in the same table as the rest of the server’s:

.authorizeHttpRequests(auth -> auth
        .requestMatchers(AntPathRequestMatcher.antMatcher("POST",
                "/api/account/register")).permitAll()
        .requestMatchers("/api/courier/**").hasRole(Roles.COURIER)
        .requestMatchers("/api/admin/**").hasRole(Roles.ADMIN)
        .requestMatchers("/api/merchant/**").hasRole(Roles.MERCHANT)
        .anyRequest().authenticated())

The merchant’s screen is built on the operations console’s Console, so it’s a list beside a detail on a wide screen and a list that opens a screen per order on a phone. A new order reaches it as a frame on the live channel, which makes it read the queue again: the frames say what changed, never the data, as in Wayline.

Menu photographs are uploaded the way couriers' documents are, stored by the server and served from it, so the seed data carries its own photographs rather than pointing at someone else’s site.

52.8. Simulated kitchens and couriers

A development server simulates the two people a customer would otherwise wait for. order/DemoKitchen accepts, cooks and readies the orders of each restaurant that has no merchant, and delivery/DemoFleet takes deliveries while no real courier is online. Both are on only for the development profile, the way the simulated cards are: the test profile turns them off, because the tests play the kitchen and the courier themselves. A restaurant with a merchant is left to its staff, and the simulated courier stands aside while a real one is online.

52.9. Tests

mvn -pl shared,backend -Dcodename1.platform=backend test
mvn -pl shared,backend -Dcodename1.platform=backend test -Dcn1.backend.compiledTests=true
./run-e2e.sh
./run-web-e2e.sh

The backend tests run the server on the JVM and then compiled, against the order and delivery state machines, the holds and captures, the quotes and promo codes and who may call what. run-e2e.sh starts a server on the test profile and drives the app in the simulator through every role — an order placed, accepted, collected and delivered, a card held and charged, a tip and a refund — taking the screenshots in the user’s guide. run-web-e2e.sh does the same for the app in a browser.

52.10. Making it yours

The ways to make Wayline your own apply here too: the name, icon and colors, the languages, the text-message and push providers, the database, hosting. A few apply to food in particular:

  • One restaurant or a small chain. Ordering and delivery under the restaurant’s own name, which Section 52.11, “Making it yours: A restaurant’s own delivery service” describes.

  • Pickup. An order with no delivery is one the kitchen hands over itself. Mark the order as collected, skip dispatch when the kitchen accepts it, and let the merchant move it from READY to DELIVERED, which captures the hold.

  • Scheduled orders. Store the time the customer wants the food, and accept the order for the kitchen only when its preparation time before that’s reached.

  • Before it’s a product. A real service needs restaurant payouts, tax rules for the places it sells in, menus that change by the hour, allergens and age checks. None of them are in the sample.

52.11. Making it yours: A restaurant’s own delivery service

A marketplace takes a share of every order and keeps the customer. A restaurant, or a chain of a few, that runs its own ordering and delivery keeps both: the app carries its name, the customers' accounts and order history are its own, and the couriers are its staff or a courier company it contracts. Savor is most of that service already. What changes is that there is one brand instead of many, and nobody applies to sell. This section says what to change, and the class each change belongs in.

52.11.1. One brand, one or a few kitchens

A chain is a restaurant row per branch, each with its own address, hours, preparation time and menu. Seed them in place of catalog/DemoRestaurants, or create them through the admin console. Nothing else in the catalog changes: Catalog.nearby already answers the branches that deliver to the customer’s door, nearest first, and the order goes to the branch the customer picked.

The customer’s first screen changes. With one kitchen, open its menu instead of the list: where Nav.build makes the customer’s home, call RestaurantForm.show with the restaurant’s id. With a few, keep the list, which is now a list of branches, and drop the row of cuisines and the sort above it in CustomerForm, which only make sense for many restaurants.

The name, the icon and the colors are the ones Section 52.1, “Running it” and Wayline’s chapter describe. Use the restaurant’s own photographs: replace the files in backend/photos, which the development server reads into the database the first time it starts, and name them in the seed. In production, upload them from the merchant’s menu editor.

52.11.2. Nobody applies to sell

Restaurants no longer join, so close that door:

  • Remove the restaurant applications from the server’s rules and from Restaurants: apply, application and applicationPhoto. The admin’s Applications pane then lists couriers only.

  • Set the commission to zero under Pricing, or with savor.fee.commissionPercent=0. The commission is what a marketplace keeps of the food; a restaurant selling its own food keeps it all, and the merchant’s sales should say so.

  • Make each branch’s staff merchants of their branch from the admin console. A merchant account works on one restaurant, the one Restaurants.mine finds. An owner who watches several branches needs a branch picker on MerchantForm and the restaurant’s id in the merchant’s calls in place of mine.

52.11.3. Couriers of its own

A restaurant’s couriers are known people, so the courier side works unchanged, with the application step done by an admin. Approve couriers from Applications, or give the role straight from People, and remove Deliver with Savor from the customer’s menu in CustomerForm, and the courier choice from RegisterForm, if the public shouldn’t apply. Offers go to the nearest courier online, as before. With two or three couriers, lengthen savor.offer.seconds and savor.search.seconds, because the one courier nearby may be at a door.

Many restaurants deliver only part of the time, or hand deliveries to a courier company at busy hours. Deliveries.dispatch is the one place a delivery starts: send it to the company’s API there instead of offering it to couriers, and move the delivery with the updates the company sends back.

52.11.4. Pickup

A customer who collects the order needs no courier. Mark the order as collected at checkout, skip dispatch when the kitchen accepts it in Orders.accept, and let the merchant move it from READY to DELIVERED, which captures the hold the way a delivery does.

52.11.5. Booking a table

A restaurant that delivers usually takes bookings too, and the parts are all in the sample. A booking isn’t in it, so this is the outline:

  • The record. A Reservation entity — restaurant, account, time, party size, a note and a state of requested, confirmed, declined, seated or cancelled — in a new migration, with a state machine of conditional moves like the order’s, so a guest cancelling while the restaurant confirms can’t both win.

  • The contract. A @RestClient interface in shared for the guest’s calls (the free times, book, cancel, their own bookings) and calls under /api/merchant/restaurants/{id}/…​ for the staff, behind the same rules as the merchant’s other calls.

  • Free times. Slots inside the restaurant’s opening hours, each with the number of covers the room takes, less the bookings already confirmed.

  • The staff’s screen. A tab beside the order queue in MerchantForm, refreshed by a frame on the live channel when a booking arrives, as a new order is.

  • Telling the guest. A text message through SmsSender and a push through the push package when a booking is confirmed, and a reminder before it.

A deposit for a large party is a card hold, as an order is: authorize when the booking is made, capture it for a no-show, and release it when the guest arrives.

53. Skirmish: Making the game your own

Skirmish shares the module layout, the accounts and sign-in, push notifications and the operations console with Savor and Wayline. What it adds is a game: a deterministic simulation that the app, the server, the replay viewer and the tests all run, a 3D battle drawn over it, and the progression, store and moderation a live game needs. This chapter shows where each of those lives and what to change to make the game yours.

53.1. Running it

The project is in scripts/skirmish, and the Initializr generates it under your own package and name. Start the server on the development profile, which keeps its database in memory, seeds the demo accounts and simulates purchases and push notifications:

CN1_PROFILE=dev backend/server.sh run

Then run the app in the simulator, from the project’s directory:

mvn verify -Psimulator -DskipTests -Dcodename1.platform=javase

The app looks for the server at http://localhost:8080/; Settings changes the address, which is how a phone reaches a server on your computer. To build the native iOS app on a Mac, generate the Xcode project, which lands under ios/target, then open it and run it on a simulator or a device from Xcode:

mvn package -DskipTests -Dcodename1.platform=ios -Dcodename1.buildTarget=ios-source -Dopen=false

The development profile needs nothing installed, and four demo accounts exist, each with the password skirmish-demo:

AccountWhat it’s for

[email protected]

A player with some history: level 3, two chests waiting and a daily quest ready to claim.

[email protected]

A second player, to battle the first from another simulator or device.

[email protected]

A player the server has already flagged, so the console has something to review.

[email protected]

The operator. Signs in to the same app and gets the admin console as well.

53.2. What the sample does

This tour follows a player through the app, with a pointer to the section that explains how each part is built.

53.2.1. Signing in

The first screen offers to sign in, to create an account, or to practice against the bot without one. A new account picks a battle name, which is what opponents and the leaderboard see.

Creating an account: three heroes above a field for the battle name, its preview, and fields for e-mail and password
The sign-in screen: three heroes above the name Skirmish, fields for e-mail and password, and buttons to sign in, create an account or practice

A new player goes straight into the training battle, described in Section 53.16, “The training battle”.

53.2.2. The home screen

The home screen shows the player’s progress at a glance: level and how close the next one is, coins, gems and trophies, the hero of the deck, the BATTLE button, chests, today’s quests and the deck.

The home screen: avatar, level and experience bar, the hero on stage, the BATTLE button, the chest slots and the daily quests
  • Chests are earned by winning and by levelling up. A tap opens one.

  • Daily quests change every day. Three are picked for each player, and a finished one is claimed with Claim.

  • Achievements are long-term goals with gem rewards, listed in the Trophies room.

Every reward is shown in a popup with the player’s hero cheering. The server decides every part of it, as Section 53.7, “Progression” shows.

A reward popup: Training complete, a level-up badge, coins, gems, experience and a chest, and the achievement unlocked

53.2.3. The deck

A deck is eight cards, and the battle hand is four of them at a time, with the next card waiting. Deck shows every card with its elixir cost, and the eight in use are framed in gold. A tap swaps a card in or out.

The deck screen: ten card portraits, eight of them framed in gold, the deck’s average elixir cost and a button to save it

53.2.4. Battle

A battle lasts three minutes. Each side has a king’s castle and two archer towers. Toppling a tower wins a crown, and toppling the castle wins outright. When the clock runs out, the side with more crowns wins. A tie goes to a minute of overtime where the next crown wins, and is a draw if nobody scores. Elixir comes twice as fast in the last minute of regular time.

A battle: the field with the river and two bridges, both sides' towers, troops on the left lane, and the hand of cards under the elixir bar

Elixir fills the bar at the bottom, one drop at a time up to ten. A card is played by tapping it and then the field, or by dragging it there. Troops and buildings go on the player’s own side of the river, and spells go anywhere. Troops walk to the nearest bridge and attack the first thing in their way.

The result screen follows, with the crowns, trophies and coins won. From there a player can watch the replay, report the opponent, or watch a sponsored video for extra coins.

The result screen: Victory, the crown count, and buttons to watch an ad for coins and to continue

53.2.5. Finding an opponent

BATTLE puts the player in a queue that pairs players with similar trophy counts and falls back to the bot if nobody is found. During an online battle, the buttons under the hand send a quick emote to the opponent. Section 53.5, “The server is the referee” explains how the two phones stay in step.

An online battle against the bot, with the emote buttons GG, Wow!, Oops and Thanks under the hand

Practice plays the bot straight away and earns nothing. Challenge makes a code and a link to send a friend, and opening the link starts the friend’s app straight into the battle.

53.2.6. Replays

Every online battle is kept, and Replays lists them. Any signed-in player can watch any battle, with both players' names. A replay isn’t a recording. It’s the starting state and every card played, run again through the same rules. The viewer pauses, plays at two or four times speed, and a slider jumps to any moment.

The replay viewer showing a battle in progress with play, pause and speed controls

53.2.7. The shop and settings

The shop sells gems for real money, and cosmetic items for gems: arenas, emote sets and a season pass. Purchases go through the platform’s store, and the server checks every receipt before granting anything, as Section 53.9, “Purchases” shows. On the development profile the store is simulated, so a purchase completes immediately.

The shop: gem packs with prices, and cosmetic items with their gem cost

Settings renames the player, and switches the sound, push notifications and sharing anonymous usage statistics on or off. The server address can be changed here too, which is how the app reaches a server on another machine.

The settings screen with the battle name, sound, notification and privacy switches, and the server address

53.3. The modules

ModuleWhat it holds

rules

The game itself: the cards, the arena, the units, the bot and replays. It uses nothing but a handful of java.* classes, no Codename One API and no floating point, so the app, the server and the tests compile the same classes.

shared

The contract: the data transfer objects and the @RestClient interfaces both sides compile against.

common

The app: the 3D battle, the menus, the store, ads, analytics, push and the admin console.

backend

The server: accounts, decks, matchmaking, the authoritative match rooms, replays, progression, receipts, push and moderation.

ios

The iOS build, for generating the Xcode project.

53.4. The rules run everywhere

Everything that decides a battle is in Match.step, and nothing else changes a match. It advances the game by one tick, a twentieth of a second, applying the cards played on that tick:

/// Advances one tick. `commands` may hold anything; only those stamped with
/// the current tick are applied, in the order given (the server's order).
public void step(List<Command> commands) {
    if (isOver()) {
        return;
    }
    events.clear();
    if (commands != null) {
        for (int i = 0; i < commands.size(); i++) {
            Command c = commands.get(i);
            if (c.tick == tick) {
                apply(c);
            }
        }
    }
    runWaves();
    regenElixir();
    int count = units.size();
    for (int i = 0; i < count; i++) {
        Unit u = units.get(i);
        if (u.hp > 0) {
            update(u);
        }
    }
    separate();
    removeDead();
    tick++;
    checkEnd();
}

Three rules keep every copy of a match identical:

  • No floating point. Positions are thousandths of a tile, held in int, and FixedMath supplies the integer square root and distance checks. Floating point rounds differently on different processors and compilers, so a battle that used it would drift apart between a phone and the server.

  • No clock and no java.util.Random. Time is the tick count, and chance comes from Rng, seeded by the server when the match starts.

  • The order is fixed. Units act in the order they were created, and cards played on the same tick apply in the order the server received them, which the server’s log fixes for every copy of the match.

Because of that, a replay is only the seed, the two decks and the list of cards played. Replay re-runs them through Match and arrives at the same battle, and the server and both players compare a hash of the state to detect a client that has gone its own way.

53.4.1. Adding a card

A card is a row in Cards:

add(new CardDef("squire", "Squire", CardDef.TROOP, 3)
        .hp(1450).damage(160).hitTicks(24).range(700).speed(45).radius(500));

Hit points and damage are whole numbers, ranges and radii are in thousandths of a tile, speed is thousandths of a tile per tick, and hitTicks is the time between attacks. CardDef also describes what a card targets, whether it splashes, how many units it spawns and how long a building lasts.

The look of a card on the field is a row in Models, the glTF character it uses, its height in tiles and its attack animation:

public final class Models {
    /// How one card looks on the field.
    public static final class Look {
        public final String model;
        /// Height in tiles for a character; footprint width in tiles for a
        /// building.
        public final float size;
        public final String attack;
        public final float hover;
        public final int tint;
        public final String idle;
        public final String run;
        public final String death;

        Look(String model, float size, String attack, float hover, int tint) {
            this(model, size, attack, hover, tint, "Idle", "Running_A", "Death_A");
        }

        Look(String model, float size, String attack, float hover, int tint, String idle, String run,
                String death) {
            this.model = model;
            this.size = size;
            this.attack = attack;
            this.hover = hover;
            this.tint = tint;
            this.idle = idle;
            this.run = run;
            this.death = death;
        }
    }

    private static final Map<String, Look> LOOKS = new HashMap<String, Look>();
    private static final Map<String, GltfScene> SCENES = new HashMap<String, GltfScene>();

    static {
        look("squire", "knight", 1.96f, "1H_Melee_Attack_Chop", 0f, 0xffffffff);
        look("twin-archers", "rogue_hooded", 1.67f, "1H_Ranged_Shoot", 0f, 0xffffffff);
        look("ogre", "barbarian", 3.04f, "2H_Melee_Attack_Chop", 0f, 0xffffffff);
        look("bat-swarm", "skeleton_rogue", 1.16f, "1H_Melee_Attack_Chop", 1.6f, 0xffb8c8ff);
        look("sharpshooter", "rogue", 1.89f, "2H_Ranged_Shoot", 0f, 0xffffffff);
        look("spearmen", "skeleton_warrior", 1.74f, "1H_Melee_Attack_Chop", 0f, 0xffffffff);
        look("drake", "mage", 2.03f, "Spellcast_Shoot", 1.8f, 0xffffffff);
        look("imp", "skeleton_minion", 1.38f, "Unarmed_Melee_Attack_Punch_A", 0f, 0xffffffff);
        look("imp-den", "crypt", 3.77f, null, 0f, 0xffffffff);
    }

    private Models() {
    }

    private static void look(String card, String model, float size, String attack, float hover, int tint) {
        LOOKS.put(card, new Look(model, size, attack, hover, tint));
    }

    /// The look of `card`, or null for a spell or a tower (drawn by the view).
    public static Look of(String card) {
        return LOOKS.get(card);
    }

    /// The look of a card from a Forge pack: its own model, bundled or
    /// uploaded, its size and tint, and the clips its author mapped. A card
    /// with no model of its own falls back to a bundled one by kind.
    public static Look of(CardDef card) {
        Look builtin = LOOKS.get(card.id);
        if (builtin != null || card.kind == CardDef.SPELL || card.kind == CardDef.TOWER) {
            return builtin;
        }
        String model = card.model();
        if (model == null || model.length() == 0) {
            model = card.kind == CardDef.BUILDING ? "crypt" : card.isFlying() ? "skeleton_rogue" : "knight";
        }
        float size = (card.kind == CardDef.BUILDING ? 3.5f : 1.9f) * Math.max(25, card.scalePercent()) / 100f;
        int tint = card.tint() < 0 ? 0xffffffff : 0xff000000 | card.tint();
        String clips = card.clips();
        String attack = GlbInspector.clip(clips, "attack");
        if (attack == null && card.kind != CardDef.BUILDING) {
            attack = card.range() > 1500 ? "1H_Ranged_Shoot" : "1H_Melee_Attack_Chop";
        }
        return new Look(model, size, attack, card.isFlying() ? 1.6f : 0f, tint,
                orElse(GlbInspector.clip(clips, "idle"), "Idle"), orElse(GlbInspector.clip(clips, "run"), "Running_A"),
                orElse(GlbInspector.clip(clips, "death"), "Death_A"));
    }

    private static String orElse(String v, String fallback) {
        return v == null ? fallback : v;
    }

    /// Whether `name` is one of the models that ship with the game.
    public static boolean isBundled(String name) {
        return CN.getResourceAsStream("/model_" + name + ".glb") != null;
    }

    /// The parsed model `name`, loaded once: `/model_<name>.glb` for a bundled
    /// one, or an uploaded file, `asset:<sha256>`, from [ForgeFiles].
    public static synchronized GltfScene scene(String name) {
        GltfScene s = SCENES.get(name);
        if (s == null) {
            InputStream in = name.startsWith("asset:") ? ForgeFiles.open(name.substring(6))
                    : CN.getResourceAsStream("/model_" + name + ".glb");
            if (in == null) {