This is part 2 of my journey to build a train tracker to aide my office commute. You can find part 1 here.

In this post I am going to talk about setting up the project to customise the gradle project created by IntelliJ.

Dependencies

Only runtime dependency is going to be Gson, so lets add that to gradle config

implementation("com.google.code.gson:gson.2.13.0")

Dev dependency will be Junit and mockito. IntelliJ already adds junit, lets add mokito and update the Junit dependency.

testImplementation(platform("org.junit:junit-bom:5.12.1"))
testImplementation("org.junit.jupiter:junit-jupiter")
testImplementation("org.mockito:mockito-core:5.16.1")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")

Main Class

To begin with we need a main class that will serve as the single startup point. Very imaginatively I am going to name it Main.

package blog.devrandom

public class Main {
    public static void main(String[] args) {
        System.out.println("Train Tracker version 1.0.0");
    }
}

Fat Jar

Train tracker is going to be executed from systemd, so building a fat jar makes our life easier to launch. Unfortunately gradle does not come with a build-in way to create a fat jar. We have to add a custom task to make one for us.

We can using the application gradle plugin to help us

plugins {
    application
}

application {
    mainClass = "blog.devrandom.Main"
}

Now that we defined the main class, we can now add the custom task to build the fatjar.

tasks {
    val fatJar = register<Jar>("fatJar") {
        dependsOn.addAll(listOf("compileJava", "processResources"))
        duplicatesStrategy = DuplicatesStrategy.EXCLUDE
        manifest {
            attributes(mapOf("Main-Class" to application.mainClass))
        }
        val sourcesMain = sourceSets.main.get()
        val contents = configurations.runtimeClasspath.get()
            .map { if (it.isDirectory) it else zipTree(it) } +
                sourcesMain.output
        from(contents)
    }
    build {
        dependsOn(fatJar)
    }
}

Build and launch

With all the scaffolding in place we can now build and launch our application. From the command line we can run

$ ./gradlew fatJar

$ java -jar build/libs/train-tracker-service-1.0.0.jar
Train Tracker version: 1.0.0

Code

You can see the git repo at this stage on the project-setup branch on Github ( link).