Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ktlint #28

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[*.{kt,kts}]
disabled_rules=no-wildcard-imports
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,11 @@ class TCNCloudAPIHandler(
)

override fun handleRequest(input: APIGatewayProxyRequestEvent, context: Context): APIGatewayProxyResponseEvent {
logger.info("Processing request: ${context.awsRequestId}. " +
logger.info(
"Processing request: ${context.awsRequestId}. " +
"Query params: ${input.queryStringParameters}. " +
"Body: ${input.body}")
"Body: ${input.body}"
)
try {
if (input.httpMethod == "GET") {
logger.info("Handling GET Request for :${input.path}. ReqId: ${context.awsRequestId}")
Expand All @@ -46,8 +48,8 @@ class TCNCloudAPIHandler(
} catch (ex: Exception) {
logger.info("Failed to serve request: ${context.awsRequestId}. Cause: ${ex.message}")
return APIGatewayProxyResponseEvent()
.withStatusCode(500)
.withBody("CoEpi Service Internal Failure")
.withStatusCode(500)
.withBody("CoEpi Service Internal Failure")
}
}

Expand All @@ -65,4 +67,4 @@ class TCNCloudAPIHandler(
private fun HttpResponse.toAPIGatewayProxyResponseEvent(): APIGatewayProxyResponseEvent =
APIGatewayProxyResponseEvent()
.withStatusCode(status)
.withBody(body?.decodeToString())
.withBody(body?.decodeToString())
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ class TCNReport {
// TODO: Do stuff with the ByteBuffer and validate signature
}
}
}
}
6 changes: 6 additions & 0 deletions buildSrc/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ plugins {

gradlePlugin {
plugins {
register("ktlint-plugin") {
id = "ktlint"
implementationClass = "KtlintPlugin"
description = "Format Kotlin files with ktlint"
}

register("project-defaults-plugin") {
id = "project-defaults"
implementationClass = "ProjectDefaultsPlugin"
Expand Down
78 changes: 78 additions & 0 deletions buildSrc/src/main/kotlin/KtlintPlugin.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.artifacts.Configuration
import org.gradle.api.plugins.JavaPluginConvention
import org.gradle.api.tasks.JavaExec
import org.gradle.kotlin.dsl.*

/**
* Provides tasks for checking and, where possible, fixing formatting and style errors using
* [ktlint](https://ktlint.github.io/).
*/
class KtlintPlugin : Plugin<Project> {

override fun apply(project: Project) {
project.run {
val ktlint: Configuration by project.configurations.creating

dependencies {
ktlint("com.pinterest", "ktlint", "0.36.0")
}

tasks {
register<JavaExec>("ktlintApplyToIdeaProject") {
description = "REPLACE IntelliJ style with ktlint for this project"
main = "com.pinterest.ktlint.Main"
classpath = ktlint
args = listOf("--apply-to-idea-project", "--experimental", "-y")
}
}

afterEvaluate {
withConvention(JavaPluginConvention::class) {
tasks {
for (sourceSet in sourceSets) {
val sourceSetName =
if (sourceSet.name == "main") ""
else sourceSet.name.capitalize()

val baseArgs = listOf("--experimental")

val files =
sourceSet.allSource.sourceDirectories.files
.map { it.path + "/**/*.kt" }

val checkTaskName = "ktlintCheck$sourceSetName"

register<JavaExec>(checkTaskName) {
group = "verification"
description = "Check Kotlin code style"
main = "com.pinterest.ktlint.Main"
classpath = ktlint
args = baseArgs + files
}

named("check") {
dependsOn(checkTaskName)
}

val formatTaskName = "ktlintFormat$sourceSetName"

register<JavaExec>("ktlintFormat$sourceSetName") {
group = "verification"
description = "Fix Kotlin code style deviations"
main = "com.pinterest.ktlint.Main"
classpath = ktlint
args = baseArgs + listOf("-F") + files
}

named("compile${sourceSetName}Kotlin") {
dependsOn(formatTaskName)
}
}
}
}
}
}
}
}
2 changes: 2 additions & 0 deletions buildSrc/src/main/kotlin/ProjectDefaultsPlugin.kt
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ class ProjectDefaultsPlugin : Plugin<Project> {

private fun Project.configurePlugins() {
plugins.apply("java-library")
plugins.apply("ktlint")

plugins.apply("org.jetbrains.kotlin.jvm")
}

Expand Down
2 changes: 1 addition & 1 deletion core/src/main/kotlin/org/coepi/api/Exceptions.kt
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@ open class InvalidTCNSignatureException : RuntimeException {
open class UnexpectedIntervalLengthException : RuntimeException {
constructor(message: String?) : super(message)
constructor(message: String?, cause: Throwable?) : super(message, cause)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ fun ByteBuffer.decodeToString(): String = String(array())

fun String.toByteBuffer(): ByteBuffer = ByteBuffer.wrap(toByteArray())

fun ByteArray.toByteBuffer(): ByteBuffer = ByteBuffer.wrap(this)
fun ByteArray.toByteBuffer(): ByteBuffer = ByteBuffer.wrap(this)
2 changes: 1 addition & 1 deletion core/src/main/kotlin/org/coepi/api/v4/Intervals.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ object Intervals {
fun Instant.toInterval(): Long = toEpochMilli() / Intervals.INTERVAL_LENGTH_MS

fun generateIntervalForTimestamp(timestamp: Long): Long =
timestamp / Intervals.INTERVAL_LENGTH_MS
timestamp / Intervals.INTERVAL_LENGTH_MS
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,4 @@ data class TCNReportRecord(

@DynamoDBAttribute
var report: ByteArray = byteArrayOf()
)
)
14 changes: 8 additions & 6 deletions core/src/main/kotlin/org/coepi/api/v4/dao/TCNReportsDao.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBQueryExpression
import com.amazonaws.services.dynamodbv2.model.AttributeValue
import org.apache.commons.lang3.Validate
import java.time.LocalDate
import java.util.*
import org.apache.commons.lang3.Validate

class TCNReportsDao {
private val dynamoMapper: DynamoDBMapper
Expand All @@ -22,10 +22,12 @@ class TCNReportsDao {
this.dynamoMapper = DynamoDBMapper(ddbClient)
}

fun addReport(reportData: ByteArray,
date: LocalDate,
intervalNumber: Long,
timestamp: Long): TCNReportRecord {
fun addReport(
reportData: ByteArray,
date: LocalDate,
intervalNumber: Long,
timestamp: Long
): TCNReportRecord {
Validate.isTrue(reportData.isNotEmpty(), "reportData cannot be empty")
Validate.isTrue(intervalNumber > 0, "intervalNumber should be positive")
Validate.isTrue(timestamp > 0, "timestamp needs to be positive")
Expand Down Expand Up @@ -58,4 +60,4 @@ class TCNReportsDao {

return outputList
}
}
}
15 changes: 8 additions & 7 deletions core/src/main/kotlin/org/coepi/api/v4/http/TCNHttpHandler.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package org.coepi.api.v4.http

import com.fasterxml.jackson.databind.ObjectMapper
import java.nio.ByteBuffer
import java.time.LocalDate
import java.time.format.DateTimeParseException
import java.util.*
import org.coepi.api.InvalidTCNSignatureException
import org.coepi.api.TCNClientException
import org.coepi.api.UnexpectedIntervalLengthException
Expand All @@ -10,10 +14,6 @@ import org.coepi.api.common.toByteBuffer
import org.coepi.api.v4.Intervals
import org.coepi.api.v4.reports.TCNReportService
import org.slf4j.LoggerFactory
import java.nio.ByteBuffer
import java.time.LocalDate
import java.time.format.DateTimeParseException
import java.util.*

class TCNHttpHandler(
private val objectMapper: ObjectMapper,
Expand Down Expand Up @@ -84,15 +84,15 @@ private fun parseQueryParameters(
if (!parameters.containsKey(INTERVAL_LENGTH_MS_KEY)) {
throw TCNClientException(
"$INTERVAL_LENGTH_MS_KEY query parameter is required if " +
" $INTERVAL_LENGTH_MS_KEY is provided"
" $INTERVAL_LENGTH_MS_KEY is provided"
)
}
val intervalLengthMs = parameters[INTERVAL_LENGTH_MS_KEY]?.toLong()

if (intervalLengthMs != Intervals.INTERVAL_LENGTH_MS) {
throw UnexpectedIntervalLengthException(
"$intervalLengthMs is invalid for the date " +
"$DATE_KEY. Please use ${Intervals.INTERVAL_LENGTH_MS} to calculate $INTERVAL_NUMBER_KEY"
"$DATE_KEY. Please use ${Intervals.INTERVAL_LENGTH_MS} to calculate $INTERVAL_NUMBER_KEY"
)
}
}
Expand All @@ -101,7 +101,8 @@ private fun parseQueryParameters(
} catch (ex: NumberFormatException) {
throw TCNClientException(
"$INTERVAL_NUMBER_KEY or $INTERVAL_LENGTH_MS_KEY in " +
"illegal number format.", ex
"illegal number format.",
ex
)
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
package org.coepi.api.v4.reports

import java.nio.ByteBuffer
import java.time.Clock
import java.time.LocalDate
import org.coepi.api.common.time.toUtcLocalDate
import org.coepi.api.v4.dao.TCNReportRecord
import org.coepi.api.v4.dao.TCNReportsDao
import org.coepi.api.v4.toInterval
import java.nio.ByteBuffer

class TCNReportService(
private val clock: Clock,
Expand Down
9 changes: 4 additions & 5 deletions core/src/test/kotlin/org/coepi/api/Fixtures.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@ package org.coepi.api

import io.mockk.every
import io.mockk.mockk
import org.assertj.core.api.ObjectAssert
import org.coepi.api.v4.dao.TCNReportRecord

object Fixtures {
fun someBytes() = ByteArray(42) { it.toByte() }
fun someBytes() = ByteArray(42) { it.toByte() }

fun mockSavedReport(): TCNReportRecord = mockk {
every { reportId } returns "<mock report id>"
}
fun mockSavedReport(): TCNReportRecord = mockk {
every { reportId } returns "<mock report id>"
}
}
10 changes: 5 additions & 5 deletions core/src/test/kotlin/org/coepi/api/base/LocalDynamoDB.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import com.amazonaws.services.dynamodbv2.local.main.ServerRunner

class LocalDynamoDB {

fun startDynamoDb(){
val localUrl= "http://localhost:9000"
fun startDynamoDb() {
val localUrl = "http://localhost:9000"
val region = "us-west-2"

println("Trying to start dynamo db at $localUrl")
Expand All @@ -17,8 +17,8 @@ class LocalDynamoDB {
server.start()

val ddb = AmazonDynamoDBClientBuilder.standard()
.withEndpointConfiguration(AwsClientBuilder.EndpointConfiguration(localUrl, region))
.build()
.withEndpointConfiguration(AwsClientBuilder.EndpointConfiguration(localUrl, region))
.build()
var ddbMapper = DynamoDBMapper(ddb)
}
}
}
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
package org.coepi.api.v4.dao

import org.coepi.api.v4.generateIntervalForTimestamp
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
import java.nio.charset.Charset
import java.time.Instant
import java.time.LocalDate
import java.time.ZoneId
import org.coepi.api.v4.generateIntervalForTimestamp
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test

@Disabled
class TCNReportsDaoTest {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ import com.fasterxml.jackson.databind.ObjectMapper
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import java.time.LocalDate
import java.util.*
import org.assertj.core.api.Assertions.assertThat
import org.coepi.api.Fixtures
import org.coepi.api.common.toByteBuffer
import org.coepi.api.v4.reports.TCNReportService
import org.junit.jupiter.api.Test
import java.time.LocalDate
import java.util.*

class TCNHttpHandlerTest {

Expand Down Expand Up @@ -52,4 +52,3 @@ class TCNHttpHandlerTest {
assertThat(response).isInstanceOf(Ok::class.java)
}
}