Created
February 5, 2017 18:27
-
-
Save tuesd4y/714496072e3c553518a599f39394e068 to your computer and use it in GitHub Desktop.
abstract User Checking RestResource
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package at.tnzstz.rest | |
import at.tnzstz.authentication.Authenticated | |
import at.tnzstz.cdi.ReflectionHelper | |
import at.tnzstz.entity.User | |
import at.tnzstz.interfaces.AbstractEntity | |
import at.tnzstz.persistence.UserCheckingFacade | |
import io.swagger.annotations.Api | |
import javax.json.JsonObject | |
import javax.ws.rs.* | |
import javax.ws.rs.core.Context | |
import javax.ws.rs.core.MediaType | |
import javax.ws.rs.core.Response | |
import kotlin.reflect.jvm.javaType | |
import kotlin.reflect.memberProperties | |
/** | |
* @author Christopher Stelzmüller | |
* @version 1.0 | |
* created on 14.11.2016 | |
*/ | |
@Api | |
@Authenticated | |
abstract class RestResource<T> where T: AbstractEntity { | |
open val baseFacade: UserCheckingFacade<T> | |
get() { | |
val typeName = ReflectionHelper.getParameterClassOfRestResource(javaClass).simpleName | |
val expectedFacadeName = typeName.toLowerCase() + "Facade" | |
val expectedFacadeTypeName = "${UserCheckingFacade::class.java.`package`.name}.${typeName}Facade" | |
val property = javaClass.kotlin | |
.memberProperties | |
.filter { | |
it.name == expectedFacadeName || it.returnType.javaType.typeName == expectedFacadeTypeName | |
} | |
.firstOrNull() | |
if(property != null) { | |
@Suppress("UNCHECKED_CAST") | |
return property.get(this) as UserCheckingFacade<T> | |
} else throw Exception("There should be a property of type ${UserCheckingFacade::class.java.simpleName}<$typeName> with the name $expectedFacadeName if baseFacade is not overridden... ") | |
} | |
@GET | |
@Produces(MediaType.APPLICATION_JSON) | |
open fun get(@Context user: User): List<T> { | |
return baseFacade.findAll(user) | |
} | |
@GET | |
@Path("{id}") | |
@Produces(MediaType.APPLICATION_JSON) | |
open fun get(@PathParam("id") id: Long, @Context user: User): Response { | |
val e = baseFacade.findById(id, user) | |
e ?: return Response | |
.status(Response.Status.NOT_FOUND) | |
.build() | |
return Response.ok(e).build() | |
} | |
@POST | |
@Consumes(MediaType.APPLICATION_JSON) | |
@Produces(MediaType.APPLICATION_JSON) | |
abstract fun create(entity: JsonObject, @Context user: User): Response | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment