Skip to content

Customizing localization

Note

This is a wiki stub, while this allows you to know such features exist, there is little to no content about it, however, you can:

  • Ask questions about it in the support server
  • Help create this wiki by contributing directly, or by suggesting what topics should be explained, how they should be structured, give relevant use cases/examples...

Creating readers

The reader is the last step in loading a bundle. You get handed an object with the requested bundle (base name + locale), and its job is to read that bundle however it wants. This is most likely what you'll want to customize.

For example, you can change:

  • The format the bundle uses (JSON, YAML, TOML...)
  • The location it is read from (local filesystem, from the classpath...)
  • The templates it uses (instead of using DefaultLocalizationTemplate which uses Java's MessageFormat, use ICU4J)

Tip

For bundles which are readable by Jackson, you can help yourself with AbstractJacksonLocalizationMapReader.

Reading bundles from the local filesystem

class LocalLocalizationMapReader(
    context: BContext,
    mapper: ObjectMapper,
    private val basePath: Path,
) : AbstractJacksonLocalizationMapReader(context, mapper) {

    override fun getInputStream(request: LocalizationMapRequest): InputStream? {
        val fileName = "${request.bundleName}.json"
        val path = basePath.resolve(fileName)
        if (path.notExists()) {
            logger.trace { "Found no bundle at ${path.pathString}" }
            return null
        }

        return path.inputStream()
    }
}
public class LocalLocalizationMapReader extends AbstractJacksonLocalizationMapReader {
    private static final Logger LOGGER = Logging.getLogger();

    private final Path basePath;

    public LocalLocalizationMapReader(@NonNull BContext context, @NonNull ObjectMapper mapper, @NonNull Path basePath) {
        super(context, mapper);
        this.basePath = basePath;
    }

    @Nullable
    @Override
    public InputStream getInputStream(@NonNull LocalizationMapRequest request) {
        var fileName = basePath + ".json";
        var path = basePath.resolve(fileName);
        if (Files.notExists(path)) {
            LOGGER.trace("Found no bundle at {}", path);
            return null;
        }

        try {
            return Files.newInputStream(path);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
}