Initial commit

This commit is contained in:
Hubert Van De Walle 2021-05-05 11:28:43 +02:00
commit 1e89c93bfc
19 changed files with 601 additions and 0 deletions

6
.gitattributes vendored Normal file
View File

@ -0,0 +1,6 @@
#
# https://help.github.com/articles/dealing-with-line-endings/
#
# These are explicitly windows files and should use crlf
*.bat text eol=crlf

4
.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
.gradle
build
.idea
*.mv.db

9
README.md Normal file
View File

@ -0,0 +1,9 @@
# Issues Log
## Usage
```bash
./gradlew run
```
Small project to experiment with [Htmx](https://htmx.org) and [_hyperscript](https://hyperscript.org/)

17
app/build.gradle.kts Normal file
View File

@ -0,0 +1,17 @@
plugins {
id("kotlin-application")
}
dependencies {
implementation("org.slf4j:slf4j-api:2.0.0-alpha1")
runtimeOnly("org.slf4j:slf4j-simple:2.0.0-alpha1")
implementation("org.ktorm:ktorm-core:3.3.0")
implementation("com.h2database:h2:1.4.200")
implementation("org.jetbrains.kotlinx:kotlinx-html:0.7.3")
implementation("io.javalin:javalin:3.13.6")
implementation("org.ocpsoft.prettytime:prettytime:5.0.1.Final")
}
application {
mainClass.set("be.vandewalleh.issueslog.MainKt")
}

View File

@ -0,0 +1,9 @@
org.slf4j.simpleLogger.logFile=System.out
org.slf4j.simpleLogger.showDateTime=true
org.slf4j.simpleLogger.dateTimeFormat=yyyy-MM-dd HH:mm:ss:SSS Z
org.slf4j.simpleLogger.defaultLogLevel=info
# Logging detail level for a SimpleLogger instance named "xxxxx".
# Must be one of ("trace", "debug", "info", "warn", or "error").
# If not specified, the default logging detail level is used.
#org.slf4j.simpleLogger.log.xxxxx=

51
app/src/Components.kt Normal file
View File

@ -0,0 +1,51 @@
package be.vandewalleh.issueslog
import kotlinx.html.*
@HtmlTagMarker
fun TagConsumer<*>.head() {
script(src = "https://unpkg.com/htmx.org@1.3.3") {}
script(src = "https://unpkg.com/hyperscript.org@0.0.9") {}
link(
href = "https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css",
rel = "stylesheet"
)
title("Issues log")
}
@HtmlTagMarker
fun TagConsumer<*>.issues(issues: List<IssueEntity>) {
issues.forEach {
div("card") {
style = "margin: 6px"
div("card-header") { +it.created.pretty() }
div("card-body") {
h5("card-title text-center") { +it.name }
p("card-text") { +it.cause }
div {
button(classes = "btn btn-outline-danger btn-sm") {
hxDelete = "/issues?id=${it.id}"
hxTarget = "#issues"
+"Delete"
}
}
}
}
}
}
@HtmlTagMarker
fun TagConsumer<*>.requiredInput(label: String, name: String) {
div("mb-3") {
label("form-label") {
`for` = name
+label
}
input(classes = "form-control") {
id = name
this.name = name
required = true
maxLength = "255"
}
}
}

View File

@ -0,0 +1,23 @@
package be.vandewalleh.issueslog
import org.ktorm.database.Database
import org.ktorm.dsl.delete
import org.ktorm.dsl.eq
import org.ktorm.entity.add
import org.ktorm.entity.sequenceOf
import org.ktorm.entity.sortedByDescending
import org.ktorm.entity.toList
class IssuesRepository(private val database: Database) {
fun create(issueEntity: IssueEntity) {
database.sequenceOf(IssuesTable).add(issueEntity)
}
fun all() = database.sequenceOf(IssuesTable).sortedByDescending { it.created }.toList()
fun delete(id: Int) {
database.delete(IssuesTable) {
it.id eq id
}
}
}

52
app/src/Main.kt Normal file
View File

@ -0,0 +1,52 @@
package be.vandewalleh.issueslog
import io.javalin.Javalin
import kotlinx.html.*
import org.h2.jdbcx.JdbcDataSource
import org.ktorm.database.Database
fun main() {
val dataSource = JdbcDataSource()
.apply { setURL("jdbc:h2:./issues;DB_CLOSE_DELAY=-1;CASE_INSENSITIVE_IDENTIFIERS=TRUE") }
val database = Database.connect(dataSource).apply { createTables() }
val repo = IssuesRepository(database)
val app = Javalin.create()
app.get("/") { ctx ->
ctx.document {
head()
body {
style = "padding:1.5rem"
form {
hxPost = "/new"
hxTarget = "#issues"
hs = "on submit set #name.value to '' set #cause.value to '' call #name.focus()"
requiredInput(label = "Name", name = "name")
requiredInput(label = "Cause", name = "cause")
button(classes = "btn btn-outline-primary") { +"Add" }
}
h1 { +"Issues Log" }
div {
id = "issues"
style = "display:flex;flex-wrap:wrap"
issues(repo.all())
}
}
}
}
app.post("/new") { ctx ->
repo.create(IssueEntity {
name = ctx.formParam("name")!!
cause = ctx.formParam("cause")!!
})
ctx.fragment { issues(repo.all()) }
}
app.delete("/issues") { ctx ->
repo.delete(ctx.queryParam("id")!!.toInt())
ctx.fragment { issues(repo.all()) }
}
app.start(System.getenv("PORT")?.toIntOrNull() ?: 9000)
}

42
app/src/Tables.kt Normal file
View File

@ -0,0 +1,42 @@
package be.vandewalleh.issueslog
import org.ktorm.database.Database
import org.ktorm.entity.Entity
import org.ktorm.entity.EntitySequence
import org.ktorm.entity.sequenceOf
import org.ktorm.schema.Table
import org.ktorm.schema.int
import org.ktorm.schema.timestamp
import org.ktorm.schema.varchar
import java.time.Instant
object IssuesTable : Table<IssueEntity>("Issues") {
val id = int("id").primaryKey().bindTo { it.id }
val name = varchar("name").bindTo { it.name }
val cause = varchar("cause").bindTo { it.cause }
val created = timestamp("created").bindTo { it.created }
}
interface IssueEntity : Entity<IssueEntity> {
companion object : Entity.Factory<IssueEntity>()
var id: Int
var name: String
var cause: String
var created: Instant
}
fun Database.createTables() {
useConnection { connection ->
connection.prepareStatement(
"""
CREATE TABLE IF NOT EXISTS Issues (
id int auto_increment primary key,
name varchar not null,
cause varchar not null,
created timestamp not null default CURRENT_TIMESTAMP()
);
""".trimIndent()
).execute()
}
}

52
app/src/Utils.kt Normal file
View File

@ -0,0 +1,52 @@
package be.vandewalleh.issueslog
import io.javalin.http.Context
import kotlinx.html.*
import kotlinx.html.stream.*
import org.ocpsoft.prettytime.PrettyTime
import java.time.Instant
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
class AttributeDelegate(private val name: String? = null) : ReadWriteProperty<Tag, String> {
override fun getValue(thisRef: Tag, property: KProperty<*>): String {
throw UnsupportedOperationException()
}
override fun setValue(thisRef: Tag, property: KProperty<*>, value: String) {
val name = this.name ?: property.name.camelToKebabCase()
thisRef.attributes[name] = value
}
companion object {
private val camelRegex = "(?<=[a-zA-Z])[A-Z]".toRegex()
private fun String.camelToKebabCase() = camelRegex.replace(this) { "-${it.value}" }.lowercase()
}
}
var Tag.hxTarget by AttributeDelegate()
var Tag.hxGet by AttributeDelegate()
var Tag.hxPost by AttributeDelegate()
var Tag.hxDelete by AttributeDelegate()
var Tag.hs by AttributeDelegate("_")
var LABEL.`for` by AttributeDelegate("for")
fun Context.document(block: TagConsumer<StringBuilder>.() -> Unit) {
header("Content-Type", "text/html; charset=utf-8")
result(buildString {
append("<!DOCTYPE html>\n")
appendHTML().apply(block)
})
}
fun Context.fragment(block: TagConsumer<StringBuilder>.() -> Unit) {
header("Content-Type", "text/html; charset=utf-8")
result(buildString {
appendHTML().apply(block)
})
}
private val prettyTime by lazy(LazyThreadSafetyMode.NONE) { PrettyTime() }
fun Instant.pretty(): String = prettyTime.format(this)

12
buildSrc/build.gradle.kts Normal file
View File

@ -0,0 +1,12 @@
plugins {
`kotlin-dsl`
}
repositories {
gradlePluginPortal()
}
dependencies {
implementation(platform("org.jetbrains.kotlin:kotlin-bom:1.5.0"))
implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.0")
}

View File

@ -0,0 +1,21 @@
plugins {
java
}
repositories {
mavenCentral()
}
java {
targetCompatibility = JavaVersion.toVersion(16)
sourceCompatibility = JavaVersion.toVersion(16)
}
tasks.withType<JavaCompile> {
options.encoding = "UTF-8"
}
sourceSets["main"].resources.setSrcDirs(listOf("resources"))
sourceSets["main"].java.setSrcDirs(emptyList<String>())
sourceSets["test"].resources.setSrcDirs(listOf("test-resources"))
sourceSets["test"].java.setSrcDirs(emptyList<String>())

View File

@ -0,0 +1,4 @@
plugins {
id("kotlin-convention")
application
}

View File

@ -0,0 +1,18 @@
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("java-convention")
kotlin("jvm")
}
dependencies {
implementation(kotlin("stdlib-jdk8"))
implementation(platform(kotlin("bom")))
}
tasks.withType<KotlinCompile> { kotlinOptions { jvmTarget = "15" } }
kotlin {
sourceSets["main"].kotlin.setSrcDirs(listOf("src"))
sourceSets["test"].kotlin.setSrcDirs(listOf("test"))
}

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.0-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

185
gradlew vendored Executable file
View File

@ -0,0 +1,185 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"

89
gradlew.bat vendored Normal file
View File

@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

2
settings.gradle.kts Normal file
View File

@ -0,0 +1,2 @@
rootProject.name = "Issues Log"
include("app")