Skip to content

Commit

Permalink
ont-converter: change usage printing, add aliases to handle input for…
Browse files Browse the repository at this point in the history
…mat and punnings
  • Loading branch information
sszuev committed Apr 24, 2022
1 parent 6f5dcc2 commit a44dcad
Show file tree
Hide file tree
Showing 5 changed files with 84 additions and 44 deletions.
104 changes: 77 additions & 27 deletions src/main/kotlin/com/github/sszuev/ontconverter/Args.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ package com.github.sszuev.ontconverter
import com.github.owlcs.ontapi.OntFormat
import com.github.owlcs.ontapi.jena.impl.conf.OntModelConfig
import com.github.owlcs.ontapi.jena.impl.conf.OntPersonality
import com.github.sszuev.ontconverter.api.utils.supportedReadFormats
import com.github.sszuev.ontconverter.api.utils.supportedWriteFormats
import kotlinx.cli.ArgParser
import kotlinx.cli.ArgType
import kotlinx.cli.default
Expand All @@ -14,6 +12,7 @@ import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
import kotlin.io.path.isDirectory
import kotlin.streams.toList

data class Args(
val sourceFile: Path,
Expand Down Expand Up @@ -53,74 +52,87 @@ data class Args(
}

internal fun parseArgs(args: Array<String>): Args {
val locale = Locale.ENGLISH
val parser = ArgParser("java -jar ont-converter.jar")
val inputStringPath by parser.option(
ArgType.String, shortName = "i", fullName = "input",
description = """
description = description(
"""
The file path or not-empty directory to load ontology/ontologies.
""".trimIndent()
"""
)
).required()
val sourceFormat by parser.option(
ArgType.Choice(supportedReadFormats(), { e -> OntFormat.valueOf(e) }, { it.name }),
ArgType.Choice(supportedReadFormats(), { formatByAlias(it) }, { formatInputString(it) }),
shortName = "if", fullName = "input-format",
description = """
The input format. If not specified the program will choose
the most suitable one to load ontology from a file.
""".trimIndent()
description = description(
"""
The input format.
If not specified the program will choose the most suitable one to load ontology from a file.
"""
)
)
val outputStringPath by parser.option(
ArgType.String, shortName = "o", fullName = "output",
description = """
description = description(
"""
The file or directory path to store result ontology/ontologies.
If the --input is a file then this parameter must also be a file.
""".trimIndent()
"""
)
).required()
val targetFormat by parser.option(
ArgType.Choice(supportedWriteFormats(), { OntFormat.valueOf(it.uppercase(locale)) }, { it.name }),
ArgType.Choice(supportedWriteFormats(), { formatByAlias(it) }, { formatInputString(it) }),
shortName = "of", fullName = "output-format",
description = """
description = description(
"""
The format of output ontology/ontologies.
""".trimIndent()
"""
)
).required()

val punnings by parser.option(
ArgType.Choice<OntModelConfig.StdMode>({ OntModelConfig.StdMode.valueOf(it.uppercase(locale)) }, { it.name }),
ArgType.Choice<OntModelConfig.StdMode>({ punningByAlias(it) }, { punningInputString(it) }),
shortName = "p", fullName = "punnings",
description = """
The punning mode. Could be used in conjunction with --refine option. Must be one of the following:
description = description(
"""
The punning mode.
Could be used in conjunction with --refine option. Must be one of the following:
Lax mode: allows any punnings, i.e. ontology is allowed to contain multiple entity declarations
Middle mode: two forbidden intersections: Datatype <-> Class & NamedObjectProperty <-> DatatypeProperty
Strict mode: all punnings are forbidden, i.e. Datatype <-> Class and rdf:Property intersections
(any pairs of NamedObjectProperty, DatatypeProperty, AnnotationProperty).
""".trimIndent()
Strict mode: all punnings are forbidden, i.e. Datatype <-> Class and rdf:Property intersections (any pairs of NamedObjectProperty, DatatypeProperty, AnnotationProperty).
"""
)
).default(OntModelConfig.StdMode.LAX)

val refine by parser.option(
ArgType.Boolean, shortName = "r", fullName = "refine",
description = """
description = description(
"""
Refine output:
if specified the resulting ontologies will consist only of the OWL2-DL components (annotations and axioms),
otherwise there could be some rdf-stuff (in case the output format is provided by jena)
""".trimIndent()
"""
)
).default(false)

val web by parser.option(
ArgType.Boolean, shortName = "w", fullName = "web",
description = """
description = description(
"""
Allow web/ftp diving to retrieve dependent ontologies from imports (owl:imports),
otherwise the specified directory (see --input) will be used as the only source.
""".trimIndent()
"""
)
).default(false)

val force by parser.option(
ArgType.Boolean, shortName = "f", fullName = "force",
description = "Ignore any exceptions while loading/saving and processing imports."
description = description("Ignore any exceptions while loading/saving and processing imports.")
).default(false)

val verbose by parser.option(
ArgType.Boolean, shortName = "v", fullName = "verbose",
description = "To print progress messages to console."
description = description("To print progress messages to console.")
).default(false)

parser.parse(args)
Expand Down Expand Up @@ -163,4 +175,42 @@ private fun parseOutput(outputStringPath: String, source: Path): Path {
Files.createDirectory(target)
}
return target
}

private fun description(msg: String): String {
return msg.trimIndent().replace("\n", "")
}

private fun supportedReadFormats(): List<OntFormat> {
return OntFormat.formats().filter(OntFormat::isReadSupported).toList()
}

private fun supportedWriteFormats(): List<OntFormat> {
return OntFormat.formats().filter(OntFormat::isWriteSupported).toList()
}

@Throws(NoSuchElementException::class)
private fun formatByAlias(key: String): OntFormat {
return OntFormat.values().first { f -> formatAliases(f).any { key.equals(it, true) } }
}

private fun formatInputString(format: OntFormat): String {
return formatAliases(format).joinToString(", ", "{", "}")
}

private fun formatAliases(f: OntFormat): Sequence<String> {
return sequenceOf(f.ordinal.toString(), f.ext, f.name, f.id).distinctBy { it.lowercase(Locale.ENGLISH) }
}

@Throws(NoSuchElementException::class)
private fun punningByAlias(key: String): OntModelConfig.StdMode {
return OntModelConfig.StdMode.values().first { m -> punningAliases(m).any { key.equals(it, true) } }
}

private fun punningInputString(mode: OntModelConfig.StdMode): String {
return punningAliases(mode).joinToString(", ", "{", "}")
}

private fun punningAliases(m: OntModelConfig.StdMode): Sequence<String> {
return sequenceOf(m.ordinal.toString(), m.name).distinctBy { it.lowercase(Locale.ENGLISH) }
}
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ class Processor(private val args: Args) {
manager.saveOntology(ont, targetFormat, IRI.create(file.toFile()))
} catch (ex: Exception) {
if (args.force) {
logger.error("Can't save $name to ${file}: ${exceptionMessage(ex)}")
logger.error("Can't save $name to ${file}; ${exceptionMessage(ex)}")
} else {
throw OntApiException("Can't save $name to $file", ex)
}
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,10 @@ fun sourceName(source: OWLOntologyDocumentSource): String {
* @return [String]
*/
fun exceptionMessage(ex: Throwable): String {
val msg = ex.message?.split("\n")?.get(0)?.take(100)
var msg = ex.message?.split("\n")?.get(0)?.take(97)
if (msg?.length == 97) {
msg += "..."
}
val clazz = ex.javaClass.name.split(".").last()
return "$clazz -- $msg"
return "$clazz: \"$msg\""
}
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ fun loadOntology(
manager.loadOntologyFromOntologyDocument(source)
} catch (ex: OWLOntologyCreationException) {
if (ignoreExceptions) {
logger.error("Failed to load ontology-document from $name: ${exceptionMessage(ex)}")
logger.error("Failed to load ontology-document from $name; ${exceptionMessage(ex)}")
return null
}
throw OntApiException("Failed to load ontology-document from $name", ex)
Expand Down

0 comments on commit a44dcad

Please sign in to comment.