Skip to content

About

JAXB marshaller and unmarshaller using streaming to handle large files

Topics

Resources

Stars

22 stars

Watchers

2 watching

Forks

Repository files navigation

JAXB Streaming

Quality Gate Dependency Check Maven Central License

This library allows you to read and write a list of elements (even from different types, but with the same parent) item by item from and to an XML file. The goal is to avoid loading a huge amount of data into memory when processing large files.

Installation

The dependency is available in maven central (see badge for version):

<dependency>
    <groupId>com.chavaillaz</groupId>
    <artifactId>jaxb-stream</artifactId>
</dependency>

The library is annotated with JSpecify nullability annotations (the whole package is @NullMarked, meaning every parameter, return type and field is non-null unless explicitly marked @Nullable), so static analysis tools (IDE inspections, NullAway, the Checker Framework, ...) can catch null-safety issues in your code at build time.

Usage

You can find the following example in the StreamingTest class. Note that this library also works with JAXB classes generated by an XSD file. In that case, have a look at the StreamingXsdTest class. The extension points for XML files with a more complex structure are covered in StreamingComplexStructureTest, and the for-each/stream() API, schema validation and output configuration in StreamingErgonomicsTest.

Context

You are storing different types of metrics in an XML file. Because of memory constraints and the number of entries, you cannot load them at once as it would be done with JAXB by unmarshalling the file into the container class.

In order to process them anyway, you can use this library to read or write them, item by item.

In this example, an interface Metric is implemented by multiple metric types:

  • Disk metrics (class DiskMetric, XML element disk)
  • Memory metrics (class MemoryMetric, XML element memory)
  • Processor metrics (class ProcessorMetric, XML element processor)

Each metric defines an XML element by using the annotation @XmlRootElement. Those metrics would usually be stored in the container MetricsList, representing a list of metrics (container). This list also defines an XML element, in that case metrics, the XML tag for that container.

Below an XML file from that example:

<?xml version="1.0" ?>
<metrics>
    <disk>
        <disk>/</disk>
        <freePartitionSpace>688865050624</freePartitionSpace>
        <usablePartitionSpace>544384016384</usablePartitionSpace>
        <totalCapacity>700001001472</totalCapacity>
    </disk>
    <memory>
        <freeMemory>521889952</freeMemory>
        <maxMemory>8589934592</maxMemory>
        <totalMemory>536870912</totalMemory>
    </memory>
    <processor>
        <systemLoad>0.25</systemLoad>
        <processLoad>0.18</processLoad>
        <availableProcessors>16</availableProcessors>
    </processor>
    ...
</metrics>

Writing elements

For example, to write two metrics (memory and processor metrics), the following code can be used:

try (StreamingMarshaller marshaller = new StreamingMarshaller(MetricsList.class)) {
    marshaller.open(new FileOutputStream(fileName));
    marshaller.write(MemoryMetric.class, new MemoryMetric());
    marshaller.write(ProcessorMetric.class, new ProcessorMetric());
    ...
}

Note that you can also give the root element tag name instead of giving MetricsList.class.

Reading elements

For example, to read the written metrics (memory and processor metrics), the following code can be used:

try (StreamingUnmarshaller unmarshaller = new StreamingUnmarshaller(MemoryMetric.class, ProcessorMetric.class)) {
    unmarshaller.open(new FileInputStream(fileName));
    unmarshaller.iterate((type, element) -> doWhatYouWant(element));
}

or by iterating over each element by yourself:

try (StreamingUnmarshaller unmarshaller = new StreamingUnmarshaller(MemoryMetric.class, ProcessorMetric.class)) {
    unmarshaller.open(new FileInputStream(fileName));
    while (unmarshaller.hasNext()) {
        doWhatYouWant(unmarshaller.next(YourObject.class));
    }
}

Note that if the classes given to the StreamingUnmarshaller do not have the XmlRootElement annotation (for example if they are generated by XJC from an XSD), you can give the tag names with the classes using a Map.

Since StreamingUnmarshaller is also Iterable, you can use a for-each loop or the stream() method instead:

try (StreamingUnmarshaller unmarshaller = new StreamingUnmarshaller(MemoryMetric.class, ProcessorMetric.class)) {
    unmarshaller.open(new FileInputStream(fileName));
    for (Object element : unmarshaller) {
        doWhatYouWant(element);
    }
}
try (StreamingUnmarshaller unmarshaller = new StreamingUnmarshaller(MemoryMetric.class, ProcessorMetric.class)) {
    unmarshaller.open(new FileInputStream(fileName));
    unmarshaller.stream().forEach(element -> doWhatYouWant(element));
}

Checked exceptions (XMLStreamException, JAXBException) raised while iterating or streaming are wrapped in an unchecked UncheckedXmlException, since neither Iterator nor Stream allow their methods to throw them.

XSD schema validation

You can validate elements against an XSD schema while marshalling or unmarshalling them by giving a Schema built with a SchemaFactory:

Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(new File("schema.xsd"));

try (StreamingUnmarshaller unmarshaller = new StreamingUnmarshaller(MemoryMetric.class, ProcessorMetric.class)) {
    unmarshaller.setSchema(schema);
    unmarshaller.open(new FileInputStream(fileName));
    // A JAXBException is thrown when reading an element invalid against the schema
    ...
}

The same setSchema method is available on StreamingMarshaller to validate elements while writing them.

Namespace support

When a type's @XmlRootElement declares a namespace (or inherits one from its package's @XmlSchema), both StreamingMarshaller.write(Class, Object) and the StreamingUnmarshaller(Class...) constructor resolve it automatically the same way JAXB itself would, so writing and reading namespaced elements works without any extra configuration:

// @XmlRootElement(name = "memory") in a package annotated @XmlSchema(namespace = "urn:example:metrics")
marshaller.write(MemoryMetric.class, metric); // written as <memory xmlns="urn:example:metrics">
new StreamingUnmarshaller(MemoryMetric.class); // correctly expects that same namespace when reading

For classes without @XmlRootElement (or to use a namespace not declared on the type itself), give the tag name in the {namespaceURI}localName format instead, both when writing with write(Class, String, Object) and when reading with the Map-based StreamingUnmarshaller constructor.

Resilient reading

By default, an element that fails to unmarshal (invalid data, or data rejected by a schema given to setSchema) aborts the whole read. For large files where a few bad records shouldn't stop processing the rest, enable setSkipInvalidElements to skip them instead — this applies to iterate, iterator (and therefore for-each loops) and stream, but not to next, which always throws:

try (StreamingUnmarshaller unmarshaller = new StreamingUnmarshaller(MemoryMetric.class, ProcessorMetric.class)) {
    unmarshaller.setSchema(schema);
    unmarshaller.setSkipInvalidElements(true);
    unmarshaller.open(new FileInputStream(fileName));
    // Elements that fail to unmarshal are logged at WARN level and skipped instead of aborting
    unmarshaller.iterate((type, element) -> doSomething(element));
}

Each element has to be buffered in memory before being unmarshalled so that a failure cannot corrupt the position of the underlying reader, which adds some overhead compared to the default behavior.

Output configuration

StreamingMarshaller writes indented UTF-8 XML by default. Both can be changed before calling open:

try (StreamingMarshaller marshaller = new StreamingMarshaller(MetricsList.class)) {
    marshaller.setCharset(StandardCharsets.ISO_8859_1);
    marshaller.setPrettyPrint(false);
    marshaller.open(new FileOutputStream(fileName));
    ...
}

Nested containers

If the elements to write are not all direct children of the root element — for example several lists of different element types, each wrapped in its own container — use openChild to write into a nested container without subclassing anything. The returned marshaller shares the same underlying stream and only closes its own container tag, not the whole document, so it can be closed independently (typically with its own try-with-resources block) and nesting can go arbitrarily deep:

try (StreamingMarshaller marshaller = new StreamingMarshaller("metrics")) {
    marshaller.open(new FileOutputStream(fileName));

    try (StreamingMarshaller memoryMetrics = marshaller.openChild("memory")) {
        memoryMetrics.write(MemoryMetric.class, new MemoryMetric());
        ...
    }

    try (StreamingMarshaller processorMetrics = marshaller.openChild("processor")) {
        processorMetrics.write(ProcessorMetric.class, new ProcessorMetric());
        ...
    }
}

Complex XML file structure

For anything openChild doesn't cover — reading back a nested structure, or customizing the very start/end of the document itself (an XML declaration with extra attributes, a namespace declaration on the root, ...) — you have the possibility to extend both marshaller and unmarshaller and override the following methods:

  • createDocumentStart in StreamingMarshaller to write the start of the XML file before the stream of elements
  • close in StreamingMarshaller to write the end of the XML file (note that tags are closed automatically)
  • skipDocumentStart in StreamingUnmarshaller to reach the stream of elements in the document

Contributing

If you have a feature request or found a bug, you can:

  • Write an issue
  • Create a pull request

If you want to contribute then

  • Please write tests covering all your changes
  • Ensure you didn't break the build by running mvn test
  • Fork the repo and create a pull request

License

This project is under Apache 2.0 License.

About

JAXB marshaller and unmarshaller using streaming to handle large files

Topics

Resources

Stars

22 stars

Watchers

2 watching

Forks

Releases

Used by

Contributors

Languages