Skip to content

Instantly share code, notes, and snippets.

View oharaandrew314's full-sized avatar

Andrew O'Hara oharaandrew314

View GitHub Profile
@oharaandrew314
oharaandrew314 / OkHttpXrayInterceptor.kt
Last active February 1, 2018 20:10
An OKHttp Interceptor to emit a trace to AWS X-Ray
import com.amazonaws.xray.AWSXRay
import com.amazonaws.xray.entities.Namespace
import com.amazonaws.xray.entities.Subsegment
import com.amazonaws.xray.exceptions.SegmentNotFoundException
import okhttp3.Interceptor
import okhttp3.Response
/**
* An OKHttp Interceptor to emit an HTTP request trace to AWS X-Ray
*
import io.javalin.Javalin
import io.javalin.http.Context
import io.javalin.plugin.openapi.OpenApiOptions
import io.javalin.plugin.openapi.OpenApiPlugin
import io.javalin.plugin.openapi.annotations.OpenApi
import io.javalin.plugin.openapi.annotations.OpenApiParam
import io.javalin.plugin.openapi.ui.ReDocOptions
import io.javalin.plugin.openapi.ui.SwaggerOptions
import io.swagger.v3.oas.models.info.Info
class PetsDao(private val dataSource: DataSource) {
private object Sql {
const val get = """
SELECT pets.*, GROUP_CONCAT(photos.url) photo_urls
FROM pets
LEFT JOIN photos ON photos.pet_id = pets.id
WHERE pets.id = ?
GROUP BY pets.id
"""
data class Pet(
val id: Long,
val name: String,
val photoUrls: List<String>
)
class PetsDaoTest {
private val testObj = PetsDao.mock()
@Test
fun `get missing`() {
testObj[123] shouldBe null
}
@Test
class FakeThirdPartyImageBackend: HttpHandler {
private var nextId = 0
val images = mutableListOf<ThirdPartyImageDto>()
private fun upload(request: Request): Response {
val id = "image${nextId++}"
val image = ThirdPartyImageDto(
id = id,
class PetService(private val pets: PetsDao, private val images: ThirdPartyImageClient) {
fun get(id: Long): Pet? {
return pets[id]
}
fun create(name: String): Pet {
val id = pets.create(name)
return pets[id] ?: throw IllegalStateException("Pet was not created")
}
class RestApi(private val pets: PetService) {
companion object {
val petIdLens = Path.long().of("petId")
val petLens = Body.auto<Pet>().toLens()
val nameLens = Query.nonEmptyString().required("name")
const val petsPath = "/pet"
val petPath = "/pet/${petIdLens}"
val uploadImagePath = "/pet/${petIdLens}/uploadImage"
class RestApiTest {
private val imageBackend = FakeThirdPartyImageBackend()
private val petService = PetService(
pets = PetsDao.mock(),
images = ThirdPartyImageClient(imageBackend)
)
private val testObj = RestApi(petService).toHttpHandler()
fun main() {
val imagesHost = System.getenv("IMAGES_HOST")
val imagesApiKey = System.getenv("IMAGES_API_KEY")
val dbHost = System.getenv("DB_HOST")
val dbUser = System.getenv("DB_USER")
val dbPass = System.getenv("DB_PASS")
val dbName = System.getenv("DB_NAME")
val dataSource = MysqlDataSource().apply {