A java modelisation of HAL (Hypertext Application Language).
- Java 17+
Add the hal-model dependency:
<dependency>
<groupId>com.cosium.hal_model</groupId>
<artifactId>hal-model2</artifactId>
<version>${hal-model.version}</version>
</dependency>record User(@JsonProperty("username") String username) {
}
void main() {
HalFormsBody<User> halFormsBody = HalFormsBodies.parseJson(json);
}record User(@JsonProperty("username") String username) {
}
void main() {
JsonMapper jsonMapper = JsonMapper.builder().addModule(new HalModelJacksonModule()).build();
HalFormsBody<User> halFormsBody = jsonMapper.readValue(json, new TypeReference<>() {
});
}{
"username": "jdoe",
"_links": {
"self": {
"href": "http://localhost/self"
}
},
"_templates": {
"default": {
"method": "PUT",
"properties": [
{
"name": "foo"
}
]
}
}
}record User(@JsonProperty("username") String username) {
}
void main() {
HalFormsBody<User> halFormsBody = HalFormsBodies.parseJson(json);
assertThat(halFormsBody.representation().username()).isEqualTo("jdoe");
assertThat(halFormsBody.linkByName()).containsOnlyKeys("self");
assertThat(halFormsBody.requireLink("self").href().expand())
.isEqualTo("http://localhost/self");
assertThat(halFormsBody.requireSelfUri()).isEqualTo("http://localhost/self");
assertThat(halFormsBody.templateByKey()).containsOnlyKeys("default");
TemplateRepresentation template = halFormsBody.requireTemplate("default");
assertThat(template.method()).isEqualTo("PUT");
assertThat(template.propertyByName()).containsOnlyKeys("foo");
TemplatePropertyRepresentation property = template.propertyByName().get("foo");
assertThat(property.type()).isEqualTo("text");
}{
"_embedded": {
"content": [
"element1",
"element2"
]
},
"_links": {
"self": {
"href": "http://localhost/self"
}
},
"_templates": {
"default": {
"method": "PUT",
"properties": [
{
"name": "foo"
}
]
}
}
}record ContentList<T>(@JsonProperty("content") @Nullable List<T> content) {
}
void main() {
HalFormsBody<EmbeddedContainer<ContentList<String>>> halFormsBody = HalFormsBodies.parseJson(json);
assertThat(halFormsBody.representation().requireEmbedded().content())
.containsExactly("element1", "element2");
assertThat(halFormsBody.linkByName()).containsOnlyKeys("self");
assertThat(halFormsBody.requireLink("self").href().expand())
.isEqualTo("http://localhost/self");
assertThat(halFormsBody.templateByKey()).containsOnlyKeys("default");
TemplateRepresentation template = halFormsBody.requireTemplate("default");
assertThat(template.method()).isEqualTo("PUT");
assertThat(template.propertyByName()).containsOnlyKeys("foo");
TemplatePropertyRepresentation property = template.propertyByName().get("foo");
assertThat(property.type()).isEqualTo("text");
}