Skip to content

Attribute Converters

Martin Ledvinka edited this page Oct 26, 2022 · 1 revision

Since 0.19.0.

JOPA has internally supported attribute converters for some time, but now it is possible to register custom converters as well. Note however, that custom attribute converters can be applied only to attributes mapped by data and annotation properties, object properties are still handled only by JOPA.

Creating Attribute Converter

To create a custom attribute converter, just implement the AttributeConverter interface. It is generic, the first parameter denotes the type of the target attribute (Java field), the second one denotes the value provided by/to the OntoDriver API. In addition, attribute converters should be annotated with the Converter annotation.

Here's a simple example of a custom attribute converter (taken from integration tests in JOPA):

@Converter
public class ZoneOffsetConverter implements AttributeConverter<ZoneOffset, String> {

    @Override
    public String convertToAxiomValue(ZoneOffset value) {
        return value.getId();
    }

    @Override
    public ZoneOffset convertToAttribute(String value) {
        return ZoneOffset.of(value);
    }
}

The converter must have a public no-arg constructor and if it should be applied automatically (see below), it must be in a package covered by the cz.cvut.jopa.scanPackage property.

Using Attribute Converter

There are two ways to use a custom attribute converter:

  1. Declare autoApply in the Converter annotation to true. In this case, any attribute matching the converter type will automatically be processed by the converter.
  2. Declare the converter per attribute using the Convert annotation. In this case, the converter class is specified via the converter parameter. This annotation can also be used to disable automatic application of an auto-applied converter.

Here's a simple example of declaring the converter locally:

@OWLClass(iri = "http://example.org/entity")
public class Entity {
  @Id
  private URI id;

  @Convert(converter = ZoneOffsetConverter.class)
  @OWLDataProperty(iri = "http://example.org/has-timezone", simpleLiteral = true)
  private ZoneOffset timezone;
}