Skip to content

Instantly share code, notes, and snippets.

@dalexandrov
Created March 12, 2021 10:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dalexandrov/a971a37ebba2ce5e77a857a3b1c68789 to your computer and use it in GitHub Desktop.
Save dalexandrov/a971a37ebba2ce5e77a857a3b1c68789 to your computer and use it in GitHub Desktop.
@Path("/greet")
@RequestScoped
open class GreetResource
/**
* Using constructor injection to get a configuration property.
* By default this gets the value from META-INF/microprofile-config
*
*/ @Inject constructor(
/**
* The greeting message provider.
*/
private val greetingProvider: GreetingProvider) {
/**
* Return a worldly greeting message.
*
* @return [JsonObject]
*/
@get:Produces(MediaType.APPLICATION_JSON)
@get:GET
open val defaultMessage: JsonObject
get() = createResponse("World")
/**
* Return a greeting message using the name that was provided.
*
* @param name the name to greet
* @return [JsonObject]
*/
@Path("/{name}")
@GET
@Produces(MediaType.APPLICATION_JSON)
open fun getMessage(@PathParam("name") name: String): JsonObject {
return createResponse(name)
}
/**
* Set the greeting to use in future messages.
*
* @param jsonObject JSON containing the new greeting
* @return [Response]
*/
@Path("/greeting")
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@RequestBody(name = "greeting", required = true, content = [Content(mediaType = "application/json", schema = Schema(type = SchemaType.STRING, example = "{\"greeting\" : \"Hola\"}"))])
@APIResponses(APIResponse(name = "normal", responseCode = "204", description = "Greeting updated"), APIResponse(name = "missing 'greeting'", responseCode = "400", description = "JSON did not contain setting for 'greeting'"))
open fun updateGreeting(jsonObject: JsonObject): Response {
if (!jsonObject.containsKey("greeting")) {
val entity = JSON.createObjectBuilder()
.add("error", "No greeting provided")
.build()
return Response.status(Response.Status.BAD_REQUEST).entity(entity).build()
}
val newGreeting = jsonObject.getString("greeting")
greetingProvider.setMessage(newGreeting)
return Response.status(Response.Status.NO_CONTENT).build()
}
private fun createResponse(who: String): JsonObject {
val msg = String.format("%s %s!", greetingProvider.getMessage(), who)
return JSON.createObjectBuilder()
.add("message", msg)
.build()
}
companion object {
private val JSON = Json.createBuilderFactory(emptyMap<String, Any>())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment