Skip to content

Commit

Permalink
fix: allow extension of a template class
Browse files Browse the repository at this point in the history
  • Loading branch information
jenspots committed Apr 19, 2024
1 parent b2f24f4 commit 099e0ff
Show file tree
Hide file tree
Showing 11 changed files with 73 additions and 42 deletions.
1 change: 1 addition & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ dependencies {
tasks.test {
useJUnitPlatform()
}

kotlin {
jvmToolchain(17)
}
2 changes: 1 addition & 1 deletion src/main/kotlin/Configuration.kt
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class Configuration(configPath: String) {
data class Step(val processor: Processor, val arguments: List<Any>)

/** Shared logger object. */
private val logger = createLogger();
private val logger = createLogger()

/** Processors described in the config. */
private val processors: MutableMap<String, Processor> = mutableMapOf()
Expand Down
17 changes: 8 additions & 9 deletions src/main/kotlin/Processor.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import org.apache.jena.query.QuerySolution
import org.apache.jena.rdf.model.Model
import technology.idlab.compiler.JavaCodeHandler
import technology.idlab.logging.createLogger
import technology.idlab.logging.fatal
import java.io.File
import java.lang.reflect.Method
import kotlin.system.exitProcess
Expand All @@ -20,24 +21,21 @@ class Processor(
private val argumentTypes: List<String> = listOf("java.lang.String"),
) {
// Runtime objects.
private val logger = createLogger();
private val instance: Any
private val method: Method

companion object {
private val logger = createLogger()

/**
* Read the SPARQL query from the resources folder and return it as a string.
*/
private fun readQuery(): String {
val resource = object {}.javaClass.getResource("/processors.sparql")
val data = resource?.readText()
if (data == null) {
println(
"ERROR: Could not read ${resource?.path}",
)
exitProcess(-1)
}
return data
logger.info("Reading SPARQL query from ${resource?.path}")

return resource?.readText()
?: logger.fatal("Could not read ${resource?.path}")
}

/**
Expand Down Expand Up @@ -87,6 +85,7 @@ class Processor(

// Go over the resulting solutions and initialize a processor
// object.
logger.info("Executing SPARQL query against model")
QueryExecutionFactory.create(query, model).use {
val results = it.execSelect()
while (results.hasNext()) {
Expand Down
7 changes: 0 additions & 7 deletions src/main/kotlin/Template.kt

This file was deleted.

14 changes: 7 additions & 7 deletions src/main/kotlin/compiler/CodeHandler.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import java.io.File

abstract class CodeHandler {
protected val outputDirectory = "out"
protected open val logger = createLogger()
protected val logger = createLogger()
private val classLoader: ClassLoader = FileClassLoader(outputDirectory)

/**
Expand All @@ -26,11 +26,12 @@ abstract class CodeHandler {
* Initialize a class using its default constructor.
*/
fun createInstance(clazz: Class<*>): Any {
val constructor = try {
clazz.getConstructor()
} catch (e: NoSuchMethodException) {
logger.fatal("Could not find constructor for ${clazz.name}")
}
val constructor =
try {
clazz.getConstructor()
} catch (e: NoSuchMethodException) {
logger.fatal("Could not find constructor for ${clazz.name}")
}

return try {
constructor.newInstance()
Expand All @@ -48,4 +49,3 @@ abstract class CodeHandler {
}.toTypedArray()
}
}

3 changes: 2 additions & 1 deletion src/main/kotlin/compiler/FileClassLoader.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ class FileClassLoader(private val directory: String) : ClassLoader() {

override fun findClass(name: String): Class<*> {
// Define the path to the class file.
val path = "$directory/${name.replace('.', File.separatorChar)}.class"
var path = "$directory/${name.replace('.', File.separatorChar)}.class"
path = File(path).absolutePath

// Open file pointer.
val file = File(path)
Expand Down
30 changes: 25 additions & 5 deletions src/main/kotlin/compiler/JavaCodeHandler.kt
Original file line number Diff line number Diff line change
@@ -1,20 +1,40 @@
package technology.idlab.compiler

import technology.idlab.logging.createLogger
import technology.idlab.logging.fatal
import java.io.File
import java.io.PrintWriter
import javax.tools.JavaCompiler
import javax.tools.ToolProvider

class JavaCodeHandler : CodeHandler() {
override val logger = createLogger()
private val compiler: JavaCompiler = ToolProvider.getSystemJavaCompiler() ?: logger.fatal("No Java compiler found.")
private val compiler: JavaCompiler =
ToolProvider.getSystemJavaCompiler() ?: logger.fatal(
"No Java compiler found.",
)
private val fileManager = compiler.getStandardFileManager(null, null, null)

override fun compile(file: File) {
val compilationUnits = fileManager.getJavaFileObjectsFromFiles(listOf(file))
val templateUrl =
this::class.java.getResource(
"/Template.java",
) ?: logger.fatal("Could not find template in resources")
val template = File(templateUrl.toURI())
logger.info("Using template $template")

val compilationUnits =
fileManager.getJavaFileObjectsFromFiles(
listOf(template, file),
)
val options = listOf("-d", outputDirectory)
val task = compiler.getTask(null, fileManager, null, options, null, compilationUnits)
val task =
compiler.getTask(
PrintWriter(System.out),
fileManager,
null,
options,
null,
compilationUnits,
)

// Execute compilation.
logger.info("Compiling $file")
Expand Down
28 changes: 19 additions & 9 deletions src/main/kotlin/logging/BasicFormatter.kt
Original file line number Diff line number Diff line change
@@ -1,23 +1,33 @@
import java.util.*
import java.util.Date
import java.util.TimeZone
import java.util.logging.Formatter

class BasicFormatter(): Formatter() {
class BasicFormatter() : Formatter() {
override fun format(record: java.util.logging.LogRecord): String {
// Parse date and time.
val instant = Date(record.millis).toInstant()
val instantTimezone = instant.atZone(TimeZone.getDefault().toZoneId())
val isoString = instantTimezone.format(java.time.format.DateTimeFormatter.ISO_LOCAL_TIME)
val time = isoString.padEnd(12, '0');
val isoString =
instantTimezone.format(
java.time.format.DateTimeFormatter.ISO_LOCAL_TIME,
)
val time = isoString.padEnd(12, '0')

// Parse thread.
val thread = "[${record.longThreadID}]".padEnd(6, ' ');
val thread = "[${record.longThreadID}]".padEnd(6, ' ')
// Parse level.
val level = record.level.toString().padEnd(7, ' ');
val level = record.level.toString().padEnd(7, ' ')

// Parse class and method.
val className = record.sourceClassName.split(".").last();
val location = "${className}::${record.sourceMethodName}"
.padEnd(30, ' ');
var className = record.sourceClassName.split(".").last()
className =
className.contains("$").let {
className.split("$").first()
}

val location =
"$className::${record.sourceMethodName}"
.padEnd(30, ' ')

// Output the result as a single string.
return "$time $thread $level $location ${record.message}\n"
Expand Down
2 changes: 1 addition & 1 deletion src/main/kotlin/logging/StandardOutput.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package technology.idlab.logging
import BasicFormatter
import java.util.logging.ConsoleHandler

class StandardOutput(): ConsoleHandler() {
class StandardOutput() : ConsoleHandler() {
init {
this.formatter = BasicFormatter()
this.setOutputStream(System.out)
Expand Down
7 changes: 7 additions & 0 deletions src/main/resources/Template.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import java.util.logging.Logger;

import static technology.idlab.logging.ExtensionKt.createLogger;

public class Template {
public Logger logger = createLogger();
}
4 changes: 2 additions & 2 deletions src/test/resources/Greeting.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
public class Greeting {
public class Greeting extends Template {
public void greet(String name) {
System.out.println("Hello, " + name + "!");
logger.info("Hello, " + name + "!");
}
}

0 comments on commit 099e0ff

Please sign in to comment.