#715 - Add link and affordance DSLs to help write idiomatic Kotlin code.

* Provide a LinkBuilderDsl for help create links.
* Provider an AffordanceBuilderDsl to help create affordances.
This commit is contained in:
Kulcsár Roland
2018-05-27 13:40:12 +02:00
committed by Greg Turnquist
parent 26c9a3d71e
commit 9c5d10aa07
5 changed files with 400 additions and 7 deletions

65
pom.xml
View File

@@ -80,6 +80,7 @@
<slf4j.version>1.7.25</slf4j.version>
<spring.version>5.0.11.RELEASE</spring.version>
<spring-plugin.version>2.0.0.BUILD-SNAPSHOT</spring-plugin.version>
<kotlin.version>1.2.71</kotlin.version>
</properties>
<profiles>
@@ -422,6 +423,26 @@
<dependencies>
<!-- Kotlin extension -->
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>${kotlin.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-reflect</artifactId>
<version>${kotlin.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-test</artifactId>
<version>${kotlin.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
@@ -554,13 +575,6 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>xmlunit</groupId>
<artifactId>xmlunit</artifactId>
<version>1.6</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.jadler</groupId>
<artifactId>jadler-all</artifactId>
@@ -663,6 +677,43 @@
<useSystemClassLoader>false</useSystemClassLoader>
</configuration>
</plugin>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>${kotlin.version}</version>
<executions>
<execution>
<id>compile</id>
<goals>
<goal>compile</goal>
</goals>
<configuration>
<sourceDirs>
<sourceDir>${project.basedir}/src/main/kotlin</sourceDir>
<sourceDir>${project.basedir}/src/main/java</sourceDir>
</sourceDirs>
</configuration>
</execution>
<execution>
<id>test-compile</id>
<goals>
<goal>test-compile</goal>
</goals>
<configuration>
<sourceDirs>
<sourceDir>${project.basedir}/src/test/kotlin</sourceDir>
<sourceDir>${project.basedir}/src/test/java</sourceDir>
</sourceDirs>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>

View File

@@ -0,0 +1,59 @@
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.hateoas
import org.springframework.hateoas.mvc.ControllerLinkBuilder
import org.springframework.hateoas.mvc.ControllerLinkBuilder.afford
import org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn
/**
* Create a new [Link] with additional [Affordance]s.
*
* @author Roland Kulcsár
* @since 1.0
*/
inline infix fun Link.andAffordances(setup: AffordanceBuilderDsl.() -> Unit): Link {
val builder = AffordanceBuilderDsl()
builder.setup()
return andAffordances(builder.affordances)
}
/**
* Extract a [Link] from the [ControllerLinkBuilder] and look up the related [Affordance]. Should
* only be one.
*
* @author Roland Kulcsár
* @since 1.0
*/
inline fun <reified C> afford(func: C.() -> Unit): Affordance = afford(methodOn(C::class.java).apply(func))
/**
* Provide an [Affordance]s DSL to help write idiomatic Kotlin code.
*
* @author Roland Kulcsár
* @since 1.0
*/
open class AffordanceBuilderDsl(val affordances: MutableList<Affordance> = mutableListOf()) {
inline fun <reified C> afford(func: C.() -> Any) {
val affordance = afford(methodOn(C::class.java).func())
affordances.add(affordance)
}
}

View File

@@ -0,0 +1,87 @@
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.hateoas
import org.springframework.hateoas.mvc.ControllerLinkBuilder
import org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo
import org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn
import kotlin.reflect.KClass
/**
* Create a [ControllerLinkBuilder] pointing to a [func] method.
*
* @author Roland Kulcsár
* @since 1.0
*/
inline fun <reified C> linkTo(func: C.() -> Unit): ControllerLinkBuilder = linkTo(methodOn(C::class.java).apply(func))
/**
* Create a [Link] with the given [rel].
*
* @author Roland Kulcsár
* @since 1.0
*/
infix fun ControllerLinkBuilder.withRel(rel: String): Link = withRel(rel)
/**
* Add [links] to the [R] resource.
*
* @author Roland Kulcsár
* @since 1.0
*/
fun <C, R : ResourceSupport> R.add(controller: Class<C>, links: LinkBuilderDsl<C, R>.(R) -> Unit): R {
val builder = LinkBuilderDsl(controller, this)
builder.links(this)
return this
}
/**
* Add [links] to the [R] resource.
*
* @author Roland Kulcsár
* @since 1.0
*/
fun <C : Any, R : ResourceSupport> R.add(controller: KClass<C>, links: LinkBuilderDsl<C, R>.(R) -> Unit): R {
return add(controller.java, links)
}
/**
* Provide a [LinkBuilder] DSL to help write idiomatic Kotlin code.
*
* @author Roland Kulcsár
* @since 1.0
*/
open class LinkBuilderDsl<C, R : ResourceSupport>(val controller: Class<C>, val resource: R) {
/**
* Create a [ControllerLinkBuilder] pointing to [func] method.
*/
fun <R> linkTo(func: C.() -> R): ControllerLinkBuilder = linkTo(methodOn(controller).run(func))
/**
* Add a link with the given [rel] to the [resource].
*/
infix fun ControllerLinkBuilder.withRel(rel: String): Link {
val link = withRel(rel)
resource.add(link)
return link
}
}

View File

@@ -0,0 +1,94 @@
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.hateoas
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.springframework.http.HttpMethod
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
/**
* Unit tests for [LinkBuilderDsl] and [AffordanceBuilderDsl].
*
* @author Roland Kulcsár
*/
class AffordanceBuilderDslUnitTest : TestUtils() {
/**
* @see #715
*/
@Test
fun `creates affordance to controller method`() {
val delete = afford<CustomerController> { delete("15") }
assertThat(delete.httpMethod).isEqualTo(HttpMethod.DELETE)
assertThat(delete.name).isEqualTo("delete")
}
/**
* @see #715
*/
@Test
fun `creates link to controller method with affordances`() {
val id = "15"
val self = linkTo<CustomerController> { findById(id) } withRel Link.REL_SELF
val selfWithAffordances = self andAffordances {
afford<CustomerController> { update(id, CustomerDTO("John Doe")) }
afford<CustomerController> { delete(id) }
}
assertThat(selfWithAffordances.rel).isEqualTo(Link.REL_SELF)
assertThat(selfWithAffordances.href).isEqualTo("http://localhost/customers/15")
assertThat(selfWithAffordances.affordances).hasSize(3)
assertThat(selfWithAffordances.affordances[0].httpMethod).isEqualTo(HttpMethod.GET)
assertThat(selfWithAffordances.affordances[0].name).isEqualTo("findById")
assertThat(selfWithAffordances.affordances[1].httpMethod).isEqualTo(HttpMethod.PUT)
assertThat(selfWithAffordances.affordances[1].name).isEqualTo("update")
assertThat(selfWithAffordances.affordances[2].httpMethod).isEqualTo(HttpMethod.DELETE)
assertThat(selfWithAffordances.affordances[2].name).isEqualTo("delete")
assertThat(selfWithAffordances.hashCode()).isNotEqualTo(self.hashCode())
assertThat(selfWithAffordances).isNotEqualTo(self)
}
data class Customer(val id: String, val name: String)
data class CustomerDTO(val name: String)
open class CustomerResource(val id: String, val name: String) : ResourceSupport()
open class ProductResource(val id: String) : ResourceSupport()
@RequestMapping("/customers")
interface CustomerController {
@GetMapping("/{id}")
fun findById(@PathVariable id: String): ResponseEntity<CustomerResource>
@GetMapping("/{id}/products")
fun findProductsById(@PathVariable id: String): PagedResources<ProductResource>
@PutMapping("/{id}")
fun update(@PathVariable id: String, @RequestBody customer: CustomerDTO): ResponseEntity<CustomerResource>
@DeleteMapping("/{id}")
fun delete(@PathVariable id: String): ResponseEntity<Unit>
}
}

View File

@@ -0,0 +1,102 @@
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.hateoas
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
/**
* Unit tests for [LinkBuilderDsl] and [AffordanceBuilderDsl].
*
* @author Roland Kulcsár
*/
class LinkBuilderDslUnitTest : TestUtils() {
private val REL_PRODUCTS = "products"
/**
* @see #715
*/
@Test
fun `creates link to controller method`() {
val self = linkTo<CustomerController> { findById("15") } withRel Link.REL_SELF
assertPointsToMockServer(self)
assertThat(self.rel).isEqualTo(Link.REL_SELF)
assertThat(self.href).endsWith("/customers/15")
}
/**
* @see #715
*/
@Test
fun `adds links to wrapped domain object`() {
val customer = Resource(Customer("15", "John Doe"))
customer.add(CustomerController::class) {
linkTo { findById(it.content.id) } withRel Link.REL_SELF
linkTo { findProductsById(it.content.id) } withRel REL_PRODUCTS
}
customer.links.forEach { assertPointsToMockServer(it) }
assertThat(customer.hasLink(Link.REL_SELF)).isTrue()
assertThat(customer.hasLink(REL_PRODUCTS)).isTrue()
}
/**
* @see #715
*/
@Test
fun `adds links to resourcesupport object`() {
val customer = CustomerResource("15", "John Doe")
customer.add(CustomerController::class) {
linkTo { findById(it.id) } withRel Link.REL_SELF
linkTo { findProductsById(it.id) } withRel REL_PRODUCTS
}
customer.links.forEach { assertPointsToMockServer(it) }
assertThat(customer.hasLink(Link.REL_SELF)).isTrue()
assertThat(customer.hasLink(REL_PRODUCTS)).isTrue()
}
data class Customer(val id: String, val name: String)
data class CustomerDTO(val name: String)
open class CustomerResource(val id: String, val name: String) : ResourceSupport()
open class ProductResource(val id: String) : ResourceSupport()
@RequestMapping("/customers")
interface CustomerController {
@GetMapping("/{id}")
fun findById(@PathVariable id: String): ResponseEntity<CustomerResource>
@GetMapping("/{id}/products")
fun findProductsById(@PathVariable id: String): PagedResources<ProductResource>
@PutMapping("/{id}")
fun update(@PathVariable id: String, @RequestBody customer: CustomerDTO): ResponseEntity<CustomerResource>
@DeleteMapping("/{id}")
fun delete(@PathVariable id: String): ResponseEntity<Unit>
}
}