EG-433 - Error Reporting Framework (Merge)

Error Reporting Framework - Phase 1
This commit is contained in:
Katelyn Baker 2020-04-30 13:12:54 +01:00 committed by GitHub
commit 99fd08909d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
72 changed files with 1353 additions and 14 deletions

View File

@ -16,6 +16,8 @@ dependencies {
compile "com.jcabi:jcabi-manifests:$jcabi_manifests_version"
testCompile project(":test-utils")
testCompile "com.nhaarman:mockito-kotlin:$mockito_kotlin_version"
testCompile "org.mockito:mockito-core:$mockito_version"
}

View File

@ -0,0 +1,31 @@
package net.corda.common.logging.errorReporting
import net.corda.common.logging.CordaVersion
import java.util.*
/**
* Provides information specific to Corda to the error reporting library.
*
* The primary use of this is to provide the URL to the docs site where the error information is hosted.
*/
class CordaErrorContextProvider : ErrorContextProvider {
companion object {
private const val BASE_URL = "https://docs.corda.net/docs"
private const val OS_PAGES = "corda-os"
private const val ENTERPRISE_PAGES = "corda-enterprise"
private const val ERROR_CODE_PAGE = "error-codes.html"
}
override fun getURL(locale: Locale): String {
val versionNumber = CordaVersion.releaseVersion
// This slightly strange block here allows the code to be merged across to Enterprise with no changes.
val productVersion = if (CordaVersion.platformEditionCode == "OS") {
OS_PAGES
} else {
ENTERPRISE_PAGES
}
return "$BASE_URL/$productVersion/$versionNumber/$ERROR_CODE_PAGE"
}
}

View File

@ -0,0 +1,28 @@
package net.corda.common.logging.errorReporting
/**
* A type representing an error condition.
*
* Error codes should be used in situations where an error is expected and information can be provided back to the user about what they've
* done wrong. Each error code should have a resource bundle defined for it, which contains set of properties that define the error string
* in different languages. See the resource bundles in common/logging/src/main/resources/errorReporting for more details.
*/
interface ErrorCode<CODES> where CODES: ErrorCodes, CODES: Enum<CODES> {
/**
* The error code.
*
* Error codes are used to indicate what sort of error occurred. A unique code should be returned for each possible
* error condition that could be reported within the defined namespace. The code should very briefly describe what has gone wrong, e.g.
* "failed-to-store" or "connection-unavailable".
*/
val code: CODES
/**
* Parameters to pass to the string template when reporting this error. The corresponding template that defines the error string in the
* resource bundle must be expecting this list of parameters. Parameters should be in the order required by the message template - for
* example, if the message template is "This error has argument {0} and argument {1}", the first element of this list will be placed
* into {0}.
*/
val parameters: List<Any>
}

View File

@ -0,0 +1,16 @@
package net.corda.common.logging.errorReporting
/**
* A collection of error codes.
*
* Types implementing this are required to be enum classes to be used in an error.
*/
interface ErrorCodes {
/**
* The namespace of this collection of errors.
*
* These are used to partition errors into categories, e.g. "database" or "cordapp". Namespaces should be unique, which can be enforced
* by using enum elements.
*/
val namespace: String
}

View File

@ -0,0 +1,24 @@
package net.corda.common.logging.errorReporting
import java.util.*
/**
* Provide context around reported errors by supplying product specific information.
*/
interface ErrorContextProvider {
/**
* Get the URL to the docs site where the error codes are hosted.
*
* Note that the correct docs site link is likely to depend on the following:
* - The locale of the error message
* - The product the error was reported from
* - The version of the product the error was reported from
*
* The returned URL must be the link the to the error code table in the documentation.
*
* @param locale The locale of the link
* @return The URL of the docs site, to be printed in the logs
*/
fun getURL(locale: Locale) : String
}

View File

@ -0,0 +1,16 @@
package net.corda.common.logging.errorReporting
import org.slf4j.Logger
/**
* Reports error conditions to the logs, using localised error messages.
*/
internal interface ErrorReporter {
/**
* Report a particular error condition
*
* @param error The error to report
* @param logger The logger to use when reporting this error
*/
fun report(error: ErrorCode<*>, logger: Logger)
}

View File

@ -0,0 +1,36 @@
package net.corda.common.logging.errorReporting
import org.slf4j.Logger
import java.text.MessageFormat
import java.util.*
internal const val ERROR_INFO_RESOURCE = "ErrorInfo"
internal const val ERROR_CODE_MESSAGE = "errorCodeMessage"
internal const val ERROR_CODE_URL = "errorCodeUrl"
internal class ErrorReporterImpl(private val resourceLocation: String,
private val locale: Locale,
private val errorContextProvider: ErrorContextProvider) : ErrorReporter {
private fun fetchAndFormat(resource: String, property: String, params: Array<out Any>) : String {
val bundle = ResourceBundle.getBundle(resource, locale)
val template = bundle.getString(property)
val formatter = MessageFormat(template, locale)
return formatter.format(params)
}
// Returns the string appended to all reported errors, indicating the error code and the URL to go to.
// e.g. [Code: my-error-code, For further information, please go to https://docs.corda.net/corda-os/4.5/error-codes.html]
private fun getErrorInfo(error: ErrorCode<*>) : String {
val resource = "$resourceLocation/$ERROR_INFO_RESOURCE"
val codeMessage = fetchAndFormat(resource, ERROR_CODE_MESSAGE, arrayOf(error.formatCode()))
val urlMessage = fetchAndFormat(resource, ERROR_CODE_URL, arrayOf(errorContextProvider.getURL(locale)))
return "[$codeMessage, $urlMessage]"
}
override fun report(error: ErrorCode<*>, logger: Logger) {
val errorResource = ErrorResource.fromErrorCode(error, resourceLocation, locale)
val message = "${errorResource.getErrorMessage(error.parameters.toTypedArray())} ${getErrorInfo(error)}"
logger.error(message)
}
}

View File

@ -0,0 +1,70 @@
package net.corda.common.logging.errorReporting
import java.util.*
/**
* Entry point into the Error Reporting framework.
*
* This creates the error reporter used to report errors. The `initialiseReporting` method should be called to build a reporter before any
* errors are reported.
*/
class ErrorReporting private constructor(private val localeString: String,
private val resourceLocation: String,
private val contextProvider: ErrorContextProvider?) {
constructor() : this(DEFAULT_LOCALE, DEFAULT_LOCATION, null)
private companion object {
private const val DEFAULT_LOCALE = "en-US"
private const val DEFAULT_LOCATION = "."
private var errorReporter: ErrorReporter? = null
}
/**
* Set the locale to use when reporting errors
*
* @param locale The locale tag to use when reporting errors, e.g. en-US
*/
@Suppress("UNUSED_PARAMETER")
fun withLocale(locale: String) : ErrorReporting {
// Currently, if anything other than the default is used this is entirely untested. As a result, an exception is thrown here to
// indicate that this functionality is not ready at this point in time.
throw LocaleSettingUnsupportedException()
}
/**
* Set the location of the resource bundles containing the error codes.
*
* @param location The location within the JAR of the resource bundle
*/
fun usingResourcesAt(location: String) : ErrorReporting {
return ErrorReporting(localeString, location, contextProvider)
}
/**
* Set the context provider to supply project-specific information about the errors.
*
* @param contextProvider The context provider to use with error reporting
*/
fun withContextProvider(contextProvider: ErrorContextProvider) : ErrorReporting {
return ErrorReporting(localeString, resourceLocation, contextProvider)
}
/**
* Set up the reporting of errors.
*/
fun initialiseReporting() {
if (contextProvider == null) {
throw NoContextProviderSuppliedException()
}
if (errorReporter != null) {
throw DoubleInitializationException()
}
errorReporter = ErrorReporterImpl(resourceLocation, Locale.forLanguageTag(localeString), contextProvider)
}
internal fun getReporter() : ErrorReporter {
return errorReporter ?: throw ReportingUninitializedException()
}
}

View File

@ -0,0 +1,27 @@
package net.corda.common.logging.errorReporting
abstract class ErrorReportingException(message: String, cause: Throwable? = null) : Exception(message, cause)
/**
* Occurs when reporting is requested before the error reporting code has been initialized
*/
class ReportingUninitializedException : ErrorReportingException("Error reporting is uninitialized")
/**
* Occurs when no error context provider is supplied while initializing error reporting
*/
class NoContextProviderSuppliedException
: ErrorReportingException("No error context provider was supplied when initializing error reporting")
/**
* Occurs if the error reporting framework has been initialized twice
*/
class DoubleInitializationException : ErrorReportingException("Error reporting has previously been initialized")
/**
* Occurs if a locale is set while initializing the error reporting framework.
*
* This is done as locale support has not yet been properly designed, and so using anything other than the default is untested.
*/
class LocaleSettingUnsupportedException :
ErrorReportingException("Setting a locale other than the default is not supported in the first release")

View File

@ -0,0 +1,18 @@
package net.corda.common.logging.errorReporting
import org.slf4j.Logger
/**
* Report errors that have occurred.
*
* Doing this allows the error reporting framework to find the corresponding resources for the error and pick the correct locale.
*
* @param error The error that has occurred.
*/
fun Logger.report(error: ErrorCode<*>) = ErrorReporting().getReporter().report(error, this)
internal fun ErrorCode<*>.formatCode() : String {
val namespaceString = this.code.namespace.toLowerCase().replace("_", "-")
val codeString = this.code.toString().toLowerCase().replace("_", "-")
return "$namespaceString-$codeString"
}

View File

@ -0,0 +1,60 @@
package net.corda.common.logging.errorReporting
import net.corda.common.logging.errorReporting.ResourceBundleProperties.ACTIONS_TO_FIX
import net.corda.common.logging.errorReporting.ResourceBundleProperties.ALIASES
import net.corda.common.logging.errorReporting.ResourceBundleProperties.MESSAGE_TEMPLATE
import net.corda.common.logging.errorReporting.ResourceBundleProperties.SHORT_DESCRIPTION
import java.text.MessageFormat
import java.util.*
/**
* A representation of a single error resource file.
*
* This handles selecting the right properties from the resource bundle and formatting the error message.
*/
class ErrorResource private constructor(private val bundle: ResourceBundle,
private val locale: Locale) {
companion object {
/**
* Construct an error resource from a provided code.
*
* @param errorCode The code to get the resource bundle for
* @param resourceLocation The location in the JAR of the error code resource bundles
* @param locale The locale to use for this resource
*/
fun fromErrorCode(errorCode: ErrorCode<*>, resourceLocation: String, locale: Locale) : ErrorResource {
val resource = "$resourceLocation/${errorCode.formatCode()}"
val bundle = ResourceBundle.getBundle(resource, locale)
return ErrorResource(bundle, locale)
}
/**
* Construct an error resource using resources loaded in a given classloader
*
* @param resource The resource bundle to load
* @param classLoader The classloader used to load the resource bundles
* @param locale The locale to use for this resource
*/
fun fromLoader(resource: String, classLoader: ClassLoader, locale: Locale) : ErrorResource {
val bundle = ResourceBundle.getBundle(resource, locale, classLoader)
return ErrorResource(bundle, locale)
}
}
private fun getProperty(propertyName: String) : String = bundle.getString(propertyName)
private fun formatTemplate(template: String, args: Array<Any>) : String {
val formatter = MessageFormat(template, locale)
return formatter.format(args)
}
fun getErrorMessage(args: Array<Any>): String {
val template = getProperty(MESSAGE_TEMPLATE)
return formatTemplate(template, args)
}
val shortDescription: String = getProperty(SHORT_DESCRIPTION)
val actionsToFix: String = getProperty(ACTIONS_TO_FIX)
val aliases: String = getProperty(ALIASES)
}

View File

@ -0,0 +1,33 @@
package net.corda.common.logging.errorReporting
/**
* Namespaces for errors within the node.
*/
enum class NodeNamespaces {
DATABASE,
CORDAPP
}
/**
* Errors related to database connectivity
*/
enum class NodeDatabaseErrors : ErrorCodes {
COULD_NOT_CONNECT,
MISSING_DRIVER,
FAILED_STARTUP,
PASSWORD_REQUIRED_FOR_H2;
override val namespace = NodeNamespaces.DATABASE.toString()
}
/**
* Errors related to loading of Cordapps
*/
enum class CordappErrors : ErrorCodes {
DUPLICATE_CORDAPPS_INSTALLED,
MULTIPLE_CORDAPPS_FOR_FLOW,
MISSING_VERSION_ATTRIBUTE,
INVALID_VERSION_IDENTIFIER;
override val namespace = NodeNamespaces.CORDAPP.toString()
}

View File

@ -0,0 +1,11 @@
package net.corda.common.logging.errorReporting
/**
* Constants defining the properties available in the resource bundle files.
*/
object ResourceBundleProperties {
const val MESSAGE_TEMPLATE = "errorTemplate"
const val SHORT_DESCRIPTION = "shortDescription"
const val ACTIONS_TO_FIX = "actionsToFix"
const val ALIASES = "aliases"
}

View File

@ -0,0 +1,2 @@
errorCodeMessage = Error Code: {0}
errorCodeUrl = For further information, please go to {0}

View File

@ -0,0 +1,2 @@
errorCodeMessage = Error Code: {0}
errorCodeUrl = For further information, please go to {0}

View File

@ -0,0 +1,4 @@
errorTemplate = The CorDapp (name: {0}, file: {1}) is installed multiple times on the node. The following files correspond to the exact same content: {2}
shortDescription = A CorDapp has been installed multiple times on the same node.
actionsToFix = Investigate the logs to determine the files with duplicate content, and remove one of them from the cordapps directory.
aliases = iw8d4e

View File

@ -0,0 +1,3 @@
errorTemplate = The CorDapp (name: {0}, file: {1}) is installed multiple times on the node. The following files correspond to the exact same content: {2}
shortDescription = A CorDapp has been installed multiple times on the same node.
actionsToFix = Investigate the logs to determine the files with duplicate content, and remove one of them from the cordapps directory.

View File

@ -0,0 +1,4 @@
errorTemplate = Version identifier ({0}) for attribute {1} must be a whole number starting from 1.
shortDescription = A version attribute was specified in the CorDapp manifest with an invalid value. The value must be a whole number, and it must be greater than or equal to 1.
actionsToFix = Investigate the logs to find the invalid attribute, and change the attribute value to be valid (a whole number greater than or equal to 1).
aliases =

View File

@ -0,0 +1,4 @@
errorTemplate = Version identifier ({0}) for attribute {1} must be a whole number starting from 1.
shortDescription = A version attribute was specified in the CorDapp manifest with an invalid value. The value must be a whole number, and it must be greater than or equal to 1.
actionsToFix = Investigate the logs to find the invalid attribute, and change the attribute value to be valid (a whole number greater than or equal to 1).
aliases =

View File

@ -0,0 +1,4 @@
errorTemplate = Target versionId attribute {0} not specified. Please specify a whole number starting from 1.
shortDescription = A required version attribute was not specified in the manifest of the CorDapp JAR.
actionsToFix = Investigate the logs to find out which version attribute has not been specified, and add that version attribute to the CorDapp manifest.
aliases =

View File

@ -0,0 +1,3 @@
errorTemplate = Target versionId attribute {0} not specified. Please specify a whole number starting from 1.
shortDescription = A required version attribute was not specified in the manifest of the CorDapp JAR.
actionsToFix = Investigate the logs to find out which version attribute has not been specified, and add that version attribute to the CorDapp manifest.

View File

@ -0,0 +1,4 @@
errorTemplate = There are multiple CorDapp JARs on the classpath for the flow {0}: [{1}]
shortDescription = Multiple CorDapp JARs on the classpath define the same flow class. As a result, the platform will not know which version of the flow to start when the flow is invoked.
actionsToFix = Investigate the logs to find out which CorDapp JARs define the same flow classes. The developers of these apps will need to resolve the clash.
aliases =

View File

@ -0,0 +1,4 @@
errorTemplate = There are multiple CorDapp JARs on the classpath for the flow {0}: [{1}]
shortDescription = Multiple CorDapp JARs on the classpath define the same flow class. As a result, the platform will not know which version of the flow to start when the flow is invoked.
actionsToFix = Investigate the logs to find out which CorDapp JARs define the same flow classes. The developers of these apps will need to resolve the clash.
aliases =

View File

@ -0,0 +1,4 @@
errorTemplate = Could not connect to the database. Please check your JDBC connection URL, or the connectivity to the database.
shortDescription = The node failed to connect to the database on node startup, preventing the node from starting correctly.
actionsToFix = This happens either because the database connection has been misconfigured or the database is unreachable. Check that the JDBC URL is configured correctly in your node.conf. If this is correctly configured, then check your database connection.
aliases =

View File

@ -0,0 +1,3 @@
errorTemplate = Could not connect to the database. Please check your JDBC connection URL, or the connectivity to the database.
shortDescription = The node failed to connect to the database on node startup, preventing the node from starting correctly.
actionsToFix = This happens either because the database connection has been misconfigured or the database is unreachable. Check that the JDBC URL is configured correctly in your node.conf. If this is correctly configured, then check your database connection.

View File

@ -0,0 +1,4 @@
errorTemplate = Failed to create the datasource. See the logs for further information and the cause.
shortDescription = The datasource could not be created for unknown reasons.
actionsToFix = The logs in the logs directory should contain more information on what went wrong.
aliases =

View File

@ -0,0 +1,3 @@
errorTemplate = Failed to create the datasource. See the logs for further information and the cause.
shortDescription = The datasource could not be created for unknown reasons.
actionsToFix = The logs in the logs directory should contain more information on what went wrong.

View File

@ -0,0 +1,4 @@
errorTemplate = Could not find the database driver class. Please add it to the 'drivers' folder.
shortDescription = The node could not find the driver in the 'drivers' directory.
actionsToFix = Please ensure that the correct database driver has been placed in the 'drivers' folder. The driver must contain the driver main class specified in 'node.conf'.
aliases =

View File

@ -0,0 +1,3 @@
errorTemplate = Could not find the database driver class. Please add it to the 'drivers' folder.
shortDescription = The node could not find the driver in the 'drivers' directory.
actionsToFix = Please ensure that the correct database driver has been placed in the 'drivers' folder. The driver must contain the driver main class specified in 'node.conf'.

View File

@ -0,0 +1,4 @@
errorTemplate = Database password is required for H2 server listening on {0}
shortDescription = A password is required to access the H2 server the node is trying to access, and this password is missing.
actionsToFix = Add the required password to the 'datasource.password' configuration in 'node.conf'.
aliases =

View File

@ -0,0 +1,3 @@
errorTemplate = Database password is required for H2 server listening on {0}
shortDescription = A password is required to access the H2 server the node is trying to access, and this password is missing.
actionsToFix = Add the required password to the 'datasource.password' configuration in 'node.conf'.

View File

@ -0,0 +1,20 @@
package net.corda.commmon.logging.errorReporting
import net.corda.common.logging.CordaVersion
import net.corda.common.logging.errorReporting.CordaErrorContextProvider
import org.junit.Test
import java.util.*
import kotlin.test.assertEquals
class CordaErrorContextProviderTest {
@Test(timeout = 300_000)
fun `check that correct URL is returned from context provider`() {
val context = CordaErrorContextProvider()
val expectedURL = "https://docs.corda.net/docs/corda-os/${CordaVersion.releaseVersion}/error-codes.html"
// In this first release, there is only one localisation and the URL structure for future localisations is currently unknown. As
// a result, the same URL is expected for all locales.
assertEquals(expectedURL, context.getURL(Locale.getDefault()))
assertEquals(expectedURL, context.getURL(Locale.forLanguageTag("es-ES")))
}
}

View File

@ -0,0 +1,12 @@
package net.corda.commmon.logging.errorReporting
import net.corda.common.logging.errorReporting.CordappErrors
class CordappErrorsTest : ErrorCodeTest<CordappErrors>(CordappErrors::class.java, true) {
override val dataForCodes = mapOf(
CordappErrors.MISSING_VERSION_ATTRIBUTE to listOf("test-attribute"),
CordappErrors.INVALID_VERSION_IDENTIFIER to listOf(-1, "test-attribute"),
CordappErrors.MULTIPLE_CORDAPPS_FOR_FLOW to listOf("MyTestFlow", "Jar 1, Jar 2"),
CordappErrors.DUPLICATE_CORDAPPS_INSTALLED to listOf("TestCordapp", "testapp.jar", "testapp2.jar")
)
}

View File

@ -0,0 +1,13 @@
package net.corda.commmon.logging.errorReporting
import net.corda.common.logging.errorReporting.NodeDatabaseErrors
import java.net.InetAddress
class DatabaseErrorsTest : ErrorCodeTest<NodeDatabaseErrors>(NodeDatabaseErrors::class.java) {
override val dataForCodes = mapOf(
NodeDatabaseErrors.COULD_NOT_CONNECT to listOf<Any>(),
NodeDatabaseErrors.FAILED_STARTUP to listOf(),
NodeDatabaseErrors.MISSING_DRIVER to listOf(),
NodeDatabaseErrors.PASSWORD_REQUIRED_FOR_H2 to listOf(InetAddress.getLocalHost())
)
}

View File

@ -0,0 +1,61 @@
package net.corda.commmon.logging.errorReporting
import junit.framework.TestCase.assertFalse
import net.corda.common.logging.errorReporting.ErrorCode
import net.corda.common.logging.errorReporting.ErrorCodes
import net.corda.common.logging.errorReporting.ErrorResource
import net.corda.common.logging.errorReporting.ResourceBundleProperties
import org.junit.Test
import java.util.*
import kotlin.test.assertTrue
/**
* Utility for testing that error code resource files behave as expected.
*
* This allows for testing that error messages are printed correctly if they are provided the correct parameters. The test will fail if any
* of the parameters of the template are not filled in.
*
* To use, override the `dataForCodes` with a map from an error code enum value to a list of parameters the message template takes. If any
* are missed, the test will fail.
*
* `printProperties`, if set to true, will print the properties out the resource files, with the error message filled in. This allows the
* message to be inspected.
*/
abstract class ErrorCodeTest<T>(private val clazz: Class<T>,
private val printProperties: Boolean = false) where T: Enum<T>, T: ErrorCodes {
abstract val dataForCodes: Map<T, List<Any>>
private class TestError<T>(override val code: T,
override val parameters: List<Any>) : ErrorCode<T> where T: Enum<T>, T: ErrorCodes
@Test(timeout = 300_000)
fun `test error codes`() {
for ((code, params) in dataForCodes) {
val error = TestError(code, params)
val resource = ErrorResource.fromErrorCode(error, "error-codes", Locale.forLanguageTag("en-US"))
val message = resource.getErrorMessage(error.parameters.toTypedArray())
assertFalse(
"The error message reported for code $code contains missing parameters",
message.contains("\\{.*}".toRegex())
)
val otherProperties = Triple(resource.shortDescription, resource.actionsToFix, resource.aliases)
if (printProperties) {
println("Data for $code")
println("Error Message = $message")
println("${ResourceBundleProperties.SHORT_DESCRIPTION} = ${otherProperties.first}")
println("${ResourceBundleProperties.ACTIONS_TO_FIX} = ${otherProperties.second}")
println("${ResourceBundleProperties.ALIASES} = ${otherProperties.third}")
println("")
}
}
}
@Test(timeout = 300_000)
fun `ensure all error codes tested`() {
val expected = clazz.enumConstants.toSet()
val actual = dataForCodes.keys.toSet()
val missing = expected - actual
assertTrue(missing.isEmpty(), "The following codes have not been tested: $missing")
}
}

View File

@ -0,0 +1,121 @@
package net.corda.commmon.logging.errorReporting
import junit.framework.TestCase.assertEquals
import net.corda.common.logging.errorReporting.ErrorCode
import net.corda.common.logging.errorReporting.ErrorCodes
import net.corda.common.logging.errorReporting.ErrorContextProvider
import net.corda.common.logging.errorReporting.ErrorReporterImpl
import org.junit.After
import org.junit.Test
import org.mockito.ArgumentMatchers.anyString
import org.mockito.Mockito
import org.slf4j.Logger
import java.text.DateFormat
import java.time.Instant
import java.util.*
class ErrorReporterImplTest {
companion object {
private const val TEST_URL = "test-url"
}
private val logs: MutableList<Any> = mutableListOf()
private val loggerMock = Mockito.mock(Logger::class.java).also {
Mockito.`when`(it.error(anyString())).then { logs.addAll(it.arguments) }
}
private val contextProvider: ErrorContextProvider = object : ErrorContextProvider {
override fun getURL(locale: Locale): String {
return "$TEST_URL/${locale.toLanguageTag()}"
}
}
private enum class TestNamespaces {
TEST
}
private enum class TestErrors : ErrorCodes {
CASE1,
CASE2,
CASE_3;
override val namespace = TestNamespaces.TEST.toString()
}
private val TEST_ERROR_1 = object : ErrorCode<TestErrors> {
override val code = TestErrors.CASE1
override val parameters = listOf<Any>()
}
private class TestError2(currentDate: Date) : ErrorCode<TestErrors> {
override val code = TestErrors.CASE2
override val parameters: List<Any> = listOf("foo", 1, currentDate)
}
private val TEST_ERROR_3 = object : ErrorCode<TestErrors> {
override val code = TestErrors.CASE_3
override val parameters = listOf<Any>()
}
private fun createReporterImpl(localeTag: String?) : ErrorReporterImpl {
val locale = if (localeTag != null) Locale.forLanguageTag(localeTag) else Locale.getDefault()
return ErrorReporterImpl("errorReporting", locale, contextProvider)
}
@After
fun tearDown() {
logs.clear()
}
@Test(timeout = 300_000)
fun `error codes logged correctly`() {
val error = TEST_ERROR_1
val testReporter = createReporterImpl("en-US")
testReporter.report(error, loggerMock)
assertEquals(listOf("This is a test message [Code: test-case1, URL: $TEST_URL/en-US]"), logs)
}
@Test(timeout = 300_00)
fun `error code with parameters correctly reported`() {
val currentDate = Date.from(Instant.now())
val error = TestError2(currentDate)
val testReporter = createReporterImpl("en-US")
testReporter.report(error, loggerMock)
val format = DateFormat.getDateInstance(DateFormat.LONG, Locale.forLanguageTag("en-US"))
assertEquals(listOf("This is the second case with string foo, number 1, date ${format.format(currentDate)} [Code: test-case2, URL: $TEST_URL/en-US]"), logs)
}
@Test(timeout = 300_000)
fun `locale used with no corresponding resource falls back to default`() {
val error = TEST_ERROR_1
val testReporter = createReporterImpl("fr-FR")
testReporter.report(error, loggerMock)
assertEquals(listOf("This is a test message [Code: test-case1, URL: $TEST_URL/fr-FR]"), logs)
}
@Test(timeout = 300_000)
fun `locale with corresponding resource causes correct error to be printed`() {
val error = TEST_ERROR_1
val testReporter = createReporterImpl("ga-IE")
testReporter.report(error, loggerMock)
assertEquals(listOf("Is teachtaireacht earráide é seo [Code: test-case1, URL: $TEST_URL/ga-IE]"), logs)
}
@Test(timeout = 300_000)
fun `locale with missing properties falls back to default properties`() {
val error = TEST_ERROR_1
val testReporter = createReporterImpl("es-ES")
testReporter.report(error, loggerMock)
assertEquals(listOf("This is a test message [Code: test-case1, URL: $TEST_URL/es-ES]"), logs)
}
@Test(timeout = 300_000)
fun `error code with underscore in translated to resource file successfully`() {
val error = TEST_ERROR_3
val testReporter = createReporterImpl("en-US")
testReporter.report(error, loggerMock)
assertEquals(listOf("This is the third test message [Code: test-case-3, URL: $TEST_URL/en-US]"), logs)
}
}

View File

@ -0,0 +1,2 @@
errorCodeMessage = Code: {0}
errorCodeUrl = URL: {0}

View File

@ -0,0 +1,2 @@
errorCodeMessage = Code: {0}
errorCodeUrl = URL: {0}

View File

@ -0,0 +1,4 @@
errorTemplate = This is the third test message
shortDescription = Test description
actionsToFix = Actions
aliases =

View File

@ -0,0 +1,4 @@
errorTemplate = This is the third test message
shortDescription = Test description
actionsToFix = Actions
aliases =

View File

@ -0,0 +1,4 @@
errorTemplate = This is a test message
shortDescription = Test description
actionsToFix = Actions
aliases = foo, bar

View File

@ -0,0 +1,3 @@
errorTemplate = This is a test message
shortDescription = Test description
actionsToFix = Actions

View File

@ -0,0 +1 @@
shortDescription = Descripción de la prueba

View File

@ -0,0 +1,3 @@
errorTemplate = Is teachtaireacht earráide é seo
shortDescription = Teachtaireacht tástála
actionsToFix = Roinnt gníomhartha

View File

@ -0,0 +1,4 @@
errorTemplate = This is the second case with string {0}, number {1, number, integer}, date {2, date, long}
shortDescription = Test description
actionsToFix = Actions
aliases = ""

View File

@ -0,0 +1,4 @@
errorTemplate = This is the second case with string {0}, number {1, number, integer}, date {2, date, long}
shortDescription = Test description
actionsToFix = Actions
aliases =

View File

@ -0,0 +1,4 @@
errorTemplate = Seo an dara cás le sreang {0}, uimhir {1, uimhir, slánuimhir}, dáta {2, dáta, fada}
shortDescription = An dara tuairisc
actionsToFix = Roinnt gníomhartha eile
aliases =

View File

@ -9,6 +9,7 @@ dependencies {
compile project(":core")
compile project(":serialization") // TODO Remove this once the NetworkBootstrapper class is moved into the tools:bootstrapper module
compile project(':common-configuration-parsing') // TODO Remove this dependency once NetworkBootsrapper is moved into tools:bootstrapper
compile project(':common-logging')
compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"

View File

@ -4,10 +4,12 @@ import co.paralleluniverse.strands.Strand
import com.zaxxer.hikari.HikariDataSource
import com.zaxxer.hikari.pool.HikariPool
import com.zaxxer.hikari.util.ConcurrentBag
import net.corda.common.logging.errorReporting.ErrorCode
import net.corda.core.flows.HospitalizeFlowException
import net.corda.core.internal.NamedCacheFactory
import net.corda.core.schemas.MappedSchema
import net.corda.core.utilities.contextLogger
import net.corda.common.logging.errorReporting.NodeDatabaseErrors
import org.hibernate.tool.schema.spi.SchemaManagementException
import rx.Observable
import rx.Subscriber
@ -420,7 +422,10 @@ private fun Throwable.hasSQLExceptionCause(): Boolean =
else -> cause?.hasSQLExceptionCause() ?: false
}
class CouldNotCreateDataSourceException(override val message: String?, override val cause: Throwable? = null) : Exception()
class CouldNotCreateDataSourceException(override val message: String?,
override val code: NodeDatabaseErrors,
override val parameters: List<Any> = listOf(),
override val cause: Throwable? = null) : ErrorCode<NodeDatabaseErrors>, Exception()
class HibernateSchemaChangeException(override val message: String?, override val cause: Throwable? = null): Exception()

View File

@ -6,6 +6,7 @@ import com.google.common.collect.MutableClassToInstanceMap
import com.google.common.util.concurrent.MoreExecutors
import com.google.common.util.concurrent.ThreadFactoryBuilder
import com.zaxxer.hikari.pool.HikariPool
import net.corda.common.logging.errorReporting.NodeDatabaseErrors
import net.corda.confidential.SwapIdentitiesFlow
import net.corda.core.CordaException
import net.corda.core.concurrent.CordaFuture
@ -1353,10 +1354,19 @@ fun CordaPersistence.startHikariPool(hikariProperties: Properties, databaseConfi
start(dataSource)
} catch (ex: Exception) {
when {
ex is HikariPool.PoolInitializationException -> throw CouldNotCreateDataSourceException("Could not connect to the database. Please check your JDBC connection URL, or the connectivity to the database.", ex)
ex.cause is ClassNotFoundException -> throw CouldNotCreateDataSourceException("Could not find the database driver class. Please add it to the 'drivers' folder. See: https://docs.corda.net/corda-configuration-file.html")
ex is HikariPool.PoolInitializationException -> throw CouldNotCreateDataSourceException(
"Could not connect to the database. Please check your JDBC connection URL, or the connectivity to the database.",
NodeDatabaseErrors.COULD_NOT_CONNECT,
cause = ex)
ex.cause is ClassNotFoundException -> throw CouldNotCreateDataSourceException(
"Could not find the database driver class. Please add it to the 'drivers' folder. See: https://docs.corda.net/corda-configuration-file.html",
NodeDatabaseErrors.MISSING_DRIVER)
ex is OutstandingDatabaseChangesException -> throw (DatabaseIncompatibleException(ex.message))
else -> throw CouldNotCreateDataSourceException("Could not create the DataSource: ${ex.message}", ex)
else ->
throw CouldNotCreateDataSourceException(
"Could not create the DataSource: ${ex.message}",
NodeDatabaseErrors.FAILED_STARTUP,
cause = ex)
}
}
}

View File

@ -73,6 +73,7 @@ import net.corda.node.utilities.DefaultNamedCacheFactory
import net.corda.node.utilities.DemoClock
import net.corda.node.utilities.errorAndTerminate
import net.corda.nodeapi.internal.ArtemisMessagingClient
import net.corda.common.logging.errorReporting.NodeDatabaseErrors
import net.corda.nodeapi.internal.ShutdownHook
import net.corda.nodeapi.internal.addShutdownHook
import net.corda.nodeapi.internal.bridging.BridgeControlListener
@ -516,7 +517,10 @@ open class Node(configuration: NodeConfiguration,
if (effectiveH2Settings?.address != null) {
if (!InetAddress.getByName(effectiveH2Settings.address.host).isLoopbackAddress
&& configuration.dataSourceProperties.getProperty("dataSource.password").isBlank()) {
throw CouldNotCreateDataSourceException("Database password is required for H2 server listening on ${InetAddress.getByName(effectiveH2Settings.address.host)}.")
throw CouldNotCreateDataSourceException(
"Database password is required for H2 server listening on ${InetAddress.getByName(effectiveH2Settings.address.host)}.",
NodeDatabaseErrors.PASSWORD_REQUIRED_FOR_H2,
listOf(InetAddress.getByName(effectiveH2Settings.address.host).toString()))
}
val databaseName = databaseUrl.removePrefix(h2Prefix).substringBefore(';')
val baseDir = Paths.get(databaseName).parent.toString()

View File

@ -6,6 +6,8 @@ import net.corda.cliutils.CordaCliWrapper
import net.corda.cliutils.ExitCodes
import net.corda.cliutils.printError
import net.corda.common.logging.CordaVersion
import net.corda.common.logging.errorReporting.CordaErrorContextProvider
import net.corda.common.logging.errorReporting.ErrorCode
import net.corda.core.contracts.HashAttachmentConstraint
import net.corda.core.crypto.Crypto
import net.corda.core.internal.*
@ -16,6 +18,8 @@ import net.corda.core.utilities.Try
import net.corda.core.utilities.contextLogger
import net.corda.core.utilities.loggerFor
import net.corda.node.*
import net.corda.common.logging.errorReporting.ErrorReporting
import net.corda.common.logging.errorReporting.report
import net.corda.node.internal.Node.Companion.isInvalidJavaVersion
import net.corda.node.internal.cordapp.MultipleCordappsForFlowException
import net.corda.node.internal.subcommands.*
@ -140,6 +144,7 @@ open class NodeStartup : NodeStartupLogging {
private val logger by lazy { loggerFor<Node>() } // I guess this is lazy to allow for logging init, but why Node?
const val LOGS_DIRECTORY_NAME = "logs"
const val LOGS_CAN_BE_FOUND_IN_STRING = "Logs can be found in"
const val ERROR_CODE_RESOURCE_LOCATION = "error-codes"
}
lateinit var cmdLineOptions: SharedNodeCmdLineOptions
@ -169,6 +174,10 @@ open class NodeStartup : NodeStartupLogging {
?: return ExitCodes.FAILURE
val configuration = cmdLineOptions.parseConfiguration(rawConfig).doIfValid { logRawConfig(rawConfig) }.doOnErrors(::logConfigurationErrors).optional
?: return ExitCodes.FAILURE
ErrorReporting()
.usingResourcesAt(ERROR_CODE_RESOURCE_LOCATION)
.withContextProvider(CordaErrorContextProvider())
.initialiseReporting()
// Step 6. Check if we can access the certificates directory
if (requireCertificates && !canReadCertificatesDirectory(configuration.certificatesDirectory, configuration.devMode)) return ExitCodes.FAILURE
@ -482,6 +491,7 @@ interface NodeStartupLogging {
fun handleStartError(error: Throwable) {
when {
error is ErrorCode<*> -> logger.report(error)
error.isExpectedWhenStartingNode() -> error.logAsExpected()
error is CouldNotCreateDataSourceException -> error.logAsUnexpected()
error is Errors.NativeIoException && error.message?.contains("Address already in use") == true -> error.logAsExpected("One of the ports required by the Corda node is already in use.")

View File

@ -3,6 +3,8 @@ package net.corda.node.internal.cordapp
import io.github.classgraph.ClassGraph
import io.github.classgraph.ClassInfo
import io.github.classgraph.ScanResult
import net.corda.common.logging.errorReporting.CordappErrors
import net.corda.common.logging.errorReporting.ErrorCode
import net.corda.core.cordapp.Cordapp
import net.corda.core.crypto.SecureHash
import net.corda.core.crypto.sha256
@ -146,9 +148,7 @@ class JarScanningCordappLoader private constructor(private val cordappJarPaths:
val duplicateCordapps = registeredCordapps.filter { it.jarHash == cordapp.jarHash }.toSet()
if (duplicateCordapps.isNotEmpty()) {
throw IllegalStateException("The CorDapp (name: ${cordapp.info.shortName}, file: ${cordapp.name}) " +
"is installed multiple times on the node. The following files correspond to the exact same content: " +
"${duplicateCordapps.map { it.name }}")
throw DuplicateCordappsInstalledException(cordapp, duplicateCordapps)
}
if (registeredClassName in contractClasses) {
throw IllegalStateException("More than one CorDapp installed on the node for contract $registeredClassName. " +
@ -231,12 +231,21 @@ class JarScanningCordappLoader private constructor(private val cordappJarPaths:
private fun parseVersion(versionStr: String?, attributeName: String): Int {
if (versionStr == null) {
throw CordappInvalidVersionException("Target versionId attribute $attributeName not specified. Please specify a whole number starting from 1.")
throw CordappInvalidVersionException(
"Target versionId attribute $attributeName not specified. Please specify a whole number starting from 1.",
CordappErrors.MISSING_VERSION_ATTRIBUTE,
listOf(attributeName))
}
val version = versionStr.toIntOrNull()
?: throw CordappInvalidVersionException("Version identifier ($versionStr) for attribute $attributeName must be a whole number starting from 1.")
?: throw CordappInvalidVersionException(
"Version identifier ($versionStr) for attribute $attributeName must be a whole number starting from 1.",
CordappErrors.INVALID_VERSION_IDENTIFIER,
listOf(versionStr, attributeName))
if (version < 1) {
throw CordappInvalidVersionException("Target versionId ($versionStr) for attribute $attributeName must not be smaller than 1.")
throw CordappInvalidVersionException(
"Target versionId ($versionStr) for attribute $attributeName must not be smaller than 1.",
CordappErrors.INVALID_VERSION_IDENTIFIER,
listOf(versionStr, attributeName))
}
return version
}
@ -434,12 +443,34 @@ class JarScanningCordappLoader private constructor(private val cordappJarPaths:
/**
* Thrown when scanning CorDapps.
*/
class MultipleCordappsForFlowException(message: String) : Exception(message)
class MultipleCordappsForFlowException(
message: String,
flowName: String,
jars: String
) : Exception(message), ErrorCode<CordappErrors> {
override val code = CordappErrors.MULTIPLE_CORDAPPS_FOR_FLOW
override val parameters = listOf(flowName, jars)
}
/**
* Thrown if an exception occurs whilst parsing version identifiers within cordapp configuration
*/
class CordappInvalidVersionException(msg: String) : Exception(msg)
class CordappInvalidVersionException(
msg: String,
override val code: CordappErrors,
override val parameters: List<Any> = listOf()
) : Exception(msg), ErrorCode<CordappErrors>
/**
* Thrown if duplicate CorDapps are installed on the node
*/
class DuplicateCordappsInstalledException(app: Cordapp, duplicates: Set<Cordapp>)
: IllegalStateException("The CorDapp (name: ${app.info.shortName}, file: ${app.name}) " +
"is installed multiple times on the node. The following files correspond to the exact same content: " +
"${duplicates.map { it.name }}"), ErrorCode<CordappErrors> {
override val code = CordappErrors.DUPLICATE_CORDAPPS_INSTALLED
override val parameters = listOf(app.info.shortName, app.name, duplicates.map { it.name })
}
abstract class CordappLoaderTemplate : CordappLoader {
@ -467,7 +498,9 @@ abstract class CordappLoaderTemplate : CordappLoader {
}
}
throw MultipleCordappsForFlowException("There are multiple CorDapp JARs on the classpath for flow " +
"${entry.value.first().first.name}: [ ${entry.value.joinToString { it.second.jarPath.toString() }} ].")
"${entry.value.first().first.name}: [ ${entry.value.joinToString { it.second.jarPath.toString() }} ].",
entry.value.first().first.name,
entry.value.joinToString { it.second.jarPath.toString() })
}
entry.value.single().second
}

View File

@ -108,4 +108,5 @@ include 'serialization-deterministic'
include 'tools:checkpoint-agent'
include 'detekt-plugins'
include 'tools:error-tool'

View File

@ -0,0 +1,31 @@
apply plugin: 'kotlin'
apply plugin: 'com.github.johnrengelman.shadow'
repositories {
mavenCentral()
}
dependencies {
implementation project(":common-logging")
implementation project(":tools:cliutils")
implementation "info.picocli:picocli:$picocli_version"
implementation "org.apache.logging.log4j:log4j-slf4j-impl:$log4j_version"
testCompile "junit:junit:4.12"
}
jar {
enabled = false
classifier = 'ignore'
}
shadowJar {
baseName = "corda-tools-error-utils"
manifest {
attributes(
'Main-Class': "net.corda.errorUtilities.ErrorToolKt"
)
}
}
assemble.dependsOn shadowJar

View File

@ -0,0 +1,45 @@
package net.corda.errorUtilities
import java.net.URLClassLoader
import java.nio.file.Path
/**
* A class for reading and processing error code resource bundles from a given directory.
*/
class ErrorResourceUtilities {
companion object {
private val ERROR_INFO_RESOURCE_REGEX= ".*ErrorInfo.*".toRegex()
private val DEFAULT_RESOURCE_FILE_REGEX = "[^_]*\\.properties".toRegex()
private val PROPERTIES_FILE_REGEX = ".*\\.properties".toRegex()
/**
* List all resource bundle names in a given directory
*/
fun listResourceNames(location: Path) : List<String> {
return location.toFile().walkTopDown().filter {
it.name.matches(DEFAULT_RESOURCE_FILE_REGEX) && !it.name.matches(ERROR_INFO_RESOURCE_REGEX)
}.map {
it.nameWithoutExtension
}.toList()
}
/**
* List all resource files in a given directory
*/
fun listResourceFiles(location: Path) : List<String> {
return location.toFile().walkTopDown().filter {
it.name.matches(PROPERTIES_FILE_REGEX)
}.map { it.name }.toList()
}
/**
* Create a classloader with all URLs in a given directory
*/
fun loaderFromDirectory(location: Path) : URLClassLoader {
val urls = arrayOf(location.toUri().toURL())
val sysLoader = ClassLoader.getSystemClassLoader()
return URLClassLoader(urls, sysLoader)
}
}
}

View File

@ -0,0 +1,29 @@
package net.corda.errorUtilities
import net.corda.cliutils.CordaCliWrapper
import net.corda.cliutils.ExitCodes
import net.corda.cliutils.start
import net.corda.errorUtilities.docsTable.DocsTableCLI
import net.corda.errorUtilities.resourceGenerator.ResourceGeneratorCLI
fun main(args: Array<String>) = ErrorTool().start(args)
/**
* Entry point for the error utilities.
*
* By itself, this doesn't do anything - instead one of the subcommands should be invoked.
*/
class ErrorTool : CordaCliWrapper("error-utils", "Utilities for working with error codes and error reporting") {
private val errorPageBuilder = DocsTableCLI()
private val errorResourceGenerator = ResourceGeneratorCLI()
override fun additionalSubCommands() = setOf(errorPageBuilder, errorResourceGenerator)
override fun runProgram(): Int {
println("No subcommand specified - please invoke one of the subcommands.")
printHelp()
return ExitCodes.FAILURE
}
}

View File

@ -0,0 +1,23 @@
package net.corda.errorUtilities
import java.lang.IllegalArgumentException
import java.nio.file.Files
import java.nio.file.Path
/**
* Common functions to use among multiple of the error code subcommands
*/
class ErrorToolCLIUtilities {
companion object {
/**
* Checks that a directory provided through Picocli exists.
*/
fun checkDirectory(dir: Path?, expectedContents: String) : Path {
return dir?.also {
require(Files.exists(it)) {
"Directory $it does not exist. Please specify a valid direction for $expectedContents"
}
} ?: throw IllegalArgumentException("No location specified for $expectedContents. Please specify a directory for $expectedContents.")
}
}
}

View File

@ -0,0 +1,7 @@
package net.corda.errorUtilities
abstract class ErrorToolException(msg: String, cause: Exception? = null) : Exception(msg, cause)
class ClassDoesNotExistException(classname: String)
: ErrorToolException("The class $classname could not be found in the provided JAR. " +
"Check that the correct fully qualified name has been provided and the JAR file is the correct one for this class.")

View File

@ -0,0 +1,74 @@
package net.corda.errorUtilities.docsTable
import net.corda.cliutils.CordaCliWrapper
import net.corda.cliutils.ExitCodes
import net.corda.errorUtilities.ErrorToolCLIUtilities
import org.slf4j.LoggerFactory
import picocli.CommandLine
import java.lang.IllegalArgumentException
import java.nio.file.Files
import java.nio.file.Path
import java.util.*
/**
* Error tool sub-command for generating the documentation for error codes.
*
* The command needs a location to output the documentation to and a directory containing the resource files. From this, it generates a
* Markdown table with all defined error codes.
*
* In the event that the file already exists, the tool will report an error and exit.
*/
class DocsTableCLI : CordaCliWrapper("build-docs", "Builds the error table for the error codes page") {
@CommandLine.Parameters(
index = "0",
paramLabel = "OUTPUT_LOCATION",
arity = "1",
description = ["The file system location to output the error codes documentation table"]
)
var outputDir: Path? = null
@CommandLine.Parameters(
index = "1",
paramLabel = "RESOURCE_LOCATION",
arity = "1",
description = ["The file system location of the resource files to process"]
)
var resourceLocation: Path? = null
@CommandLine.Option(
names = ["--locale-tag"],
description = ["The locale tag of the locale to use when localising the error codes table. For example, en-US"],
arity = "1"
)
var localeTag: String? = null
companion object {
private val logger = LoggerFactory.getLogger(DocsTableCLI::class.java)
private const val ERROR_CODES_FILE = "error-codes.md"
}
override fun runProgram(): Int {
val locale = if (localeTag != null) Locale.forLanguageTag(localeTag) else Locale.getDefault()
val (outputFile, resources) = try {
val output = ErrorToolCLIUtilities.checkDirectory(outputDir, "output file")
val outputPath = output.resolve(ERROR_CODES_FILE)
require(Files.notExists(outputPath)) {
"Output file $outputPath exists, please remove it and run again."
}
Pair(outputPath, ErrorToolCLIUtilities.checkDirectory(resourceLocation, "resource bundle files"))
} catch (e: IllegalArgumentException) {
logger.error(e.message, e)
return ExitCodes.FAILURE
}
val tableGenerator = DocsTableGenerator(resources, locale)
try {
val table = tableGenerator.generateMarkdown()
outputFile.toFile().writeText(table)
} catch (e: IllegalArgumentException) {
logger.error(e.message, e)
return ExitCodes.FAILURE
}
return ExitCodes.SUCCESS
}
}

View File

@ -0,0 +1,55 @@
package net.corda.errorUtilities.docsTable
import net.corda.common.logging.errorReporting.ErrorResource
import net.corda.errorUtilities.ErrorResourceUtilities
import java.lang.IllegalArgumentException
import java.nio.file.Path
import java.util.*
/**
* Generate the documentation table given a resource file location set.
*/
class DocsTableGenerator(private val resourceLocation: Path,
private val locale: Locale) {
companion object {
private const val ERROR_CODE_HEADING = "codeHeading"
private const val ALIASES_HEADING = "aliasesHeading"
private const val DESCRIPTION_HEADING = "descriptionHeading"
private const val TO_FIX_HEADING = "toFixHeading"
private const val ERROR_HEADINGS_BUNDLE = "ErrorPageHeadings"
}
private fun getHeading(heading: String) : String {
val resource = ResourceBundle.getBundle(ERROR_HEADINGS_BUNDLE, locale)
return resource.getString(heading)
}
private fun generateTable() : List<List<String>> {
val table = mutableListOf<List<String>>()
val loader = ErrorResourceUtilities.loaderFromDirectory(resourceLocation)
for (resource in ErrorResourceUtilities.listResourceNames(resourceLocation)) {
val errorResource = ErrorResource.fromLoader(resource, loader, locale)
table.add(listOf(resource, errorResource.aliases, errorResource.shortDescription, errorResource.actionsToFix))
}
return table
}
private fun formatTable(tableData: List<List<String>>) : String {
val headings = listOf(
getHeading(ERROR_CODE_HEADING),
getHeading(ALIASES_HEADING),
getHeading(DESCRIPTION_HEADING),
getHeading(TO_FIX_HEADING)
)
val underlines = headings.map { "-".repeat(it.length) }
val fullTable = listOf(headings, underlines) + tableData
return fullTable.joinToString(System.lineSeparator()) { it.joinToString(prefix = "| ", postfix = " |", separator = " | ") }
}
fun generateMarkdown() : String {
if (!resourceLocation.toFile().exists()) throw IllegalArgumentException("Directory $resourceLocation does not exist.")
val tableData = generateTable()
return formatTable(tableData)
}
}

View File

@ -0,0 +1,79 @@
package net.corda.errorUtilities.resourceGenerator
import net.corda.common.logging.errorReporting.ErrorCodes
import net.corda.common.logging.errorReporting.ResourceBundleProperties
import net.corda.errorUtilities.ClassDoesNotExistException
import java.nio.file.Path
import java.util.*
/**
* Generate a set of resource files from an enumeration of error codes.
*/
class ResourceGenerator(private val locales: List<Locale>) {
companion object {
internal const val MESSAGE_TEMPLATE_DEFAULT = "<Message template>"
internal const val SHORT_DESCRIPTION_DEFAULT = "<Short description>"
internal const val ACTIONS_TO_FIX_DEFAULT = "<Actions to fix>"
internal const val ALIASES_DEFAULT = ""
}
private fun createResourceFile(name: String, location: Path) {
val file = location.resolve(name)
val text = """
|${ResourceBundleProperties.MESSAGE_TEMPLATE} = $MESSAGE_TEMPLATE_DEFAULT
|${ResourceBundleProperties.SHORT_DESCRIPTION} = $SHORT_DESCRIPTION_DEFAULT
|${ResourceBundleProperties.ACTIONS_TO_FIX} = $ACTIONS_TO_FIX_DEFAULT
|${ResourceBundleProperties.ALIASES} = $ALIASES_DEFAULT
""".trimMargin()
file.toFile().writeText(text)
}
/**
* Create a set of resource files in the given location.
*
* @param resources The resource file names to create
* @param resourceLocation The location to create the resource files
*/
fun createResources(resources: List<String>, resourceLocation: Path) {
for (resource in resources) {
createResourceFile(resource, resourceLocation)
}
}
private fun definedCodes(classes: List<String>, loader: ClassLoader) : List<String> {
return classes.flatMap {
val clazz = try {
loader.loadClass(it)
} catch (e: ClassNotFoundException) {
throw ClassDoesNotExistException(it)
}
if (ErrorCodes::class.java.isAssignableFrom(clazz) && clazz != ErrorCodes::class.java) {
val namespace = (clazz.enumConstants.first() as ErrorCodes).namespace.toLowerCase()
clazz.enumConstants.map { code -> "${namespace}-${code.toString().toLowerCase().replace("_", "-")}"}
} else {
listOf()
}
}
}
private fun getExpectedResources(codes: List<String>) : List<String> {
return codes.flatMap {
val localeResources = locales.map { locale -> "${it}_${locale.toLanguageTag().replace("-", "_")}.properties"}
localeResources + "$it.properties"
}
}
/**
* Calculate what resource files are missing from a set of resource files, given a set of error codes.
*
* @param classes The classes to generate resource files for
* @param resourceFiles The list of resource files
*/
fun calculateMissingResources(classes: List<String>, resourceFiles: List<String>, loader: ClassLoader) : List<String> {
val codes = definedCodes(classes, loader)
val expected = getExpectedResources(codes)
val missing = expected - resourceFiles.toSet()
return missing.toList()
}
}

View File

@ -0,0 +1,75 @@
package net.corda.errorUtilities.resourceGenerator
import net.corda.cliutils.CordaCliWrapper
import net.corda.cliutils.ExitCodes
import net.corda.errorUtilities.ErrorResourceUtilities
import net.corda.errorUtilities.ErrorToolCLIUtilities
import org.slf4j.LoggerFactory
import picocli.CommandLine
import java.lang.IllegalArgumentException
import java.nio.file.Path
import java.util.*
/**
* Subcommand for generating resource bundles from error codes.
*
* This subcommand takes a directory containing built class files that define the enumerations of codes, and a directory containing any
* existing resource bundles. From this, it generates any missing resource files with the properties specified. The data under these
* properties should then be filled in by hand.
*/
class ResourceGeneratorCLI : CordaCliWrapper(
"generate-resources",
"Generate any missing resource files for a set of error codes"
) {
@CommandLine.Parameters(
index = "0",
paramLabel = "JAR_FILE",
arity = "1",
description = ["JAR file containing class files of the error code definitions"]
)
var jarFile: Path? = null
@CommandLine.Parameters(
index = "1",
paramLabel = "RESOURCE_DIR",
arity = "1",
description = ["Directory containing resource bundles for the error codes"]
)
var resourceDir: Path? = null
@CommandLine.Parameters(
index="2..*",
paramLabel = "ERROR_CODE_CLASSES",
description = ["Fully qualified class names of the error code classes to generate resources for"]
)
var classes: List<String> = mutableListOf()
@CommandLine.Option(
names = ["--locales"],
description = ["The set of locales to generate resource files for. Specified as locale tags, for example en-US"],
arity = "1"
)
var locales: List<String> = listOf("en-US")
companion object {
private val logger = LoggerFactory.getLogger(ResourceGeneratorCLI::class.java)
}
override fun runProgram(): Int {
val jarFileLocation = ErrorToolCLIUtilities.checkDirectory(jarFile, "error code definition class files")
val resourceLocation = ErrorToolCLIUtilities.checkDirectory(resourceDir, "resource bundle files")
val resourceGenerator = ResourceGenerator(locales.map { Locale.forLanguageTag(it) })
try {
val resources = ErrorResourceUtilities.listResourceFiles(resourceLocation)
val loader = ErrorResourceUtilities.loaderFromDirectory(jarFileLocation)
val missingResources = resourceGenerator.calculateMissingResources(classes, resources, loader)
resourceGenerator.createResources(missingResources, resourceLocation)
loader.close()
} catch (e: IllegalArgumentException) {
logger.error(e.message, e)
return ExitCodes.FAILURE
}
return ExitCodes.SUCCESS
}
}

View File

@ -0,0 +1,4 @@
codeHeading = Error Code
aliasesHeading = Aliases
descriptionHeading = Description
toFixHeading = Actions to Fix

View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="info">
<Properties>
<Property name="defaultLogLevel">${sys:defaultLogLevel:-info}</Property>
<Property name="consoleLogLevel">${sys:consoleLogLevel:-error}</Property>
</Properties>
<Appenders>
<Console name="Console-Appender" target="SYSTEM_OUT">
<PatternLayout pattern="[%level{length=5}] %date{HH:mm:ssZ} - %msg%n%throwable{0}"/>
</Console>
</Appenders>
<Loggers>
<Root level="${defaultLogLevel}">
<AppenderRef ref="Console-Appender" level="${consoleLogLevel}"/>
</Root>
</Loggers>
</Configuration>

View File

@ -0,0 +1,45 @@
package net.corda.errorUtilities.docsTable
import junit.framework.TestCase.assertEquals
import org.junit.Test
import java.lang.IllegalArgumentException
import java.nio.file.Paths
import java.util.*
class DocsTableGeneratorTest {
companion object {
private val RESOURCE_LOCATION = Paths.get("src/test/resources/test-errors").toAbsolutePath()
}
private val englishTable = """| Error Code | Aliases | Description | Actions to Fix |
/| ---------- | ------- | ----------- | -------------- |
/| test-error | foo, bar | Test description | Actions |
""".trimMargin("/")
private val irishTable = """| Cód Earráide | Ailiasanna | Cur síos | Caingne le Deisiú |
/| ------------ | ---------- | -------- | ----------------- |
/| test-error | foo, bar | Teachtaireacht tástála | Roinnt gníomhartha |
""".trimMargin("/")
@Test(timeout = 1000)
fun `check error table is produced as expected`() {
val generator = DocsTableGenerator(RESOURCE_LOCATION, Locale.forLanguageTag("en-US"))
val table = generator.generateMarkdown()
// Raw strings in Kotlin always use Unix line endings, so this is required to keep the test passing on Windows
assertEquals(englishTable.split("\n").joinToString(System.lineSeparator()), table)
}
@Test(timeout = 1000)
fun `check table in other locales is produced as expected`() {
val generator = DocsTableGenerator(RESOURCE_LOCATION, Locale.forLanguageTag("ga-IE"))
val table = generator.generateMarkdown()
assertEquals(irishTable.split("\n").joinToString(System.lineSeparator()), table)
}
@Test(expected = IllegalArgumentException::class, timeout = 1000)
fun `error thrown if unknown directory passed to generator`() {
val generator = DocsTableGenerator(Paths.get("not/a/directory"), Locale.getDefault())
generator.generateMarkdown()
}
}

View File

@ -0,0 +1,56 @@
package net.corda.errorUtilities.resourceGenerator
import junit.framework.TestCase.assertEquals
import net.corda.common.logging.errorReporting.ResourceBundleProperties
import org.junit.Test
import java.util.*
class ResourceGeneratorTest {
private val classes = listOf(TestCodes1::class.qualifiedName!!, TestCodes2::class.qualifiedName!!)
private fun expectedCodes() : List<String> {
val codes1 = TestCodes1.values().map { "${it.namespace.toLowerCase()}-${it.name.replace("_", "-").toLowerCase()}" }
val codes2 = TestCodes2.values().map { "${it.namespace.toLowerCase()}-${it.name.replace("_", "-").toLowerCase()}" }
return codes1 + codes2
}
@Test(timeout = 1000)
fun `no codes marked as missing if all resources are present`() {
val resourceGenerator = ResourceGenerator(listOf())
val currentFiles = expectedCodes().map { "$it.properties" }
val missing = resourceGenerator.calculateMissingResources(classes, currentFiles, TestCodes1::class.java.classLoader)
assertEquals(setOf<String>(), missing.toSet())
}
@Test(timeout = 1000)
fun `missing locales are marked as missing when other locales are present`() {
val resourceGenerator = ResourceGenerator(listOf("en-US", "ga-IE").map { Locale.forLanguageTag(it) })
val currentFiles = expectedCodes().flatMap { listOf("$it.properties", "${it}_en_US.properties") }
val missing = resourceGenerator.calculateMissingResources(classes, currentFiles, TestCodes1::class.java.classLoader)
assertEquals(expectedCodes().map { "${it}_ga_IE.properties" }.toSet(), missing.toSet())
}
@Test(timeout = 1000)
fun `test writing out files works correctly`() {
// First test that if all files are missing then the resource generator detects this
val resourceGenerator = ResourceGenerator(listOf())
val currentFiles = listOf<String>()
val missing = resourceGenerator.calculateMissingResources(classes, currentFiles, TestCodes1::class.java.classLoader)
assertEquals(expectedCodes().map { "$it.properties" }.toSet(), missing.toSet())
// Now check that all resource files that should be created are
val tempDir = createTempDir()
resourceGenerator.createResources(missing, tempDir.toPath())
val createdFiles = tempDir.walkTopDown().filter { it.isFile && it.extension == "properties" }.map { it.name }.toSet()
assertEquals(missing.toSet(), createdFiles)
// Now check that a created file has the expected properties and values
val properties = Properties()
properties.load(tempDir.walk().filter { it.isFile && it.extension == "properties"}.first().inputStream())
assertEquals(ResourceGenerator.SHORT_DESCRIPTION_DEFAULT, properties.getProperty(ResourceBundleProperties.SHORT_DESCRIPTION))
assertEquals(ResourceGenerator.ACTIONS_TO_FIX_DEFAULT, properties.getProperty(ResourceBundleProperties.ACTIONS_TO_FIX))
assertEquals(ResourceGenerator.MESSAGE_TEMPLATE_DEFAULT, properties.getProperty(ResourceBundleProperties.MESSAGE_TEMPLATE))
assertEquals(ResourceGenerator.ALIASES_DEFAULT, properties.getProperty(ResourceBundleProperties.ALIASES))
}
}

View File

@ -0,0 +1,23 @@
package net.corda.errorUtilities.resourceGenerator
import net.corda.common.logging.errorReporting.ErrorCodes
// These test errors are not used directly, but their compiled class files are used to verify the resource generator functionality.
enum class TestNamespaces {
TN1,
TN2
}
enum class TestCodes1 : ErrorCodes {
CASE1,
CASE2;
override val namespace = TestNamespaces.TN1.toString()
}
enum class TestCodes2 : ErrorCodes {
CASE1,
CASE3;
override val namespace = TestNamespaces.TN2.toString()
}

View File

@ -0,0 +1,4 @@
codeHeading = Error Code
aliasesHeading = Aliases
descriptionHeading = Description
toFixHeading = Actions to Fix

View File

@ -0,0 +1,4 @@
codeHeading = Cód Earráide
aliasesHeading = Ailiasanna
descriptionHeading = Cur síos
toFixHeading = Caingne le Deisiú

View File

@ -0,0 +1,4 @@
errorTemplate = This is a test message
shortDescription = Test description
actionsToFix = Actions
aliases = foo, bar

View File

@ -0,0 +1,3 @@
errorTemplate = Is teachtaireacht earráide é seo
shortDescription = Teachtaireacht tástála
actionsToFix = Roinnt gníomhartha