├── settings.gradle
├── sorted_data.png
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradle.properties
├── .idea
├── codeStyles
│ ├── codeStyleConfig.xml
│ └── Project.xml
└── vcs.xml
├── src
├── main
│ ├── kotlin
│ │ └── com
│ │ │ └── santansarah
│ │ │ ├── utils
│ │ │ ├── RoutesList.kt
│ │ │ ├── Results.kt
│ │ │ ├── DateTime.kt
│ │ │ └── AppErrorCodes.kt
│ │ │ ├── data
│ │ │ ├── CityModel.kt
│ │ │ ├── CityDaoInterface.kt
│ │ │ ├── DaoInterface.kt
│ │ │ ├── Database.kt
│ │ │ ├── UserModel.kt
│ │ │ ├── Tables.kt
│ │ │ ├── CityDaoImpl.kt
│ │ │ ├── UserDaoImpl.kt
│ │ │ └── UserAppDaoImpl.kt
│ │ │ ├── domain
│ │ │ ├── CityResponse.kt
│ │ │ ├── UserResponse.kt
│ │ │ └── usecases
│ │ │ │ ├── ValidateUserApp.kt
│ │ │ │ ├── ValidateUserEmail.kt
│ │ │ │ ├── InsertNewUser.kt
│ │ │ │ ├── GenerateApiKey.kt
│ │ │ │ ├── EncryptApiKey.kt
│ │ │ │ └── InsertNewUserApp.kt
│ │ │ ├── plugins
│ │ │ ├── Serialization.kt
│ │ │ ├── Koin.kt
│ │ │ ├── Routing.kt
│ │ │ ├── JWT.kt
│ │ │ ├── Security.kt
│ │ │ └── StatusExceptions.kt
│ │ │ ├── Application.kt
│ │ │ ├── UserRoutes.kt
│ │ │ ├── AppRoutes.kt
│ │ │ └── CityRoutes.kt
│ └── resources
│ │ ├── logback.xml
│ │ └── application.conf
└── test
│ └── kotlin
│ └── com
│ └── santansarah
│ └── ApplicationTest.kt
├── .gitignore
├── LICENSE.md
├── license.md
├── gradlew.bat
├── README.md
└── gradlew
/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = "com.santansarah.cityapi"
--------------------------------------------------------------------------------
/sorted_data.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/santansarah/ktor-city-api/HEAD/sorted_data.png
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/santansarah/ktor-city-api/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | ktor_version=2.0.3
2 | kotlin_version=1.7.10
3 | logback_version=1.2.11
4 | kotlin.code.style=official
5 | exposedVersion=0.38.2
6 | koin_version=3.2.0
7 |
--------------------------------------------------------------------------------
/.idea/codeStyles/codeStyleConfig.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/src/main/kotlin/com/santansarah/utils/RoutesList.kt:
--------------------------------------------------------------------------------
1 | package com.santansarah.utils
2 |
3 | object AppRoutes {
4 | const val USERS_ROUTE = "/users"
5 | const val APPS_ROUTE = "/apps"
6 | }
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/src/main/kotlin/com/santansarah/data/CityModel.kt:
--------------------------------------------------------------------------------
1 | package com.santansarah.data
2 |
3 | @kotlinx.serialization.Serializable
4 | data class City(
5 | val zip: Int = 0,
6 | val lat: Double = 0.0,
7 | val lng: Double = 0.0,
8 | val city: String = "",
9 | val state: String = "",
10 | val population: Int = 0
11 | )
12 |
--------------------------------------------------------------------------------
/src/main/kotlin/com/santansarah/utils/Results.kt:
--------------------------------------------------------------------------------
1 | package com.santansarah.utils
2 |
3 | /**
4 | * Generic results class that's returned in DAO calls and Validation
5 | * checks.
6 | */
7 | sealed class ServiceResult {
8 | data class Success(val data: T) : ServiceResult()
9 | data class Error(val error: ErrorCode) : ServiceResult()
10 | }
11 |
--------------------------------------------------------------------------------
/src/main/kotlin/com/santansarah/data/CityDaoInterface.kt:
--------------------------------------------------------------------------------
1 | package com.santansarah.data
2 |
3 | import com.santansarah.utils.ServiceResult
4 |
5 | /**
6 | * DAO Interface.
7 | */
8 | interface CityDaoInterface {
9 | suspend fun getCitiesByName(prefix: String): ServiceResult>
10 | suspend fun getCitiesByZip(prefix: String): ServiceResult>
11 | }
12 |
13 |
--------------------------------------------------------------------------------
/src/main/kotlin/com/santansarah/utils/DateTime.kt:
--------------------------------------------------------------------------------
1 | package com.santansarah.utils
2 |
3 | import java.time.LocalDateTime
4 | import java.time.format.DateTimeFormatter
5 |
6 | private const val DATE_FORMAT = "yyyy-MM-dd hh:mm:ss"
7 |
8 | fun LocalDateTime.toDatabaseString(): String {
9 | val formatter = DateTimeFormatter.ofPattern(DATE_FORMAT)
10 | return formatter.format(this)
11 | }
12 |
--------------------------------------------------------------------------------
/.idea/codeStyles/Project.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/src/main/resources/logback.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | %d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/src/main/kotlin/com/santansarah/domain/CityResponse.kt:
--------------------------------------------------------------------------------
1 | package com.santansarah.domain
2 |
3 | import com.santansarah.data.City
4 | import com.santansarah.data.User
5 | import com.santansarah.data.UserApp
6 | import com.santansarah.data.UserWithApp
7 | import com.santansarah.utils.ErrorCode
8 |
9 | @kotlinx.serialization.Serializable
10 | data class CityResponse(
11 | val userWithApp: UserWithApp = UserWithApp(),
12 | val cities: List = emptyList(),
13 | val errors: List = emptyList()
14 | )
15 |
--------------------------------------------------------------------------------
/src/main/kotlin/com/santansarah/plugins/Serialization.kt:
--------------------------------------------------------------------------------
1 | package com.santansarah.plugins
2 |
3 | import io.ktor.serialization.kotlinx.json.*
4 | import io.ktor.server.plugins.contentnegotiation.*
5 | import io.ktor.server.application.*
6 | import io.ktor.server.response.*
7 | import io.ktor.server.request.*
8 | import io.ktor.server.routing.*
9 |
10 | fun Application.configureSerialization() {
11 | install(ContentNegotiation) {
12 | json()
13 | }
14 |
15 | routing {
16 | get("/json/kotlinx-serialization") {
17 | call.respond(mapOf("hello" to "world"))
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/resources/application.conf:
--------------------------------------------------------------------------------
1 | jwt {
2 | privateKey = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAtfJaLrzXILUg1U3N1KV8yJr92GHn5OtYZR7qWk1Mc4cy4JGjklYup7weMjBD9f3bBVoIsiUVX6xNcYIr0Ie0AQIDAQABAkEAg+FBquToDeYcAWBe1EaLVyC45HG60zwfG1S4S3IB+y4INz1FHuZppDjBh09jptQNd+kSMlG1LkAc/3znKTPJ7QIhANpyB0OfTK44lpH4ScJmCxjZV52mIrQcmnS3QzkxWQCDAiEA1Tn7qyoh+0rOO/9vJHP8U/beo51SiQMw0880a1UaiisCIQDNwY46EbhGeiLJR1cidr+JHl86rRwPDsolmeEF5AdzRQIgK3KXL3d0WSoS//K6iOkBX3KMRzaFXNnDl0U/XyeGMuUCIHaXv+n+Brz5BDnRbWS+2vkgIe9bUNlkiArpjWvX+2we"
3 | issuer = "http://127.0.0.1:8080/"
4 | audience = "http://127.0.0.1:8080/v1"
5 | realm = "Access to v1 endpoints"
6 | }
7 |
--------------------------------------------------------------------------------
/src/main/kotlin/com/santansarah/Application.kt:
--------------------------------------------------------------------------------
1 | package com.santansarah
2 |
3 | import com.santansarah.data.DatabaseFactory
4 | import com.santansarah.data.UserAppDao
5 | import com.santansarah.plugins.*
6 | import io.ktor.server.engine.*
7 | import io.ktor.server.netty.*
8 | import org.koin.ktor.ext.inject
9 |
10 |
11 | fun main() {
12 |
13 | embeddedServer(Netty, port = 8080, host = "127.0.0.1") {
14 | DatabaseFactory.init()
15 |
16 | configureStatusExceptions()
17 | configureKoin()
18 | configureRouting()
19 | configureSerialization()
20 | configureSecurity()
21 |
22 | }.start(wait = true)
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/kotlin/com/santansarah/data/DaoInterface.kt:
--------------------------------------------------------------------------------
1 | package com.santansarah.data
2 |
3 | import com.santansarah.utils.ServiceResult
4 |
5 | /**
6 | * [User] DAO Interface.
7 | */
8 | interface UserDao {
9 | suspend fun doesUserExist(userId: Int, email: String): ServiceResult
10 | suspend fun insertUser(user: User): ServiceResult
11 | }
12 |
13 | /**
14 | * [UserApp] interface.
15 | */
16 | interface UserAppDao {
17 | suspend fun getUserWithApp(apiKey: String): ServiceResult
18 | suspend fun checkForDupApp(userWithApp: UserWithApp): ServiceResult
19 | suspend fun insertUserApp(userWithApp: UserWithApp): ServiceResult
20 |
21 | }
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /us-cities
2 |
3 | build
4 | .gradle
5 | .gradletasknamecache
6 | .idea/*
7 | !.idea/runConfigurations
8 | !.idea/runConfigurations/*
9 | !.idea/vcs.xml
10 | !.idea/dictionaries
11 | !.idea/dictionaries/*
12 | !.idea/copyright
13 | !.idea/copyright/*
14 | !.idea/codeStyles
15 | !.idea/codeStyles/*
16 | !.idea/icon.png
17 | out
18 | *.iml
19 | .vscode
20 |
21 | *.versionsBackup
22 | *.releaseBackup
23 | release.properties
24 | local.properties
25 | *.swp
26 |
27 | .video
28 | .attach_pid*
29 |
30 |
31 | bin/
32 | .settings
33 | .project
34 | .classpath
35 | .konan
36 |
37 | .DS_Store
38 |
39 | hs_err_pid*.log
40 |
41 | gradle-user-home
42 |
43 |
44 | /us-cities-journal
45 | /cities
46 |
--------------------------------------------------------------------------------
/src/main/kotlin/com/santansarah/domain/UserResponse.kt:
--------------------------------------------------------------------------------
1 | package com.santansarah.domain
2 |
3 | import com.santansarah.data.User
4 | import com.santansarah.data.UserApp
5 | import com.santansarah.data.UserWithApp
6 | import com.santansarah.utils.ErrorCode
7 |
8 | @kotlinx.serialization.Serializable
9 | data class UserResponse(
10 | val user: User,
11 | val errors: List = emptyList()
12 | )
13 |
14 | @kotlinx.serialization.Serializable
15 | data class UserAppResponse(
16 | val userWithApp: UserWithApp,
17 | val errors: List = emptyList()
18 | )
19 |
20 | @kotlinx.serialization.Serializable
21 | data class ResponseErrors(val code: ErrorCode, val message: String)
22 |
--------------------------------------------------------------------------------
/src/main/kotlin/com/santansarah/domain/usecases/ValidateUserApp.kt:
--------------------------------------------------------------------------------
1 | package com.santansarah.domain.usecases
2 |
3 | import com.santansarah.data.AppType
4 | import com.santansarah.data.UserApp
5 | import com.santansarah.data.UserWithApp
6 | import com.santansarah.utils.ErrorCode
7 | import com.santansarah.utils.ServiceResult
8 |
9 | class ValidateUserApp() {
10 |
11 | operator fun invoke(userWithApp: UserWithApp): ServiceResult {
12 |
13 | return if (userWithApp.appName.isBlank() ||
14 | userWithApp.appType == AppType.NOTSET || userWithApp.email.isNullOrBlank())
15 | ServiceResult.Error(ErrorCode.INVALID_APP)
16 | else
17 | ServiceResult.Success(true)
18 |
19 | }
20 |
21 | }
--------------------------------------------------------------------------------
/src/test/kotlin/com/santansarah/ApplicationTest.kt:
--------------------------------------------------------------------------------
1 | package com.santansarah
2 |
3 | import io.ktor.server.routing.*
4 | import io.ktor.http.*
5 | import io.ktor.serialization.kotlinx.json.*
6 | import io.ktor.server.plugins.contentnegotiation.*
7 | import io.ktor.server.auth.*
8 | import io.ktor.util.*
9 | import io.ktor.server.application.*
10 | import io.ktor.server.response.*
11 | import io.ktor.server.request.*
12 | import io.ktor.client.request.*
13 | import io.ktor.client.statement.*
14 | import kotlin.test.*
15 | import io.ktor.server.testing.*
16 | import com.santansarah.plugins.*
17 |
18 | class ApplicationTest {
19 | @Test
20 | fun testRoot() = testApplication {
21 | application {
22 | //configureRouting()
23 | }
24 | client.get("/").apply {
25 | assertEquals(HttpStatusCode.OK, status)
26 | assertEquals("Hello World!", bodyAsText())
27 | }
28 | }
29 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/santansarah/domain/usecases/ValidateUserEmail.kt:
--------------------------------------------------------------------------------
1 | package com.santansarah.domain.usecases
2 |
3 | import com.santansarah.data.User
4 | import com.santansarah.utils.ErrorCode
5 | import com.santansarah.utils.ServiceResult
6 |
7 | class ValidateUserEmail() {
8 |
9 | companion object {
10 | private val EMAIL_REGEX = Regex(
11 | "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
12 | "\\@" +
13 | "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
14 | "(" +
15 | "\\." +
16 | "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
17 | ")+"
18 | )
19 | }
20 |
21 | operator fun invoke(user: User): ServiceResult {
22 |
23 | return if (user.email.isBlank() || !user.email.matches(EMAIL_REGEX))
24 | ServiceResult.Error(ErrorCode.INVALID_EMAIL)
25 | else
26 | ServiceResult.Success(true)
27 | }
28 |
29 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/santansarah/data/Database.kt:
--------------------------------------------------------------------------------
1 | package com.santansarah.data
2 |
3 | import kotlinx.coroutines.*
4 | import org.jetbrains.exposed.sql.*
5 | import org.jetbrains.exposed.sql.transactions.*
6 | import org.jetbrains.exposed.sql.transactions.experimental.*
7 |
8 | /**
9 | * I'm using SQLite. My [Users] table is created if it doesn't exist.
10 | */
11 | object DatabaseFactory {
12 | fun init() {
13 | val driverClassName = "org.sqlite.JDBC"
14 | val jdbcURL = "jdbc:sqlite:./cities"
15 | val database = Database.connect(jdbcURL, driverClassName)
16 |
17 | transaction {
18 | SchemaUtils.create(Users, UserApps)
19 | }
20 | }
21 |
22 | /**
23 | * Exposed transactions are blocking. Here I
24 | * start each query in its own coroutine and make
25 | * DB calls async on the [Dispatchers.IO] thread.
26 | */
27 | suspend fun dbQuery(block: suspend () -> T): T =
28 | newSuspendedTransaction(Dispatchers.IO) { block() }
29 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/santansarah/plugins/Koin.kt:
--------------------------------------------------------------------------------
1 | package com.santansarah.plugins
2 |
3 | import com.santansarah.data.*
4 | import com.santansarah.domain.usecases.*
5 | import io.ktor.server.application.*
6 | import org.koin.dsl.module
7 | import org.koin.ktor.plugin.Koin
8 | import org.koin.logger.slf4jLogger
9 |
10 | fun Application.configureKoin() {
11 | install(Koin) {
12 | slf4jLogger()
13 | modules(cityModule)
14 | }
15 | }
16 |
17 | /**
18 | * [InsertNewUser] expects a Dao + ValidateUserEmail Use Case.
19 | * Here, I tell Koin how to create each...then get magically
20 | * injects them into the service.
21 | */
22 | val cityModule = module {
23 | single { UserDaoImpl() }
24 | single { ValidateUserEmail() }
25 | single { InsertNewUser(get(), get()) }
26 |
27 | single { UserAppDaoImpl() }
28 | single { ValidateUserApp() }
29 | single { GenerateApiKey() }
30 | single { InsertNewUserApp(get(), get(), get(), get()) }
31 |
32 | single { CityDaoImpl() }
33 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/santansarah/UserRoutes.kt:
--------------------------------------------------------------------------------
1 | package com.santansarah
2 |
3 | import com.santansarah.data.User
4 | import com.santansarah.domain.usecases.InsertNewUser
5 | import io.ktor.http.*
6 | import io.ktor.server.application.*
7 | import io.ktor.server.request.*
8 | import io.ktor.server.response.*
9 | import io.ktor.server.routing.*
10 |
11 | fun Route.newAccount(
12 | insertNewUser: InsertNewUser
13 | ) {
14 | post("users/create") {
15 | /**
16 | * Return if the user object is null.
17 | */
18 | val request = call.receiveOrNull() ?: kotlin.run {
19 | call.respond(HttpStatusCode.BadRequest)
20 | return@post
21 | }
22 |
23 | /**
24 | * Validate the [User] object and insert if everything's good.
25 | */
26 | val userResponse = insertNewUser(request)
27 | var httpStatus = if (userResponse.errors.isEmpty()) HttpStatusCode.Created else HttpStatusCode.BadRequest
28 |
29 | call.respond(
30 | status = httpStatus,
31 | message = userResponse
32 | )
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2022 Sarah Brenner
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/license.md:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2022 Sarah Brenner
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/src/main/kotlin/com/santansarah/data/UserModel.kt:
--------------------------------------------------------------------------------
1 | package com.santansarah.data
2 |
3 | import kotlinx.serialization.SerialName
4 | import kotlinx.serialization.Serializable
5 |
6 | @Serializable
7 | data class User(
8 | val userId: Int = 0,
9 | val email: String = "",
10 | val userCreateDate: String = "",
11 | val apps: List = emptyList()
12 | )
13 |
14 | @Serializable
15 | data class UserApp(
16 | val userAppId: Int = 0,
17 | val userId: Int = 0,
18 | val appName: String = "",
19 | val appType: AppType = AppType.NOTSET,
20 | val apiKey: String = "",
21 | val appCreateDate: String = ""
22 | )
23 |
24 | @Serializable
25 | data class UserWithApp(
26 | val userId: Int = 0,
27 | val email: String = "",
28 | val userCreateDate: String = "",
29 | val userAppId: Int = 0,
30 | val appName: String = "",
31 | val appType: AppType = AppType.NOTSET,
32 | val apiKey: String = "",
33 | val appCreateDate: String = ""
34 | )
35 |
36 | @Serializable
37 | enum class AppType(val value: Int) {
38 | NOTSET(0),
39 | @SerialName("dev") DEVELOPMENT(1),
40 | @SerialName("prod") PRODUCTION(2)
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/kotlin/com/santansarah/utils/AppErrorCodes.kt:
--------------------------------------------------------------------------------
1 | package com.santansarah.utils
2 |
3 | /**
4 | * Types of errors that routes could produce. These
5 | * codes are returned in the response body.
6 | */
7 | enum class ErrorCode(val message: String) {
8 | INVALID_USER("Invalid user object. Check your JSON values."),
9 | INVALID_EMAIL("Invalid email."),
10 | EMAIL_EXISTS("This email address is already registered."),
11 | API_KEY("There was a problem generating your API Key. Try again."),
12 | UNKNOWN("An unknown error has occurred."),
13 | UNKNOWN_USER("This user doesn't exist."),
14 | UNKNOWN_APP("This app doesn't exist."),
15 | APP_EXISTS("This app already exists."),
16 | INVALID_APP("UserId, email, app name, and app type can not be blank. Use 'dev' or 'prod' for app type."),
17 | DATABASE_ERROR("Unknown database error. Try again, and check your parameters."),
18 | INVALID_JSON("Your JSON must match the format in this sample response."),
19 | INVALID_CITY_QUERY("You must pass a city name or zip prefix."),
20 | INVALID_API_KEY("Bad API key. Use x-api-key in the header.")
21 | }
22 |
23 | class AuthenticationException : RuntimeException()
--------------------------------------------------------------------------------
/src/main/kotlin/com/santansarah/plugins/Routing.kt:
--------------------------------------------------------------------------------
1 | package com.santansarah.plugins
2 |
3 | import com.santansarah.cityRouting
4 | import com.santansarah.data.CityDaoImpl
5 | import com.santansarah.data.CityDaoInterface
6 | import com.santansarah.domain.usecases.InsertNewUser
7 | import com.santansarah.domain.usecases.InsertNewUserApp
8 | import com.santansarah.newAccount
9 | import com.santansarah.newApp
10 | import io.ktor.server.application.*
11 | import io.ktor.server.response.*
12 | import io.ktor.server.routing.*
13 | import org.koin.ktor.ext.inject
14 |
15 | fun Application.configureRouting() {
16 |
17 | routing {
18 | get("/") {
19 | call.respondText("Hello World!")
20 | }
21 |
22 | // Lazy inject from within a Ktor Routing Node
23 | val insertService by inject()
24 |
25 | /**
26 | * User routes.
27 | */
28 | newAccount(insertService)
29 |
30 | /**
31 | * UserApp Routes
32 | */
33 | val insertAppService by inject()
34 | newApp(insertAppService)
35 |
36 | /**
37 | * City Routes
38 | */
39 | val cityDao by inject()
40 | cityRouting(cityDao)
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/main/kotlin/com/santansarah/AppRoutes.kt:
--------------------------------------------------------------------------------
1 | package com.santansarah
2 |
3 | import com.santansarah.data.User
4 | import com.santansarah.data.UserApp
5 | import com.santansarah.data.UserWithApp
6 | import com.santansarah.domain.usecases.InsertNewUser
7 | import com.santansarah.domain.usecases.InsertNewUserApp
8 | import io.ktor.http.*
9 | import io.ktor.server.application.*
10 | import io.ktor.server.request.*
11 | import io.ktor.server.response.*
12 | import io.ktor.server.routing.*
13 |
14 | fun Route.newApp(
15 | insertNewUserApp: InsertNewUserApp
16 | ) {
17 | post("apps/create") {
18 | /**
19 | * Return if the object is null.
20 | */
21 | val request = call.receiveOrNull() ?: kotlin.run {
22 | call.respond(HttpStatusCode.BadRequest)
23 | return@post
24 | }
25 |
26 | /**
27 | * Validate the [UserWithApp] object and insert if everything's good.
28 | */
29 | val userResponse = insertNewUserApp(request)
30 | var httpStatus = if (userResponse.errors.isEmpty()) HttpStatusCode.Created else HttpStatusCode.BadRequest
31 |
32 | call.respond(
33 | status = httpStatus,
34 | message = userResponse
35 | )
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/kotlin/com/santansarah/domain/usecases/InsertNewUser.kt:
--------------------------------------------------------------------------------
1 | package com.santansarah.domain.usecases
2 |
3 | import com.santansarah.data.User
4 | import com.santansarah.data.UserDao
5 | import com.santansarah.domain.ResponseErrors
6 | import com.santansarah.domain.UserResponse
7 | import com.santansarah.utils.ServiceResult
8 | import com.santansarah.utils.toDatabaseString
9 | import java.time.LocalDateTime
10 |
11 | class InsertNewUser
12 | (
13 | private val validateUserEmail: ValidateUserEmail,
14 | private val userDao: UserDao
15 | ) {
16 |
17 | suspend operator fun invoke(user: User): UserResponse {
18 |
19 | return when (val result = validateUserEmail(user)) {
20 | is ServiceResult.Success -> {
21 | val dbResult = userDao.insertUser(user.copy(
22 | userCreateDate = LocalDateTime.now().toDatabaseString())
23 | )
24 | when (dbResult) {
25 | is ServiceResult.Success -> UserResponse(dbResult.data, emptyList())
26 | is ServiceResult.Error -> UserResponse(user, listOf(ResponseErrors(dbResult.error, dbResult.error.message)))
27 | }
28 |
29 | }
30 | is ServiceResult.Error -> UserResponse(user, listOf(ResponseErrors(result.error, result.error.message)))
31 | }
32 | }
33 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/santansarah/domain/usecases/GenerateApiKey.kt:
--------------------------------------------------------------------------------
1 | package com.santansarah.domain.usecases
2 |
3 | import java.security.SecureRandom
4 |
5 |
6 | class GenerateApiKey() {
7 |
8 | /**
9 | * Shout out to: https://www.baeldung.com/kotlin/random-alphanumeric-string for
10 | * the great article.
11 | * [charPool] = letters and numbers to choose from to create a 15 char string
12 | */
13 | private val charPool: List = ('a'..'z') + ('A'..'Z') + ('0'..'9')
14 |
15 | operator fun invoke(): String {
16 | /**
17 | * [SecureRandom] generates a cryptographically strong random number generator (RNG).
18 | * To get a random number, you call `nextInt` and pass a range. In this function,
19 | * I'll use the [charPool] size, which will generate a random number from 0 to 62.
20 | */
21 | val random = SecureRandom()
22 | val bytes = ByteArray(16)
23 |
24 | /**
25 | * this gives me something like: charPool[5] = 'f' or charPool[59] = '7'
26 | */
27 | val apiKey = (0 until bytes.size - 1)
28 | .map { _ ->
29 | charPool[random.nextInt(charPool.size)]
30 | }.joinToString("")
31 |
32 | /**
33 | * this generates something like: u0LNanue58mApyD
34 | */
35 | println(apiKey)
36 | return apiKey
37 |
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/kotlin/com/santansarah/plugins/JWT.kt:
--------------------------------------------------------------------------------
1 | package com.santansarah.plugins
2 |
3 | import com.auth0.jwk.JwkProviderBuilder
4 | import io.ktor.http.*
5 | import io.ktor.server.application.*
6 | import io.ktor.server.auth.*
7 | import io.ktor.server.auth.jwt.*
8 | import io.ktor.server.response.*
9 | import java.util.concurrent.TimeUnit
10 |
11 | fun Application.configureJWT() {
12 |
13 | val privateKeyString = environment.config.property("jwt.privateKey").getString()
14 | val issuer = environment.config.property("jwt.issuer").getString()
15 | val audience = environment.config.property("jwt.audience").getString()
16 | val myRealm = environment.config.property("jwt.realm").getString()
17 | val jwkProvider = JwkProviderBuilder(issuer)
18 | .cached(10, 24, TimeUnit.HOURS)
19 | .rateLimited(10, 1, TimeUnit.MINUTES)
20 | .build()
21 | install(Authentication) {
22 | jwt("auth-jwt") {
23 | realm = myRealm
24 | verifier(jwkProvider, issuer) {
25 | acceptLeeway(3)
26 | }
27 | validate { credential ->
28 | if (credential.payload.getClaim("username").asString() != "") {
29 | JWTPrincipal(credential.payload)
30 | } else {
31 | null
32 | }
33 | }
34 | challenge { defaultScheme, realm ->
35 | call.respond(HttpStatusCode.Unauthorized, "Token is not valid or has expired")
36 | }
37 | }
38 |
39 | }
40 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/santansarah/plugins/Security.kt:
--------------------------------------------------------------------------------
1 | package com.santansarah.plugins
2 |
3 | import com.santansarah.data.UserAppDao
4 | import com.santansarah.data.UserWithApp
5 | import com.santansarah.utils.AuthenticationException
6 | import com.santansarah.utils.ServiceResult
7 | import dev.forst.ktor.apikey.apiKey
8 | import io.ktor.http.*
9 | import io.ktor.server.auth.*
10 | import io.ktor.util.*
11 | import io.ktor.server.application.*
12 | import io.ktor.server.response.*
13 | import io.ktor.server.request.*
14 | import io.ktor.server.routing.*
15 | import org.koin.core.component.KoinComponent
16 | import org.koin.ktor.ext.inject
17 |
18 | // principal for the app
19 | data class AppPrincipal(val userWithApp: UserWithApp) : Principal
20 |
21 | fun Application.configureSecurity() {
22 |
23 | val userAppDao by inject()
24 |
25 | install(Authentication) {
26 | // and then api key provider
27 | apiKey {
28 | challenge {
29 | throw AuthenticationException()
30 | }
31 |
32 | /**
33 | * get the [UserWithApp] from the api key. if it comes back with
34 | * a match, send the AppPrincipal & authenticate.
35 | */
36 | validate { keyFromHeader ->
37 | when (val userWithApp = userAppDao.getUserWithApp(keyFromHeader)) {
38 | is ServiceResult.Error -> null
39 | is ServiceResult.Success -> AppPrincipal(userWithApp.data)
40 | }
41 | }
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/main/kotlin/com/santansarah/data/Tables.kt:
--------------------------------------------------------------------------------
1 | package com.santansarah.data
2 |
3 | import org.jetbrains.exposed.sql.Table
4 |
5 |
6 | /**
7 | * Create a [User] table, and add a unique constraint
8 | * to email. The userId is [autoIncrement] - I'll get
9 | * the whole record back from my DAO on insert.
10 | */
11 | object Users : Table() {
12 | val userId = integer("userId").autoIncrement()
13 | val email = varchar("email", 255)
14 | .uniqueIndex()
15 | val userCreateDate = varchar("userCreateDate", length = 255)
16 |
17 | override val primaryKey = PrimaryKey(userId)
18 | }
19 |
20 | /**
21 | * [userId] is indexed for faster processing, and references the
22 | * [Users] table. [apiKey] must be unique. It will throw in
23 | * [UserAppDaoImpl] if it's not.
24 | */
25 | object UserApps : Table() {
26 | val userAppId = integer("userAppId").autoIncrement()
27 | val userId = integer("userId")
28 | .index(isUnique = false)
29 | .references(Users.userId) // Users is parent.
30 | val appName = varchar("appName", 255)
31 | val appType = enumeration("appType")
32 | val apiKey = varchar("apiKey", 255)
33 | .uniqueIndex()
34 | val userAppCreateDate = varchar("userAppCreateDate", 255)
35 |
36 | override val primaryKey = PrimaryKey(userAppId)
37 | }
38 |
39 | /**
40 | * City table. This one doesn't need to be created in the factory.
41 | */
42 | object Cities : Table() {
43 | val zip = integer("zip")
44 | val lat = double("lat")
45 | val lng = double("lng")
46 | val city = varchar("city", 255)
47 | val state = varchar("state_id", 255)
48 | val population = integer("population")
49 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/santansarah/domain/usecases/EncryptApiKey.kt:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | /*
6 |
7 | object AESEncyption {
8 |
9 | const val secretKey = "tK5UTui+DPh8lIlBxya5XVsmeDCoUl6vHhdIESMB6sQ="
10 | const val salt = "QWlGNHNhMTJTQWZ2bGhpV3U=" // base64 decode => AiF4sa12SAfvlhiWu
11 | const val iv = "bVQzNFNhRkQ1Njc4UUFaWA==" // base64 decode => mT34SaFD5678QAZX
12 |
13 | fun encrypt(strToEncrypt: String) : String?
14 | {
15 | try
16 | {
17 | val ivParameterSpec = IvParameterSpec(Base64.decode(iv, Base64.DEFAULT))
18 |
19 | val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1")
20 | val spec = PBEKeySpec(secretKey.toCharArray(), Base64.decode(salt, Base64.DEFAULT), 10000, 256)
21 | val tmp = factory.generateSecret(spec)
22 | val secretKey = SecretKeySpec(tmp.encoded, "AES")
23 |
24 | val cipher = Cipher.getInstance("AES/CBC/PKCS7Padding")
25 | cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec)
26 | return Base64.encodeToString(cipher.doFinal(strToEncrypt.toByteArray(Charsets.UTF_8)), Base64.DEFAULT)
27 | }
28 | catch (e: Exception)
29 | {
30 | println("Error while encrypting: $e")
31 | }
32 | return null
33 | }
34 |
35 | fun decrypt(strToDecrypt : String) : String? {
36 | try
37 | {
38 |
39 | val ivParameterSpec = IvParameterSpec(Base64.decode(iv, Base64.DEFAULT))
40 |
41 | val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1")
42 | val spec = PBEKeySpec(secretKey.toCharArray(), Base64.decode(salt, Base64.DEFAULT), 10000, 256)
43 | val tmp = factory.generateSecret(spec);
44 | val secretKey = SecretKeySpec(tmp.encoded, "AES")
45 |
46 | val cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
47 | cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
48 | return String(cipher.doFinal(Base64.decode(strToDecrypt, Base64.DEFAULT)))
49 | }
50 | catch (e : Exception) {
51 | println("Error while decrypting: $e");
52 | }
53 | return null
54 | }
55 | }*/
56 |
--------------------------------------------------------------------------------
/src/main/kotlin/com/santansarah/domain/usecases/InsertNewUserApp.kt:
--------------------------------------------------------------------------------
1 | package com.santansarah.domain.usecases
2 |
3 | import com.santansarah.data.UserApp
4 | import com.santansarah.data.UserAppDao
5 | import com.santansarah.data.UserDao
6 | import com.santansarah.data.UserWithApp
7 | import com.santansarah.domain.ResponseErrors
8 | import com.santansarah.domain.UserAppResponse
9 | import com.santansarah.domain.UserResponse
10 | import com.santansarah.utils.ErrorCode
11 | import com.santansarah.utils.ServiceResult
12 | import com.santansarah.utils.toDatabaseString
13 | import java.time.LocalDateTime
14 |
15 | class InsertNewUserApp
16 | (
17 | private val validateUserApp: ValidateUserApp,
18 | private val generateApiKey: GenerateApiKey,
19 | private val userAppDao: UserAppDao,
20 | private val userDao: UserDao
21 | ) {
22 |
23 | suspend operator fun invoke(userWithApp: UserWithApp): UserAppResponse {
24 |
25 | // check for blank fields
26 | val validateAppResult = validateUserApp(userWithApp)
27 | if (validateAppResult is ServiceResult.Error) {
28 | return userResponseError(userWithApp, validateAppResult.error)
29 | }
30 |
31 | // make sure the user exists
32 | val checkUser = userDao.doesUserExist(userWithApp.userId, userWithApp.email)
33 | if (checkUser is ServiceResult.Error)
34 | return userResponseError(userWithApp, checkUser.error)
35 |
36 | // make sure this app + app type is unique
37 | val checkAppAndType = userAppDao.checkForDupApp(userWithApp)
38 | if (checkAppAndType is ServiceResult.Error) {
39 | return userResponseError(userWithApp, checkAppAndType.error)
40 | }
41 |
42 | // generate the api key and insert the new app
43 | val apiKey = generateApiKey()
44 | val dbResult = userAppDao.insertUserApp(userWithApp.copy(
45 | apiKey = apiKey,
46 | appCreateDate = LocalDateTime.now().toDatabaseString())
47 | )
48 |
49 | if (dbResult is ServiceResult.Error)
50 | return userResponseError(userWithApp, dbResult.error)
51 |
52 | // if the app was inserted, return the app w/the user info
53 | return when (val newApp = userAppDao.getUserWithApp(apiKey)) {
54 | is ServiceResult.Error -> userResponseError(userWithApp, newApp.error)
55 | is ServiceResult.Success -> UserAppResponse(newApp.data)
56 | }
57 |
58 | }
59 |
60 | private fun userResponseError(userWithApp: UserWithApp, errorCode: ErrorCode): UserAppResponse {
61 | return UserAppResponse(userWithApp, listOf(ResponseErrors(errorCode, errorCode.message)))
62 | }
63 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/santansarah/plugins/StatusExceptions.kt:
--------------------------------------------------------------------------------
1 | package com.santansarah.plugins
2 |
3 | import com.santansarah.data.AppType
4 | import com.santansarah.data.User
5 | import com.santansarah.data.UserApps
6 | import com.santansarah.data.UserWithApp
7 | import com.santansarah.domain.CityResponse
8 | import com.santansarah.domain.ResponseErrors
9 | import com.santansarah.domain.UserAppResponse
10 | import com.santansarah.domain.UserResponse
11 | import com.santansarah.utils.AppRoutes
12 | import com.santansarah.utils.AuthenticationException
13 | import com.santansarah.utils.ErrorCode
14 | import io.ktor.http.*
15 | import io.ktor.server.application.*
16 | import io.ktor.server.plugins.statuspages.*
17 | import io.ktor.server.request.*
18 | import io.ktor.server.response.*
19 | import kotlinx.serialization.SerializationException
20 |
21 | fun Application.configureStatusExceptions() {
22 |
23 | install(StatusPages) {
24 | exception { call, cause ->
25 | println("path: ${call.request.path()}")
26 | println(cause)
27 |
28 | when (cause) {
29 | is SerializationException ->
30 | with(call.request.path()) {
31 | when {
32 | startsWith(AppRoutes.USERS_ROUTE) -> sendBadUser(call)
33 | startsWith(AppRoutes.APPS_ROUTE) -> sendBadApp(call)
34 | }
35 | }
36 | is AuthenticationException ->
37 | call.respond(
38 | status = HttpStatusCode.Unauthorized,
39 | message = CityResponse(errors =listOf(ResponseErrors(ErrorCode.INVALID_API_KEY,
40 | ErrorCode.INVALID_API_KEY.message)))
41 | )
42 | else ->
43 | call.respondText(text = "500: $cause", status = HttpStatusCode.InternalServerError)
44 | }
45 | }
46 | }
47 | }
48 |
49 | suspend fun sendBadApp(call: ApplicationCall) {
50 | val sampleApp = UserAppResponse(
51 | UserWithApp(
52 | email = "sample@email.com",
53 | appName = "Your App's Name", appType = AppType.DEVELOPMENT
54 | ),
55 | listOf(ResponseErrors(ErrorCode.INVALID_JSON, ErrorCode.INVALID_JSON.message))
56 | )
57 |
58 | call.respond(
59 | status = HttpStatusCode.BadRequest,
60 | message = sampleApp
61 | )
62 | }
63 |
64 | suspend fun sendBadUser(call: ApplicationCall) {
65 | val sampleUser = UserResponse(
66 | User(email = "sample@email.com"),
67 | listOf(ResponseErrors(ErrorCode.INVALID_JSON, ErrorCode.INVALID_JSON.message))
68 | )
69 |
70 | call.respond(
71 | status = HttpStatusCode.BadRequest,
72 | message = sampleUser
73 | )
74 | }
75 |
76 |
77 |
--------------------------------------------------------------------------------
/src/main/kotlin/com/santansarah/data/CityDaoImpl.kt:
--------------------------------------------------------------------------------
1 | package com.santansarah.data
2 |
3 | import com.santansarah.data.DatabaseFactory.dbQuery
4 | import com.santansarah.utils.ErrorCode
5 | import com.santansarah.utils.ServiceResult
6 | import org.jetbrains.exposed.exceptions.ExposedSQLException
7 | import org.jetbrains.exposed.sql.*
8 |
9 | class CityDaoImpl : CityDaoInterface {
10 |
11 | /**
12 | * Maps my [ResultRow] to a [City] object.
13 | */
14 | private fun resultRowToCity(row: ResultRow): City {
15 | return try {
16 | City(
17 | zip = row[Cities.zip],
18 | lat = row[Cities.lat],
19 | lng = row[Cities.lng],
20 | city = row[Cities.city],
21 | state = row[Cities.state],
22 | population = row[Cities.population]
23 | )
24 | } catch (e: Exception) {
25 | // turns out population was null for 1074 fields
26 | // it was throwing an error. i did a db update to fix.
27 | println(e)
28 | return City()
29 | }
30 | }
31 |
32 | override suspend fun getCitiesByName(prefix: String): ServiceResult> {
33 | return try {
34 | val minPopulation = 20000
35 | val cities = dbQuery {
36 | Cities.select {
37 | (Cities.city like "$prefix%") and (Cities.population greaterEq minPopulation)
38 | }.orderBy(Cities.city to SortOrder.ASC)
39 | .map(::resultRowToCity)
40 | }
41 |
42 | ServiceResult.Success(cities)
43 |
44 | } catch (e: Exception) {
45 | println(e)
46 | when (e) {
47 | is ExposedSQLException -> {
48 | println("exception from insert function: ${e.errorCode}")
49 | ServiceResult.Error(ErrorCode.DATABASE_ERROR)
50 | }
51 | else -> ServiceResult.Error(ErrorCode.DATABASE_ERROR)
52 | }
53 | }
54 | }
55 |
56 | override suspend fun getCitiesByZip(prefix: String): ServiceResult> {
57 | return try {
58 | val cities = dbQuery {
59 | Cities.select {
60 | Cities.zip.castTo(VarCharColumnType()) like "$prefix%"
61 | }.map(::resultRowToCity)
62 | }
63 |
64 | ServiceResult.Success(cities)
65 |
66 | } catch (e: Exception) {
67 | println(e)
68 | when (e) {
69 | is ExposedSQLException -> {
70 | println("exception from insert function: ${e.errorCode}")
71 | ServiceResult.Error(ErrorCode.DATABASE_ERROR)
72 | }
73 | else -> ServiceResult.Error(ErrorCode.DATABASE_ERROR)
74 | }
75 | }
76 | }
77 | }
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/src/main/kotlin/com/santansarah/CityRoutes.kt:
--------------------------------------------------------------------------------
1 | package com.santansarah
2 |
3 | import com.santansarah.data.CityDaoImpl
4 | import com.santansarah.data.CityDaoInterface
5 | import com.santansarah.domain.CityResponse
6 | import com.santansarah.domain.ResponseErrors
7 | import com.santansarah.plugins.AppPrincipal
8 | import com.santansarah.utils.ErrorCode
9 | import com.santansarah.utils.ServiceResult
10 | import io.ktor.http.*
11 | import io.ktor.server.application.*
12 | import io.ktor.server.auth.*
13 | import io.ktor.server.engine.*
14 | import io.ktor.server.response.*
15 | import io.ktor.server.routing.*
16 |
17 | fun Route.cityRouting(
18 | cityDaoImpl: CityDaoInterface
19 | ) {
20 | route("cities") {
21 | authenticate {
22 | get {
23 |
24 | // we know we're not null, b/c we're authenticated
25 | // at this point. something that would be really
26 | // neat here would be to insert this call into
27 | // the db to track queries by api key. we could then
28 | // get queries per second, etc.
29 | val principal = call.principal()!!
30 | val userWithApp = principal.userWithApp
31 |
32 | val namePrefix: String? = call.request.queryParameters["name"]
33 | val zipPrefix: String? = call.request.queryParameters["zip"]
34 |
35 | if (namePrefix.isNullOrBlank() && zipPrefix.isNullOrBlank()) {
36 | call.respond(
37 | status = HttpStatusCode.BadRequest,
38 | message = ResponseErrors(
39 | ErrorCode.INVALID_CITY_QUERY,
40 | ErrorCode.INVALID_CITY_QUERY.message
41 | )
42 | )
43 | }
44 |
45 | // TODO: Create Use Case and do better checks.
46 | namePrefix?.let {
47 | when (val dbResult = cityDaoImpl.getCitiesByName(it)) {
48 | is ServiceResult.Error -> {
49 | call.respond(
50 | status = HttpStatusCode.BadRequest,
51 | message = CityResponse(
52 | userWithApp = userWithApp,
53 | errors = listOf(
54 | ResponseErrors(
55 | dbResult.error,
56 | dbResult.error.message
57 | )
58 | )
59 | )
60 | )
61 | }
62 | is ServiceResult.Success -> {
63 | call.respond(
64 | status = HttpStatusCode.OK,
65 | message = CityResponse(userWithApp, dbResult.data)
66 | )
67 | }
68 | }
69 | }
70 | }
71 | }
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/src/main/kotlin/com/santansarah/data/UserDaoImpl.kt:
--------------------------------------------------------------------------------
1 | package com.santansarah.data
2 |
3 | import com.santansarah.data.DatabaseFactory.dbQuery
4 | import com.santansarah.utils.ErrorCode
5 | import com.santansarah.utils.ServiceResult
6 | import org.jetbrains.exposed.exceptions.ExposedSQLException
7 | import org.jetbrains.exposed.sql.ResultRow
8 | import org.jetbrains.exposed.sql.and
9 | import org.jetbrains.exposed.sql.insert
10 | import org.jetbrains.exposed.sql.select
11 | import org.sqlite.SQLiteErrorCode
12 | import java.sql.SQLIntegrityConstraintViolationException
13 |
14 | class UserDaoImpl : UserDao {
15 |
16 | /**
17 | * Maps my [ResultRow] to a [User] object.
18 | */
19 | private fun resultRowToUser(row: ResultRow) = User(
20 | userId = row[Users.userId],
21 | email = row[Users.email],
22 | userCreateDate = row[Users.userCreateDate],
23 | )
24 |
25 | /**
26 | * map our table join to a [UserWithApp] object
27 | */
28 | private fun resultRowToUserWithApp(row: ResultRow) = UserWithApp(
29 | userId = row[Users.userId],
30 | email = row[Users.email],
31 | userCreateDate = row[Users.userCreateDate],
32 | userAppId = row[UserApps.userAppId],
33 | appName = row[UserApps.appName],
34 | appType = row[UserApps.appType],
35 | apiKey = row[UserApps.apiKey],
36 | appCreateDate = row[UserApps.userAppCreateDate]
37 | )
38 |
39 | /**
40 | * Gets a [User] by userId and email. This is used to verify a
41 | * new [UserApp] insert.
42 | */
43 | override suspend fun doesUserExist(userId: Int, email: String): ServiceResult {
44 | return try {
45 | val isEmpty = dbQuery {
46 | Users.select {
47 | (Users.userId eq userId) and (Users.email eq email)
48 | }.empty()
49 | }
50 |
51 | if (isEmpty)
52 | ServiceResult.Error(ErrorCode.UNKNOWN_USER)
53 | else
54 | ServiceResult.Success(true)
55 |
56 | } catch (e: Exception) {
57 | when (e) {
58 | is ExposedSQLException -> {
59 | println("exception from insert function: ${e.errorCode}")
60 | ServiceResult.Error(ErrorCode.DATABASE_ERROR)
61 | }
62 | else -> ServiceResult.Error(ErrorCode.DATABASE_ERROR)
63 | }
64 | }
65 | }
66 |
67 | /**
68 | * Inserts a [User]. There is a unique constraint on the email
69 | * field, so if it's a dup, it will throw an exception.
70 | * I'm able to get the org.sqlite info in the exception;
71 | * pretty cool.
72 | */
73 | override suspend fun insertUser(user: User): ServiceResult {
74 | return try {
75 | dbQuery {
76 | Users
77 | .insert {
78 | it[email] = user.email
79 | it[userCreateDate] = user.userCreateDate
80 | }
81 | .resultedValues?.singleOrNull()?.let {
82 | ServiceResult.Success(resultRowToUser(it))
83 | } ?: ServiceResult.Error(ErrorCode.DATABASE_ERROR)
84 | }
85 | } catch (e: Exception) {
86 | when (e) {
87 | is ExposedSQLException -> {
88 | if (e.errorCode == SQLiteErrorCode.SQLITE_CONSTRAINT.code)
89 | ServiceResult.Error(ErrorCode.EMAIL_EXISTS)
90 | else
91 | ServiceResult.Error(ErrorCode.DATABASE_ERROR)
92 | }
93 | else -> ServiceResult.Error(ErrorCode.DATABASE_ERROR)
94 | }
95 | }
96 | }
97 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/santansarah/data/UserAppDaoImpl.kt:
--------------------------------------------------------------------------------
1 | package com.santansarah.data
2 |
3 | import com.santansarah.data.DatabaseFactory.dbQuery
4 | import com.santansarah.utils.ErrorCode
5 | import com.santansarah.utils.ServiceResult
6 | import org.jetbrains.exposed.exceptions.ExposedSQLException
7 | import org.jetbrains.exposed.sql.*
8 | import org.sqlite.SQLiteErrorCode
9 |
10 | class UserAppDaoImpl : UserAppDao {
11 |
12 | /**
13 | * Map my table join query to a [UserWithApp] object
14 | */
15 | private fun resultRowToUserWithApp(row: ResultRow) = UserWithApp(
16 | userId = row[Users.userId],
17 | email = row[Users.email],
18 | userCreateDate = row[Users.userCreateDate],
19 | userAppId = row[UserApps.userAppId],
20 | appName = row[UserApps.appName],
21 | appType = row[UserApps.appType],
22 | apiKey = row[UserApps.apiKey],
23 | appCreateDate = row[UserApps.userAppCreateDate]
24 | )
25 |
26 | /**
27 | * Map my table to a [UserApp] object.
28 | */
29 | private fun resultRowToUserApp(row: ResultRow) = UserApp(
30 | userId = row[UserApps.userId],
31 | userAppId = row[UserApps.userAppId],
32 | appName = row[UserApps.appName],
33 | appType = row[UserApps.appType],
34 | apiKey = row[UserApps.apiKey],
35 | appCreateDate = row[UserApps.userAppCreateDate]
36 | )
37 |
38 | override suspend fun checkForDupApp(userWithApp: UserWithApp): ServiceResult {
39 | return try {
40 | val isEmpty = dbQuery {
41 | UserApps.select {
42 | (UserApps.userId eq userWithApp.userId) and
43 | (UserApps.appName eq userWithApp.appName) and
44 | (UserApps.appType eq userWithApp.appType)
45 | }.empty()
46 | }
47 | if (isEmpty)
48 | ServiceResult.Success(false)
49 | else
50 | ServiceResult.Error(ErrorCode.APP_EXISTS)
51 | } catch (e: Exception) {
52 | when (e) {
53 | is ExposedSQLException -> {
54 | ServiceResult.Error(ErrorCode.DATABASE_ERROR)
55 | }
56 | else -> ServiceResult.Error(ErrorCode.DATABASE_ERROR)
57 | }
58 | }
59 | }
60 |
61 | override suspend fun getUserWithApp(apiKey: String): ServiceResult {
62 | return try {
63 | val userWithApp = dbQuery {
64 | (Users innerJoin UserApps).select {
65 | UserApps.apiKey eq apiKey
66 | }
67 | .map(::resultRowToUserWithApp)
68 | .single()
69 | }
70 | ServiceResult.Success(userWithApp)
71 | } catch (e: Exception) {
72 | when (e) {
73 | is NoSuchElementException -> ServiceResult.Error(ErrorCode.UNKNOWN_APP)
74 | else -> ServiceResult.Error(ErrorCode.DATABASE_ERROR)
75 | }
76 | }
77 | }
78 |
79 | override suspend fun insertUserApp(userWithApp: UserWithApp): ServiceResult {
80 | return try {
81 | dbQuery {
82 | UserApps
83 | .insert {
84 | it[userId] = userWithApp.userId
85 | it[appName] = userWithApp.appName
86 | it[appType] = userWithApp.appType
87 | it[apiKey] = userWithApp.apiKey
88 | it[userAppCreateDate] = userWithApp.appCreateDate
89 | }
90 | .resultedValues?.singleOrNull()?.let {
91 | ServiceResult.Success(resultRowToUserApp(it))
92 | } ?: ServiceResult.Error(ErrorCode.DATABASE_ERROR)
93 | }
94 | } catch (e: Exception) {
95 | when (e) {
96 | is ExposedSQLException -> {
97 | if (e.errorCode == SQLiteErrorCode.SQLITE_CONSTRAINT.code)
98 | ServiceResult.Error(ErrorCode.API_KEY)
99 | else
100 | ServiceResult.Error(ErrorCode.DATABASE_ERROR)
101 | }
102 | else -> ServiceResult.Error(ErrorCode.DATABASE_ERROR)
103 | }
104 | }
105 | }
106 |
107 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Ktor City API with Koin, Exposed, and SQLite
2 |
3 | This Ktor REST API provides:
4 |
5 | * User Validation with Google One Tap JWT
6 | * API Key Generation
7 | * CRUD Operations for API Keys Assigned to Apps
8 | * City Name Lookups
9 | * City Detail Lookups
10 |
11 | Features and plugins include Exposed with SQLite, global error handling with Ktor Status Pages, and two forms of
12 | Authentication, including by API key for the front-end client, and JWT authentication for Google One Tap.
13 |
14 | ## Important - Latest Branch - Do Not Use Main
15 |
16 | > https://github.com/santansarah/ktor-city-api/tree/ktor-crud
17 |
18 | ## Database Setup
19 |
20 | 1. Get the data: https://simplemaps.com/data/us-zips.
21 | 2. Scrub the data. I deleted some unwanted columns, and set the population to
22 | `0` where it was null.
23 |
24 | 
25 | 3. Import the data into an SQLite database.
26 | 4. Save it in your project root folder.
27 |
28 | ## Ktor API with Exposed
29 |
30 | [](https://www.youtube.com/watch?v=iX4ZIRjmpN4)
31 |
32 | Links:
33 |
34 | * GitHub Source Code: https://github.com/santansarah/ktor-city-api
35 | * Video Branch: https://github.com/santansarah/ktor-city-api/tree/user-implementation
36 | * Ktor Status Pages: https://ktor.io/docs/status-pages.html
37 | * Exposed Wiki: https://github.com/JetBrains/Exposed/wiki
38 | * City info: https://simplemaps.com/data/us-zips
39 |
40 | In Part 1, I'll go over:
41 |
42 | * The project background and basic concepts
43 | * API Postman/Endpoints
44 | * Exposed setup with SQLite
45 | * Ktor data layer
46 | * Creating tables and inserting data with Exposed
47 | * Koin dependency injection
48 | * Implementing Use Cases
49 | * Ktor routes
50 | * Ktor Status Pages (Routing Exceptions)
51 |
52 | ## Google One Tap Validation with Ktor
53 |
54 | [](https://www.youtube.com/playlist?list=PLzxawGXQRFswx9iqiCCnrDtYJw1zwGLkd)
55 |
56 | This branch validates a Google JWT token that's returned from the Google One Tap API.
57 | When the validation is successful for a new user, it inserts basic user data (email, name)
58 | into the Users SQLite table. It also validates existing users and returns user data from the
59 | database from the JWT token email address.
60 |
61 | The validation routes throw a custom Google validation exception, and also support validating
62 | a Nonce claim.
63 |
64 | Links:
65 |
66 | * Android app: https://github.com/santansarah/city-api-client/tree/ktor-network-api
67 | * Ktor JWT: https://ktor.io/docs/jwt.html
68 | * Google One Tap: https://developers.google.com/identity/one-tap/android/idtoken-auth
69 |
70 | ### Authenticate a User
71 |
72 | Sign up, Sign In: This route inserts or returns an authenticated user.
73 |
74 | In my Android app, I send an Nonce with my sign in requests. Google sends back a JWT,
75 | including a users basic account info and the Nonce.
76 |
77 | My Ktor API expects the following request, which includes a custom `x-nonce` header field
78 | and the Google `Bearer Authorization` JWT token.
79 |
80 | ```
81 | curl --location --request GET 'http://127.0.0.1:8080/users/authenticate' \
82 | --header 'x-nonce: XXXaaa000YYyy' \
83 | --header 'Authorization: Bearer xxxxXXXX.yyyyYYYY.zzzzZZZZ'
84 | ```
85 |
86 | ### Get Existing User
87 |
88 | Once a userId is created and saved to my Android app, this route uses my app’s API key to return a user.
89 |
90 | ```
91 | curl --location --request GET 'http://127.0.0.1:8080/users/20' \
92 | --header 'x-api-key: Pr67HTHS4VIP1eN'
93 | ```
94 |
95 | ## Get Cities by Prefix and Zip Code
96 |
97 | [](https://www.youtube.com/watch?v=gyOdfRgNs2k)
98 |
99 | This branch adds the routes to get city data.
100 |
101 | * Android Source: https://github.com/santansarah/city-api-client/tree/ktor-client-app-scoped
102 | * Android Source: https://github.com/santansarah/city-api-client/tree/ktor-client-closable
103 |
104 | ### Get City by Prefix
105 |
106 | ```
107 | curl --location --request GET 'http://127.0.0.1:8080/cities?name=pho' \
108 | --header 'x-api-key: Pr67HTHS4VIP1eN'
109 | ```
110 |
111 | ### Get City by Zip
112 |
113 | ```
114 | curl --location --request GET 'http://127.0.0.1:8080/cities/zip/90210' \
115 | --header 'x-api-key: Pr67HTHS4VIP1eN'
116 | ```
117 |
118 | # Ktor Create, Read, Patch (CRUD)
119 |
120 | [](https://www.youtube.com/watch?v=vT5q6dQ-em4)
121 |
122 | This branch allows users to create, get, and patch apps. When an app is created,
123 | the API auto-generates an API key that developers can use to query city data.
124 |
125 | * Ktor API Source: https://github.com/santansarah/ktor-city-api/tree/ktor-crud
126 | * Android Source: https://github.com/santansarah/city-api-client/tree/ktor-crud
127 |
128 | ### GET: Apps
129 |
130 | ```
131 | curl --location --request GET 'http://127.0.0.1:8080/apps/24' \
132 | --header 'x-api-key: Pr67HTHS4VIP1eN'
133 | ```
134 |
135 | ### POST: Create a New App
136 |
137 | ```
138 | curl --location --request POST 'http://127.0.0.1:8080/apps/create' \
139 | --header 'x-api-key: Pr67HTHS4VIP1eN' \
140 | --header 'Content-Type: application/json' \
141 | --data-raw '{
142 | "userId": 24,
143 | "email": "tester@mail.com",
144 | "appName": "Create App Demo",
145 | "appType": "dev"
146 | }
147 | '
148 | ```
149 |
150 | ### GET: Get App Details
151 |
152 | ```
153 | curl --location --request GET 'http://127.0.0.1:8080/app/4' \
154 | --header 'x-api-key: Pr67HTHS4VIP1eN'
155 | ```
156 |
157 | ### PATCH: Update App Details
158 |
159 | ```
160 | curl --location --request PATCH 'http://127.0.0.1:8080/app/4' \
161 | --header 'x-api-key: Pr67HTHS4VIP1eN' \
162 | --header 'Content-Type: application/json' \
163 | --data-raw '{
164 | "appName": "Update App",
165 | "appType": "dev"
166 | }
167 | '
168 | ```
169 |
170 | City info provided by: https://simplemaps.com/data/us-zips
171 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | #
4 | # Copyright © 2015-2021 the original authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | #
21 | # Gradle start up script for POSIX generated by Gradle.
22 | #
23 | # Important for running:
24 | #
25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
26 | # noncompliant, but you have some other compliant shell such as ksh or
27 | # bash, then to run this script, type that shell name before the whole
28 | # command line, like:
29 | #
30 | # ksh Gradle
31 | #
32 | # Busybox and similar reduced shells will NOT work, because this script
33 | # requires all of these POSIX shell features:
34 | # * functions;
35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
37 | # * compound commands having a testable exit status, especially «case»;
38 | # * various built-in commands including «command», «set», and «ulimit».
39 | #
40 | # Important for patching:
41 | #
42 | # (2) This script targets any POSIX shell, so it avoids extensions provided
43 | # by Bash, Ksh, etc; in particular arrays are avoided.
44 | #
45 | # The "traditional" practice of packing multiple parameters into a
46 | # space-separated string is a well documented source of bugs and security
47 | # problems, so this is (mostly) avoided, by progressively accumulating
48 | # options in "$@", and eventually passing that to Java.
49 | #
50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
52 | # see the in-line comments for details.
53 | #
54 | # There are tweaks for specific operating systems such as AIX, CygWin,
55 | # Darwin, MinGW, and NonStop.
56 | #
57 | # (3) This script is generated from the Groovy template
58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
59 | # within the Gradle project.
60 | #
61 | # You can find Gradle at https://github.com/gradle/gradle/.
62 | #
63 | ##############################################################################
64 |
65 | # Attempt to set APP_HOME
66 |
67 | # Resolve links: $0 may be a link
68 | app_path=$0
69 |
70 | # Need this for daisy-chained symlinks.
71 | while
72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
73 | [ -h "$app_path" ]
74 | do
75 | ls=$( ls -ld "$app_path" )
76 | link=${ls#*' -> '}
77 | case $link in #(
78 | /*) app_path=$link ;; #(
79 | *) app_path=$APP_HOME$link ;;
80 | esac
81 | done
82 |
83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
84 |
85 | APP_NAME="Gradle"
86 | APP_BASE_NAME=${0##*/}
87 |
88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
90 |
91 | # Use the maximum available, or set MAX_FD != -1 to use that value.
92 | MAX_FD=maximum
93 |
94 | warn () {
95 | echo "$*"
96 | } >&2
97 |
98 | die () {
99 | echo
100 | echo "$*"
101 | echo
102 | exit 1
103 | } >&2
104 |
105 | # OS specific support (must be 'true' or 'false').
106 | cygwin=false
107 | msys=false
108 | darwin=false
109 | nonstop=false
110 | case "$( uname )" in #(
111 | CYGWIN* ) cygwin=true ;; #(
112 | Darwin* ) darwin=true ;; #(
113 | MSYS* | MINGW* ) msys=true ;; #(
114 | NONSTOP* ) nonstop=true ;;
115 | esac
116 |
117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
118 |
119 |
120 | # Determine the Java command to use to start the JVM.
121 | if [ -n "$JAVA_HOME" ] ; then
122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
123 | # IBM's JDK on AIX uses strange locations for the executables
124 | JAVACMD=$JAVA_HOME/jre/sh/java
125 | else
126 | JAVACMD=$JAVA_HOME/bin/java
127 | fi
128 | if [ ! -x "$JAVACMD" ] ; then
129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
130 |
131 | Please set the JAVA_HOME variable in your environment to match the
132 | location of your Java installation."
133 | fi
134 | else
135 | JAVACMD=java
136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
137 |
138 | Please set the JAVA_HOME variable in your environment to match the
139 | location of your Java installation."
140 | fi
141 |
142 | # Increase the maximum file descriptors if we can.
143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
144 | case $MAX_FD in #(
145 | max*)
146 | MAX_FD=$( ulimit -H -n ) ||
147 | warn "Could not query maximum file descriptor limit"
148 | esac
149 | case $MAX_FD in #(
150 | '' | soft) :;; #(
151 | *)
152 | ulimit -n "$MAX_FD" ||
153 | warn "Could not set maximum file descriptor limit to $MAX_FD"
154 | esac
155 | fi
156 |
157 | # Collect all arguments for the java command, stacking in reverse order:
158 | # * args from the command line
159 | # * the main class name
160 | # * -classpath
161 | # * -D...appname settings
162 | # * --module-path (only if needed)
163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
164 |
165 | # For Cygwin or MSYS, switch paths to Windows format before running java
166 | if "$cygwin" || "$msys" ; then
167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
169 |
170 | JAVACMD=$( cygpath --unix "$JAVACMD" )
171 |
172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
173 | for arg do
174 | if
175 | case $arg in #(
176 | -*) false ;; # don't mess with options #(
177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
178 | [ -e "$t" ] ;; #(
179 | *) false ;;
180 | esac
181 | then
182 | arg=$( cygpath --path --ignore --mixed "$arg" )
183 | fi
184 | # Roll the args list around exactly as many times as the number of
185 | # args, so each arg winds up back in the position where it started, but
186 | # possibly modified.
187 | #
188 | # NB: a `for` loop captures its iteration list before it begins, so
189 | # changing the positional parameters here affects neither the number of
190 | # iterations, nor the values presented in `arg`.
191 | shift # remove old arg
192 | set -- "$@" "$arg" # push replacement arg
193 | done
194 | fi
195 |
196 | # Collect all arguments for the java command;
197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
198 | # shell script including quotes and variable substitutions, so put them in
199 | # double quotes to make sure that they get re-expanded; and
200 | # * put everything else in single quotes, so that it's not re-expanded.
201 |
202 | set -- \
203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \
204 | -classpath "$CLASSPATH" \
205 | org.gradle.wrapper.GradleWrapperMain \
206 | "$@"
207 |
208 | # Use "xargs" to parse quoted args.
209 | #
210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
211 | #
212 | # In Bash we could simply go:
213 | #
214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
215 | # set -- "${ARGS[@]}" "$@"
216 | #
217 | # but POSIX shell has neither arrays nor command substitution, so instead we
218 | # post-process each arg (as a line of input to sed) to backslash-escape any
219 | # character that might be a shell metacharacter, then use eval to reverse
220 | # that process (while maintaining the separation between arguments), and wrap
221 | # the whole thing up as a single "set" statement.
222 | #
223 | # This will of course break if any of these variables contains a newline or
224 | # an unmatched quote.
225 | #
226 |
227 | eval "set -- $(
228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
229 | xargs -n1 |
230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
231 | tr '\n' ' '
232 | )" '"$@"'
233 |
234 | exec "$JAVACMD" "$@"
235 |
--------------------------------------------------------------------------------