Initializer (openmrs-module-initializer)
can load a configuration/ content package into OpenMRS, but it cannot produce one. This module
does the reverse: it reads metadata out of a running, populated OpenMRS instance and writes it back
out in the Initializer format, so a configuration can be captured from a server and replayed
elsewhere.
Currently supported domains:
- Concepts (names, descriptions, class/datatype/version, numeric, complex, answers, mappings, attributes)
- Concept sources (name, description, HL7 code, unique ID)
- Concept map types (name, description, is hidden)
- Encounter types (name, description, view/edit privileges)
- Privileges (name, description)
- Concept classes (name, description)
- Roles (name, description, privileges)
- Patient identifier types (name, description, required, format, format description, validator, location/uniqueness behavior)
- Visit types (name, description)
- Relationship types (name, description, a_is_to_b, b_is_to_a, preferred, weight)
- Attribute types (name, description, Min occurs, Max occurs, Datatype classname, Datatype config, Preferred handler classname, Handler config)
- Global properties (property, value): written as XML, since Initializer loads this domain from XML rather than CSV
- Encounter Roles (name, description)
- Person Attribute Types (name, description, searchable, format, foreign uuid, edit privilege)
- Location Tags (name, description)
- Locations (name, description, parent location, tags, address fields): parent locations and tags
are pulled in via cross-domain closure. Tag membership is emitted inline as
Tag|<name>columns, which is Initializer's own equivalent of the standalonelocationtagmapsdomain, so that data needs no separate file - Drugs (name, description, strength, concept drug, concept dosage form, ingredients, mappings): drug/dosage-form/ingredient concepts are pulled in via cross-domain closure
- Order types (name, description, java class name, parent, concept classes): parent order types and concept classes are pulled in via cross-domain closure
- Flags (name, criteria, evaluator, message, priority, enabled, tags, description): requires the patientflags module (3.0+)
- Order frequencies (frequency per day, concept frequency): the referenced concept is pulled in via cross-domain closure
- Programs (name, description, program concept, outcomes concept): the referenced concepts are pulled in via cross-domain closure
- Program workflows (program, workflow concept): the referenced program and concept are pulled in via cross-domain closure
- Concept reference ranges (concept numeric, absolute/critical/normal low and high, criteria): the referenced concept numeric is pulled in via cross-domain closure
- Concept sets (parent concept, member concept, member type, sort weight): the referenced parent and member concepts are pulled in via cross-domain closure
- Program workflow states (workflow, state concept, initial, terminal): the referenced workflow and state concept are pulled in via cross-domain closure
- Procedure types (name, description): requires the emrapi module (3.4+)
- Metadata sets (name, description): requires the metadatamapping module
- Metadata set members (name, description, sort weight, metadata class, metadata uuid, metadata set uuid): the owning metadata set and the referenced metadata item are pulled in via cross-domain closure; requires the metadatamapping module
- Metadata term mappings (mapping code, mapping source, metadata class name, metadata uuid): the referenced metadata item is pulled in via cross-domain closure; requires the metadatamapping module
- Metadata sharing (raw zip packages already built and published through the metadatasharing module's own UI, copied out as-is; not CSV/XML, one file per package): requires the metadatasharing module
- Identifier sources (identifier type, name, description; sequential: prefix, suffix, first
identifier base, min/max length, base character set; remote: url, user, password; pool: backing
source, batch size, minimum size, refill with task, sequential allocation): written as
idgen_sequential/idgen_remote/idgen_pool CSVs with pools ordered last so backing sources load
first; remote-source passwords are never exported in plaintext: each row carries a
property:idgen.remote.password.<identifier source uuid>placeholder, and the importing server must define theidgen.remote.password.<identifier source uuid>system or OpenMRS runtime property (retired remote sources included; Initializer still requires the password when it bootstraps them); sources Initializer cannot import are left out and recorded as exclusions (see the note on exclusions under "Export packages (REST)"): custom identifier source types from other modules, remote sources with no user (Initializer requires one), pools whose backing source is missing or itself left out, as are auto generation options pointing at any such source; reserved identifiers on a source are not exported (Initializer has no column for them) and are flagged with a warning; requires the idgen module (4.6+) - Auto generation options (identifier type, location, identifier source, manual entry enabled, auto generation enabled): the referenced identifier type, source and location are pulled in via cross-domain closure; requires the idgen module (4.6+)
- FHIR concept sources (concept source, url): the referenced concept source is pulled in via cross-domain closure; name and description are not exported (Initializer has no columns for them; it sets the name from the concept source when it creates the row); rows without a concept source are left out as exclusions (Initializer requires that column), and when several rows share one concept source only one is exported, preferring the unretired row, the rest recorded as exclusions (Initializer matches rows by concept source, so duplicates would collapse unpredictably on import); requires the fhir2 module (1.6+)
- FHIR patient identifier systems (patient identifier type, url): the referenced patient identifier type is pulled in via cross-domain closure; name and description are not exported (Initializer has no columns for them; it overwrites the name with the identifier type's name on import); rows without an identifier type are left out as exclusions (Initializer requires that column), and when several rows share one identifier type only one is exported, preferring the unretired row, the rest recorded as exclusions (Initializer matches rows by identifier type, so duplicates would collapse unpredictably on import); requires the fhir2 module (1.6+)
- Address hierarchy (the
addressConfiguration.xml, rebuilt from the ordered hierarchy levels and the live address template, plus a headerlessaddresshierarchy.csvof one root-to-leaf path per leaf entry; not CSV/XML rows but a whole-config directory): requires the addresshierarchy module - Cohort types (name, description): requires the cohort module (3.5+)
- Cohort attribute types (name, description, datatype classname, preferred handler classname, handler config, min/max occurs): retired attribute types are not exported (Initializer's parser cannot resolve them: its lookups exclude retired rows, so re-importing one fails on the name/uuid constraints), and datatype config is not exported (Initializer has no column for it); requires the cohort module (3.5+)
- System tasks (name, title, description, priority, default assignee role, rationale): the
default assignee is written as the provider role's uuid and returned as a cross-domain
dependency, but provider roles themselves are not yet exported: Initializer's
providerrolesdomain still targets the providermanagement module's provider roles, while core 2.8+ has its own (see Initializer #303), so until that lands Initializer resolves the assignee column through the providermanagement module only: when that module is absent the assignee is dropped with a warning, and when it is present a providermanagement provider role with the same uuid must already exist on the importing server or the row fails to import (core's ownprovider_roletable is not consulted); a task whose assignee role no longer exists on the exporting server is exported without the assignee column, with a warning; requires the tasks module (1.0+) - Queues (name, description, service, status concept set, priority concept set, location): the
referenced concepts and location are pulled in via cross-domain closure, and so are the
queue.serviceConceptSetNameglobal property and the concept set it names, because the queue module validates every imported queue against them (the importing server rejects each row until the property is set and the service concept is a member of that set); retired queues are not exported and are recorded as exclusions (Initializer bootstraps a row through the queue module's lookup by uuid, which excludes retired queues, so a retired row can never be matched on the target: where it already exists the re-import fails on the uuid constraint and Initializer 2.12 then abandons the rest of the file); requires the queue module (3.0+) - AMPATH forms (one JSON schema file per form, the same shape the O3 Form Builder saves: the form's
JSON schemaresource is written back as the file, with thename,version,description,published,retiredandencounterentries Initializer copies onto the form refreshed from the form itself;encountercarries the encounter type's name, which is what Initializer resolves even though its own error message speaks of an "id"): the encounter type and the form's translation resources are pulled in via cross-domain closure; retired forms and all but the newest version of a name are not exported and are recorded as exclusions (Initializer cannot create a retired form: its loader saves the retired flag without a retire reason, which core's form validator rejects, so the file fails on any target not already carrying that name and version; and Initializer derives the form uuid from name and version and retires the live form of that name before creating a new version, so two versions in one package would leave a survivor that depends on file order); a form whose schema resource has no readable JSON object is not exported either, and recorded as an exclusion; a form without an encounter type is still exported but flagged with a warning, because Initializer rejects the file until anencounterentry is added (unless itsprocessoris not the encounter form processor); because Initializer ignores anyuuidin the file (see above), the imported form keeps the source uuid only when the source form was itself loaded by Initializer - AMPATH form translations (one JSON file per form and language, written back from the form's
<form name>_translations_<language>resource, whether Initializer saved it as a long free text or the O3 Form Builder saved it with no datatype at all, with theformentry refreshed to the form's name and a missinglanguagefilled in from the resource name): the owning form is pulled in via cross-domain closure; only translations of exported forms (see above) are exported, and a resource whose clob is missing or does not hold a JSON object is left out as an exclusion, since there is nothing to write; a resource carrying onlyform_name_translation(the localized form name, a documented Initializer use) is exported like any other - Appointment specialities (name): requires the Bahmni appointments module (1.2.1+)
- Appointment service definitions (name, description, duration, start time, end time, max load,
speciality, location, label colour): the speciality and location are written by uuid and pulled
in via cross-domain closure; start and end times are written as
HH:mm, the only format Initializer parses, so seconds are dropped; voided definitions are not exported by design: the appointments module rejects a save whose name is already held by a live definition, so a voided row collides with the live definition that replaced it; weekly availability and the initial appointment status are not exported (Initializer has no column for them); requires the Bahmni appointments module (1.2.1+) - Appointment service types (name, duration, service definition): the owning service definition is written by uuid and pulled in via cross-domain closure; voided types and the types of voided definitions are not exported, so a voided definition can never enter the package as a live row through its types; note that Initializer's own loader rebuilds a definition's type set from its non-voided types when it imports a type, so voided types already on the importing server are deleted by the import; requires the Bahmni appointments module (1.2.1+)
- Billable services (service name, short name, concept, service type, service status): referenced concepts are pulled in via cross-domain closure; requires the billing module (2.4.0+)
- Cash points (name, description, location): referenced location is pulled in via cross-domain closure; requires the billing module (2.4.0+)
- Cashier item prices (name, price, payment mode, stock item, billable service): referenced
payment mode and billable service are pulled in via cross-domain closure; stock-item references
are not self-contained:
CashierItemPriceLineProcessorresolves a stock item throughStockManagementService.getStockItemByUuidand throws if it is absent, and Initializer has no stock-item domain for the closure to fall back on, so rows that reference a stock item only load onto a server that already holds the same stock items; requires the billing module (2.4.0+) - Payment modes (name, attributes): requires the billing module (2.4.0+)
Domains contributed by other modules that are supportable but not covered, and why:
- Bahmni forms and HTML forms: neither form engine is used in the O3 distribution, which is what this module targets.
- Data filter mappings: the datafilter module does not start on the platform baseline (its
FullTextQueryCreatedEventListenerdepends on a core class removed in 2.8.0), and its stored mappings reference entities by database id rather than uuid, so they are not portable between servers without being resolved first.
Initializer domains that cannot be exported, and why:
- Liquibase: the domain runs arbitrary changesets against the database; a running instance holds the changes' effects, not the changesets, so there is nothing to read back.
- JSON key-values: Initializer loads these files into an in-memory lookup for other modules; they are never persisted to the database.
- OCL: the domain imports concept dictionary zips produced by Open Concept Lab. Concepts loaded that way are exported through the concept domains above; the OCL export itself is produced by OCL, not by the OpenMRS instance.
- Dispositions: the domain replaces the emrapi disposition configuration in memory; the configuration is not persisted to the database.
When the metadataexport.exportOnStartup global property is true (default false), the
activator exports every instance of every registered domain on module startup. It runs on a daemon
thread (so it has full read access and does not block startup) and writes to:
<OpenMRS application data directory>/metadata_export/configuration/<domain>/...
The export is built in two separated stages:
- Selection. Starting from seed objects, a
Selectorwalks each object's dependencies to a fixpoint, producing anExportManifest(the set of objects to export, bucketed by domain). This is what makes a package self-contained: for example, exporting a concept set also pulls in its members. - Export. Each
DomainExporterwrites its bucket in its own format. The service holds a registry of these and contains no per-domain logic.
Retired (or voided) objects are exported as complete rows with the void/retire flag set, not as
uuid-only stubs. Initializer only skips a retired row's columns when the target already has the
object; on a target that lacks it, Initializer creates the object from the row and then retires
it, so a stub would fail validation there and take down every live row that references the
object (for example a concept whose answer is a retired concept).
Two kinds of retired rows are still left out and recorded as exclusions (see "Export packages (REST)"). First, rows Initializer cannot round-trip at all: it cannot create a retired AMPATH form or a voided cohort type, and it cannot find an already-present retired queue or cohort attribute type (its lookups exclude retired rows, so the re-import inserts a duplicate and fails); retired billable services (with the item prices that point at them) and voided appointment service definitions and their types are left out for the reasons given in their bullets above. Second, in the domains whose Initializer parser falls back to a lookup by name when a row's uuid is unknown on the target (concept classes, sources and map types, encounter types and roles, visit types, patient identifier types, order types, attribute types and drugs), a retired row that shares its name with another row of the domain (possible wherever the table does not itself forbid duplicate names) is left out: depending on load order it would either retire the live row of that name or be merged into it, and its own uuid would never exist on the target. Note that the same fallback means a package can retire a same-named object the target created under a different uuid; the exporter cannot prevent that. Cross-domain closure never pulls an excluded row back in: a live row that references one (a concept whose class is an excluded retired class, say) is exported as it is, the log warns about the pair, and the build manifest lists the excluded row with its reason. Where the reference is written by name (concept class, mapping source and map type, form encounter type) it resolves to the live same-named row on the target; where it is written by uuid it fails to resolve there, which the warning tells you in advance.
Named export packages can be defined and built over REST. A package describes what to export,
a list of entries, each an Initializer domain optionally narrowed to specific item uuids (empty
list = the whole domain), so e.g. a "Site A locations" package exports just one site's locations
(plus dependency closure). A package with no entries at all exports every registered domain.
Every build of a package gets an incrementing version, a
status (QUEUED → RUNNING → COMPLETED/FAILED), and a downloadable zip laid out as an
OpenMRS content package: the Initializer tree under configuration/backend_configuration/ (where
the OpenMRS SDK installs it from), a content.properties carrying the package name and build
number as version, and a metadataexport-manifest.json recording exactly what was exported and,
for every domain exported in full, the rows that were left out and why (its excluded section).
Exclusions are rows a domain has on the server but never exports because Initializer could not load them on a target: retired queues, voided cohort types, identifier sources without a user, superseded form versions, retired rows whose name another row holds in a domain Initializer resolves by name. A package that names an excluded row by uuid does not silently drop it: the build fails with the reason, separately from any uuid the domain does not know at all.
Builds run asynchronously on a daemon thread; trigger, then poll. Packages and builds are
REST web services resources under the module namespace
/openmrs/ws/rest/v1/metadataexport, so they follow every REST module convention: ?v=ref|default|full
representations (lists default to ref), ?startIndex=&limit= paging with results/links/totalCount (totalCount=true
to ask for it), includeAll=true to include retired items, the standard {"error": {...}} body
with fieldErrors/globalErrors on validation failures, and the module's authentication filter
(basic auth or a session). The two things the framework cannot express - a fixed list of strings
and a binary download - are plain Spring controllers at the same base path.
| Method | Path | Action |
|---|---|---|
| GET | /domains |
list the registered, exportable domains (not a resource) |
| GET | /packages |
list packages by name, paged; includeAll=true for retired |
| POST | /packages |
create a package (201) |
| GET | /packages/{uuid} |
fetch one, incl. latestBuild |
| POST | /packages/{uuid} |
update name/description/entries (REST module uses POST) |
| DELETE | /packages/{uuid}?reason= |
retire (204); ?purge=true is refused (400) |
| POST | /builds {"package": uuid} |
trigger a build (201 with the QUEUED build; 409 if retired or a build is active) |
| GET | /builds?package={uuid} |
build history of a package, paged, newest first (404 if unknown) |
| GET | /builds/{uuid} |
poll status; ?v=full adds the parsed manifest; updates are refused (400) |
| GET | /builds/{uuid}/download |
the zip (409 unless COMPLETED, 410 if gone; not a resource) |
A package body is {"name", "description", "entries": [{"domain", "itemUuids": [...]}]}; entries
is required on create because an explicit [] means "every registered domain", so a missing list is
rejected rather than silently widening the export. Updates are partial in the REST module's usual
way: a property left out of the body keeps its current value. A build's default
representation carries package (ref), version, status, the three dates, errorMessage and,
once COMPLETED, an absolute downloadUrl.
Example flow:
BASE=http://localhost:8080/openmrs/ws/rest/v1/metadataexport
# define a package scoped to two locations
curl -u admin:pw -H 'Content-Type: application/json' -d '{
"name": "Site A locations",
"description": "Everything Site A needs",
"entries": [ { "domain": "LOCATIONS", "itemUuids": ["<uuid-1>", "<uuid-2>"] } ]
}' $BASE/packages
# trigger a build, poll until COMPLETED, then download
curl -u admin:pw -H 'Content-Type: application/json' -d '{"package":"<pkg-uuid>"}' $BASE/builds
curl -u admin:pw $BASE/builds/<build-uuid>
curl -u admin:pw -OJ $BASE/builds/<build-uuid>/downloadPrivileges are enforced on the service (@Authorized), so they apply to every entry point that
reaches it; /domains reads the exporter registry directly and checks the Get privilege itself.
Reads need Get Metadata Export Packages; creating, updating, retiring and triggering need
Manage Metadata Export Packages; fetching a build's zip needs Download Metadata Export Packages,
kept separate so a role can pull exports without being able to change them. Both Manage and
Download must be paired with Get: every write renders the saved object in its response, and that
rendering reads (for example latestBuild), so a Manage-only role would have its POST /packages
succeed and then get back a privilege error instead of the created package; likewise the download
looks the build up before streaming it.
If the server restarts mid-build, the activator marks any stranded QUEUED/RUNNING builds as FAILED on startup so they never block future builds of their package.
Zips and their unzipped working copies accumulate under
<app data dir>/metadataexport/packages/<package-uuid>/<version>/; there is no retention policy
yet, so clean up old builds manually if disk space matters. Note also that these endpoints are
session-authenticated but not CSRF-protected (nothing under /ws/* is); treat them as an
admin-only API.
- Initializer 2.12.1+
- REST Web Services 3.1.0+
Supporting a new metadata type is a new class, never a new method on the service.
- Write a
DomainExporterand annotate it@Component; component scanning registers it, there is no list to edit. For a CSV domain, extendCsvDomainExporter<T>:
@Component
public class EncounterTypeDomainExporter extends CsvDomainExporter<EncounterType> {
public Domain getDomain() { return Domain.ENCOUNTER_TYPES; }
public boolean handles(OpenmrsObject o) { return o instanceof EncounterType; }
public Collection<EncounterType> getAllInstances() {
return Context.getEncounterService().getAllEncounterTypes();
}
// Objects from OTHER domains this one references, for cross-domain closure. Empty if none.
public Collection<? extends OpenmrsObject> getDependencies(EncounterType t) {
return Collections.emptyList();
}
protected List<BaseLineExporter<EncounterType>> chain() {
return Arrays.asList(new EncounterTypeLineExporter());
}
protected String fileName() { return "encounterTypes.csv"; }
}- Write the line exporter(s). Each writes header to value pairs into an
ExportLine; it is the inverse of Initializer's matchingBaseLineProcessor.fill(...). Reuse Initializer's header constants where they arepublicso the two sides cannot drift. For the primary exporter of a domain, extendMetadataLineExporter<T>: it writes the uuid and, for a retired object, thevoid/retireflag, then callsexportfor every object (retired ones included, so a target that lacks the object can create it before retiring it), soexportonly handles the domain-specific columns:
public class EncounterTypeLineExporter extends MetadataLineExporter<EncounterType> {
public void export(EncounterType t, ExportLine line) {
line.put(BaseLineProcessor.HEADER_NAME, t.getName());
line.put(BaseLineProcessor.HEADER_DESC, t.getDescription());
}
}Exporters that only contribute extra columns to an existing row (not the primary one) extend
BaseLineExporter<T> directly instead.
A CSV domain may emit more than one file by overriding partition(instances) (the default is one
file). When the files must load in a set sequence (e.g. idgen pools after the sources they
reference), also override order(fileName) to stamp each file with an Initializer _order:
header.
For an XML domain (Initializer loads some domains, such as global properties, from XML rather than
CSV), extend XmlDomainExporter<T> instead of CsvDomainExporter<T>. Build the DOM in
toDocuments(instances), keyed by file name so a domain can emit one file or many, and use the
inherited newDocument() to get a Document without JAXP boilerplate; the base handles indentation,
encoding, and placement in the domain directory the ExportContext chooses:
@Component
public class GlobalPropertyDomainExporter extends XmlDomainExporter<GlobalProperty> {
public Domain getDomain() { return Domain.GLOBAL_PROPERTIES; }
public boolean handles(OpenmrsObject o) { return o instanceof GlobalProperty; }
public Collection<GlobalProperty> getAllInstances() {
return Context.getAdministrationService().getAllGlobalProperties();
}
// Objects from OTHER domains this one references, for cross-domain closure. Empty if none.
public Collection<? extends OpenmrsObject> getDependencies(GlobalProperty gp) {
return Collections.emptyList();
}
protected String fileName() { return "globalProperties.xml"; }
protected Map<String, Document> toDocuments(Collection<GlobalProperty> gps) {
Document doc = newDocument();
// build <config><globalProperties><globalProperty>... and return
return Collections.singletonMap(fileName(), doc);
}
}For a JSON domain (Initializer loads AMPATH forms and their translations from one JSON file per
form), extend JsonDomainExporter<T>. Build the Jackson trees in toDocuments(instances), again
keyed by file name (leaving an instance out of the map is how you skip it), either by parsing
stored content with Jackson or from scratch with the inherited newObject(); the base handles
pretty-printing, encoding, and placement in the domain directory the ExportContext chooses:
@Component
public class AmpathFormDomainExporter extends JsonDomainExporter<Form> {
public Domain getDomain() { return Domain.AMPATH_FORMS; }
// ... handles / getAllInstances / getDependencies as for any domain ...
protected Map<String, JsonNode> toDocuments(Collection<Form> forms) throws IOException {
Map<String, JsonNode> documents = new LinkedHashMap<>();
for (Form form : forms) {
// parseStoredSchema and fileNameFor are illustrative helpers, not framework methods
ObjectNode schema = parseStoredSchema(form);
schema.put("name", form.getName());
// ... refresh the other keys Initializer reads ...
documents.put(fileNameFor(form) + ".json", schema);
}
return documents;
}
}Any other domain whose files are neither CSV, XML nor JSON (for example the address hierarchy's
whole-config directory) skips the base classes and implements DomainExporter directly. Its
export(bucket, context) must write under context.domainDir(getDomain()), which is what puts the
files where the startup export and a package zip each need them, as
AddressHierarchyDomainExporter does.
Two optional hooks on DomainExporter matter only when a domain does not export every row it has.
Override exclusions() to return the rows it leaves out, uuid to a sentence that names the row and
the one reason that applies (DomainExporter.exclusions(all, predicate, reason) builds it for the
common cases); the framework records them in the build manifest, logs them once per export, and uses
them so a package naming such a row fails with the reason instead of as an unknown uuid. Override
candidatesFor(uuids) only in a domain that exports every row and has a by-uuid service lookup, so a
package naming a few rows does not load the whole table; a filtering domain must keep the default,
and no domain should override getInstancesByUuids itself.
- Concept description UUIDs and index-term names are not round-trip-able (Initializer format/loader limitations), so they are not preserved or re-loadable.
- Cross-domain closure only pulls in objects whose domain has a registered exporter.
Java 8+ and Maven. mvn clean package produces omod/target/metadataexport-*.omod. Code
formatting is handled by Spotless during the build (mvn spotless:apply to format manually).