From 68e0ab24bf3b22d2e645c5a7b95697c320c55c4c Mon Sep 17 00:00:00 2001 From: Rob Zienert Date: Wed, 18 Dec 2019 14:03:48 -0800 Subject: [PATCH] chore(kotlin): Apply detekt fixes --- .detekt.yml | 577 +----------------- gradle/kotlin.gradle | 1 + .../expressions/ExpressionFunctionProvider.kt | 14 +- .../kork/plugins/SpinnakerPluginManager.kt | 6 +- .../kork/plugins/SpringExtensionFactory.kt | 16 +- .../config/SpringEnvironmentConfigResolver.kt | 3 +- .../loaders/SpinnakerDefaultPluginLoader.kt | 3 +- .../sql/JooqToSpringExceptionTransformer.kt | 5 +- .../sql/config/ConnectionPoolProperties.kt | 1 + .../sql/config/DefaultSqlConfiguration.kt | 14 +- .../config/SecondaryPoolDialectCondition.kt | 19 +- .../kork/sql/config/SqlProperties.kt | 7 +- .../kork/sql/health/SqlHealthProvider.kt | 3 +- 13 files changed, 66 insertions(+), 603 deletions(-) diff --git a/.detekt.yml b/.detekt.yml index 806cbf858..697f68af9 100644 --- a/.detekt.yml +++ b/.detekt.yml @@ -1,580 +1,7 @@ -build: - maxIssues: 10 - weights: - # complexity: 2 - # LongParameterList: 1 - # style: 1 - # comments: 1 - -config: - validation: true - # when writing own rules with new properties, exclude the property path e.g.: "my_rule_set,.*>.*>[my_property]" - excludes: "" - -processors: - active: true - exclude: - # - 'DetektProgressListener' - # - 'FunctionCountProcessor' - # - 'PropertyCountProcessor' - # - 'ClassCountProcessor' - # - 'PackageCountProcessor' - # - 'KtFileCountProcessor' - -console-reports: - active: true - exclude: - # - 'ProjectStatisticsReport' - # - 'ComplexityReport' - # - 'NotificationReport' - # - 'FindingsReport' - - 'FileBasedFindingsReport' - # - 'BuildFailureReport' - -comments: - active: true - excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" - CommentOverPrivateFunction: - active: false - CommentOverPrivateProperty: - active: false - EndOfSentenceFormat: - active: false - endOfSentenceFormat: ([.?!][ \t\n\r\f<])|([.?!:]$) - UndocumentedPublicClass: - active: false - searchInNestedClass: true - searchInInnerClass: true - searchInInnerObject: true - searchInInnerInterface: true - UndocumentedPublicFunction: - active: false - UndocumentedPublicProperty: - active: false - -complexity: - active: true - ComplexCondition: - active: true - threshold: 4 - ComplexInterface: - active: false - threshold: 10 - includeStaticDeclarations: false - ComplexMethod: - active: true - threshold: 15 - ignoreSingleWhenExpression: false - ignoreSimpleWhenEntries: false - ignoreNestingFunctions: false - nestingFunctions: run,let,apply,with,also,use,forEach,isNotNull,ifNull - LabeledExpression: - active: false - ignoredLabels: "" - LargeClass: - active: true - threshold: 600 - LongMethod: - active: true - threshold: 60 - LongParameterList: - active: true - threshold: 6 - ignoreDefaultParameters: false - MethodOverloading: - active: false - threshold: 6 - NestedBlockDepth: - active: true - threshold: 4 - StringLiteralDuplication: - active: false - excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" - threshold: 3 - ignoreAnnotation: true - excludeStringsWithLessThan5Characters: true - ignoreStringsRegex: '$^' - TooManyFunctions: - active: true - excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" - thresholdInFiles: 11 - thresholdInClasses: 11 - thresholdInInterfaces: 11 - thresholdInObjects: 11 - thresholdInEnums: 11 - ignoreDeprecated: false - ignorePrivate: false - ignoreOverridden: false - -empty-blocks: - active: true - EmptyCatchBlock: - active: true - allowedExceptionNameRegex: "^(_|(ignore|expected).*)" - EmptyClassBlock: - active: true - EmptyDefaultConstructor: - active: true - EmptyDoWhileBlock: - active: true - EmptyElseBlock: - active: true - EmptyFinallyBlock: - active: true - EmptyForBlock: - active: true - EmptyFunctionBlock: - active: true - ignoreOverriddenFunctions: false - EmptyIfBlock: - active: true - EmptyInitBlock: - active: true - EmptyKtFile: - active: true - EmptySecondaryConstructor: - active: true - EmptyWhenBlock: - active: true - EmptyWhileBlock: - active: true - -exceptions: - active: true - ExceptionRaisedInUnexpectedLocation: - active: false - methodNames: 'toString,hashCode,equals,finalize' - InstanceOfCheckForException: - active: false - excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" - NotImplementedDeclaration: - active: false - PrintStackTrace: - active: false - RethrowCaughtException: - active: false - ReturnFromFinally: - active: false - ignoreLabeled: false - SwallowedException: - active: false - ignoredExceptionTypes: 'InterruptedException,NumberFormatException,ParseException,MalformedURLException' - allowedExceptionNameRegex: "^(_|(ignore|expected).*)" - ThrowingExceptionFromFinally: - active: false - ThrowingExceptionInMain: - active: false - ThrowingExceptionsWithoutMessageOrCause: - active: false - exceptions: 'IllegalArgumentException,IllegalStateException,IOException' - ThrowingNewInstanceOfSameException: +style: + ThrowsCount: active: false - TooGenericExceptionCaught: - active: true - excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" - exceptionNames: - - ArrayIndexOutOfBoundsException - - Error - - Exception - - IllegalMonitorStateException - - NullPointerException - - IndexOutOfBoundsException - - RuntimeException - - Throwable - allowedExceptionNameRegex: "^(_|(ignore|expected).*)" - TooGenericExceptionThrown: - active: true - exceptionNames: - - Error - - Exception - - Throwable - - RuntimeException formatting: - active: true - android: false - autoCorrect: true - AnnotationOnSeparateLine: - active: false - autoCorrect: true - ChainWrapping: - active: true - autoCorrect: true - CommentSpacing: - active: true - autoCorrect: true - Filename: - active: true - FinalNewline: - active: true - autoCorrect: true - ImportOrdering: - active: false - autoCorrect: true - Indentation: - active: false - autoCorrect: true - indentSize: 4 - continuationIndentSize: 4 - MaximumLineLength: - active: true - maxLineLength: 120 - ModifierOrdering: - active: true - autoCorrect: true - MultiLineIfElse: - active: true - autoCorrect: true - NoBlankLineBeforeRbrace: - active: true - autoCorrect: true - NoConsecutiveBlankLines: - active: true - autoCorrect: true - NoEmptyClassBody: - active: true - autoCorrect: true - NoLineBreakAfterElse: - active: true - autoCorrect: true - NoLineBreakBeforeAssignment: - active: true - autoCorrect: true - NoMultipleSpaces: - active: true - autoCorrect: true - NoSemicolons: - active: true - autoCorrect: true - NoTrailingSpaces: - active: true - autoCorrect: true - NoUnitReturn: - active: true - autoCorrect: true - NoUnusedImports: - active: true - autoCorrect: true - NoWildcardImports: - active: true - PackageName: - active: true - autoCorrect: true ParameterListWrapping: active: false - autoCorrect: true - indentSize: 2 - SpacingAroundColon: - active: true - autoCorrect: true - SpacingAroundComma: - active: true - autoCorrect: true - SpacingAroundCurly: - active: true - autoCorrect: true - SpacingAroundDot: - active: true - autoCorrect: true - SpacingAroundKeyword: - active: true - autoCorrect: true - SpacingAroundOperators: - active: true - autoCorrect: true - SpacingAroundParens: - active: true - autoCorrect: true - SpacingAroundRangeOperator: - active: true - autoCorrect: true - StringTemplate: - active: true - autoCorrect: true - -naming: - active: true - ClassNaming: - active: true - excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" - classPattern: '[A-Z$][a-zA-Z0-9$]*' - ConstructorParameterNaming: - active: true - excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" - parameterPattern: '[a-z][A-Za-z0-9]*' - privateParameterPattern: '[a-z][A-Za-z0-9]*' - excludeClassPattern: '$^' - ignoreOverridden: true - EnumNaming: - active: true - excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" - enumEntryPattern: '^[A-Z][_a-zA-Z0-9]*' - ForbiddenClassName: - active: false - excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" - forbiddenName: '' - FunctionMaxLength: - active: false - excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" - maximumFunctionNameLength: 30 - FunctionMinLength: - active: false - excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" - minimumFunctionNameLength: 3 - FunctionNaming: - active: true - excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" - functionPattern: '^([a-z$][a-zA-Z$0-9]*)|(`.*`)$' - excludeClassPattern: '$^' - ignoreOverridden: true - FunctionParameterNaming: - active: true - excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" - parameterPattern: '[a-z][A-Za-z0-9]*' - excludeClassPattern: '$^' - ignoreOverriddenFunctions: true - InvalidPackageDeclaration: - active: false - rootPackage: '' - MatchingDeclarationName: - active: true - MemberNameEqualsClassName: - active: true - ignoreOverriddenFunction: true - ObjectPropertyNaming: - active: true - excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" - constantPattern: '[A-Za-z][_A-Za-z0-9]*' - propertyPattern: '[A-Za-z][_A-Za-z0-9]*' - privatePropertyPattern: '(_)?[A-Za-z][_A-Za-z0-9]*' - PackageNaming: - active: true - excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" - packagePattern: '^[a-z]+(\.[a-z][A-Za-z0-9]*)*$' - TopLevelPropertyNaming: - active: true - excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" - constantPattern: '[A-Z][_A-Z0-9]*' - propertyPattern: '[A-Za-z][_A-Za-z0-9]*' - privatePropertyPattern: '_?[A-Za-z][_A-Za-z0-9]*' - VariableMaxLength: - active: false - excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" - maximumVariableNameLength: 64 - VariableMinLength: - active: false - excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" - minimumVariableNameLength: 1 - VariableNaming: - active: true - excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" - variablePattern: '[a-z][A-Za-z0-9]*' - privateVariablePattern: '(_)?[a-z][A-Za-z0-9]*' - excludeClassPattern: '$^' - ignoreOverridden: true - -performance: - active: true - ArrayPrimitive: - active: true - ForEachOnRange: - active: true - excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" - SpreadOperator: - active: true - excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" - UnnecessaryTemporaryInstantiation: - active: true - -potential-bugs: - active: true - Deprecation: - active: false - DuplicateCaseInWhenExpression: - active: true - EqualsAlwaysReturnsTrueOrFalse: - active: true - EqualsWithHashCodeExist: - active: true - ExplicitGarbageCollectionCall: - active: true - HasPlatformType: - active: false - ImplicitDefaultLocale: - active: false - InvalidRange: - active: true - IteratorHasNextCallsNextMethod: - active: true - IteratorNotThrowingNoSuchElementException: - active: true - LateinitUsage: - active: false - excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" - excludeAnnotatedProperties: "" - ignoreOnClassesPattern: "" - MissingWhenCase: - active: true - RedundantElseInWhen: - active: true - UnconditionalJumpStatementInLoop: - active: false - UnreachableCode: - active: true - UnsafeCallOnNullableType: - active: true - UnsafeCast: - active: false - UselessPostfixExpression: - active: false - WrongEqualsTypeParameter: - active: true - -style: - active: true - CollapsibleIfStatements: - active: false - DataClassContainsFunctions: - active: false - conversionFunctionPrefix: 'to' - DataClassShouldBeImmutable: - active: false - EqualsNullCall: - active: true - EqualsOnSignatureLine: - active: false - ExplicitItLambdaParameter: - active: false - ExpressionBodySyntax: - active: false - includeLineWrapping: false - ForbiddenComment: - active: true - values: 'TODO:,FIXME:,STOPSHIP:' - allowedPatterns: "" - ForbiddenImport: - active: false - imports: '' - forbiddenPatterns: "" - ForbiddenVoid: - active: false - ignoreOverridden: false - ignoreUsageInGenerics: false - FunctionOnlyReturningConstant: - active: true - ignoreOverridableFunction: true - excludedFunctions: 'describeContents' - excludeAnnotatedFunction: "dagger.Provides" - LibraryCodeMustSpecifyReturnType: - active: true - LoopWithTooManyJumpStatements: - active: true - maxJumpCount: 1 - MagicNumber: - active: true - excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" - ignoreNumbers: '-1,0,1,2' - ignoreHashCodeFunction: true - ignorePropertyDeclaration: false - ignoreLocalVariableDeclaration: false - ignoreConstantDeclaration: true - ignoreCompanionObjectPropertyDeclaration: true - ignoreAnnotation: false - ignoreNamedArgument: true - ignoreEnums: false - ignoreRanges: false - MandatoryBracesIfStatements: - active: false - MaxLineLength: - active: true - maxLineLength: 120 - excludePackageStatements: true - excludeImportStatements: true - excludeCommentStatements: false - MayBeConst: - active: true - ModifierOrder: - active: true - NestedClassesVisibility: - active: false - NewLineAtEndOfFile: - active: true - NoTabs: - active: false - OptionalAbstractKeyword: - active: true - OptionalUnit: - active: false - OptionalWhenBraces: - active: false - PreferToOverPairSyntax: - active: false - ProtectedMemberInFinalClass: - active: true - RedundantExplicitType: - active: false - RedundantVisibilityModifierRule: - active: false - ReturnCount: - active: true - max: 2 - excludedFunctions: "equals" - excludeLabeled: false - excludeReturnFromLambda: true - excludeGuardClauses: false - SafeCast: - active: true - SerialVersionUIDInSerializableClass: - active: false - SpacingBetweenPackageAndImports: - active: false - ThrowsCount: - active: true - max: 2 - TrailingWhitespace: - active: false - UnderscoresInNumericLiterals: - active: false - acceptableDecimalLength: 5 - UnnecessaryAbstractClass: - active: true - excludeAnnotatedClasses: "dagger.Module" - UnnecessaryApply: - active: false - UnnecessaryInheritance: - active: true - UnnecessaryLet: - active: false - UnnecessaryParentheses: - active: false - UntilInsteadOfRangeTo: - active: false - UnusedImports: - active: false - UnusedPrivateClass: - active: true - UnusedPrivateMember: - active: false - allowedNames: "(_|ignored|expected|serialVersionUID)" - UseArrayLiteralsInAnnotations: - active: false - UseCheckOrError: - active: false - UseDataClass: - active: false - excludeAnnotatedClasses: "" - allowVars: false - UseIfInsteadOfWhen: - active: false - UseRequire: - active: false - UselessCallOnNotNull: - active: true - UtilityClassWithPublicConstructor: - active: true - VarCouldBeVal: - active: false - WildcardImport: - active: true - excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" - excludeImports: 'java.util.*,kotlinx.android.synthetic.*' diff --git a/gradle/kotlin.gradle b/gradle/kotlin.gradle index 860c4569d..6775bc041 100644 --- a/gradle/kotlin.gradle +++ b/gradle/kotlin.gradle @@ -53,6 +53,7 @@ compileKotlin { detekt { parallel = true config = files("$rootDir/.detekt.yml") + buildUponDefaultConfig = true reports { xml { enabled = false diff --git a/kork-expressions/src/main/kotlin/com/netflix/spinnaker/kork/expressions/ExpressionFunctionProvider.kt b/kork-expressions/src/main/kotlin/com/netflix/spinnaker/kork/expressions/ExpressionFunctionProvider.kt index 4c28d760f..16b5f6475 100644 --- a/kork-expressions/src/main/kotlin/com/netflix/spinnaker/kork/expressions/ExpressionFunctionProvider.kt +++ b/kork-expressions/src/main/kotlin/com/netflix/spinnaker/kork/expressions/ExpressionFunctionProvider.kt @@ -87,14 +87,21 @@ interface ExpressionFunctionProvider : ExtensionPoint { val parameters: List, val documentation: FunctionDocumentation? ) { - @Deprecated("Please use the overload with description", replaceWith = ReplaceWith("FunctionDefinition(name, \"\", functionParameters)")) + @Deprecated( + "Please use the overload with description", + replaceWith = ReplaceWith("FunctionDefinition(name, \"\", functionParameters)")) constructor(name: String, vararg functionParameters: FunctionParameter) : this(name, "", listOf(*functionParameters), null) constructor(name: String, description: String, vararg functionParameters: FunctionParameter) : this(name, description, listOf(*functionParameters), null) - constructor(name: String, description: String, documentation: FunctionDocumentation, vararg functionParameters: FunctionParameter) : + constructor( + name: String, + description: String, + documentation: FunctionDocumentation, + vararg functionParameters: FunctionParameter + ) : this(name, description, listOf(*functionParameters), documentation) } @@ -131,7 +138,8 @@ interface ExpressionFunctionProvider : ExtensionPoint { * This is used by deck to display in-line docs for a SpEL function * * @param usage example usage, e.g. "#stage('bake in us-east').hasSucceeded" - * @param description explanation of the usage sample, markdown supported e.g. "checks if the bake stage has completed successfully" + * @param description explanation of the usage sample, markdown supported + * e.g. "checks if the bake stage has completed successfully" */ data class FunctionUsageExample( val usage: String, diff --git a/kork-plugins/src/main/kotlin/com/netflix/spinnaker/kork/plugins/SpinnakerPluginManager.kt b/kork-plugins/src/main/kotlin/com/netflix/spinnaker/kork/plugins/SpinnakerPluginManager.kt index e9d070121..07253dee9 100644 --- a/kork-plugins/src/main/kotlin/com/netflix/spinnaker/kork/plugins/SpinnakerPluginManager.kt +++ b/kork-plugins/src/main/kotlin/com/netflix/spinnaker/kork/plugins/SpinnakerPluginManager.kt @@ -24,8 +24,8 @@ import com.netflix.spinnaker.kork.plugins.loaders.SpinnakerJarPluginLoader import org.pf4j.CompoundPluginLoader import org.pf4j.DefaultPluginManager import org.pf4j.ExtensionFactory -import org.pf4j.PluginLoader import org.pf4j.PluginDescriptorFinder +import org.pf4j.PluginLoader import org.pf4j.PluginStatusProvider import org.pf4j.PluginWrapper import java.nio.file.Path @@ -46,11 +46,11 @@ open class SpinnakerPluginManager( private val springExtensionFactory: ExtensionFactory = SpringExtensionFactory(this, configResolver) - private inner class ExtensionFactoryDelegate() : ExtensionFactory { + private inner class ExtensionFactoryDelegate : ExtensionFactory { override fun create(extensionClass: Class?): T = springExtensionFactory.create(extensionClass) } - private inner class PluginStatusProviderDelegate() : PluginStatusProvider { + private inner class PluginStatusProviderDelegate : PluginStatusProvider { override fun disablePlugin(pluginId: String?) = statusProvider.disablePlugin(pluginId) override fun isPluginDisabled(pluginId: String?): Boolean = statusProvider.isPluginDisabled(pluginId) diff --git a/kork-plugins/src/main/kotlin/com/netflix/spinnaker/kork/plugins/SpringExtensionFactory.kt b/kork-plugins/src/main/kotlin/com/netflix/spinnaker/kork/plugins/SpringExtensionFactory.kt index a40702951..0b24688aa 100644 --- a/kork-plugins/src/main/kotlin/com/netflix/spinnaker/kork/plugins/SpringExtensionFactory.kt +++ b/kork-plugins/src/main/kotlin/com/netflix/spinnaker/kork/plugins/SpringExtensionFactory.kt @@ -102,6 +102,7 @@ class SpringExtensionFactory( /** * Load an extension config, provided a set of [ConfigCoordinates]. */ + @Suppress("ThrowsCount") private fun loadConfig(extension: Any, coordinates: ConfigCoordinates) { if (extension !is ConfigurableExtension<*>) { return @@ -127,15 +128,18 @@ class SpringExtensionFactory( } catch (se: SecurityException) { throw SystemException(se) } catch (iae: IllegalAccessException) { - throw SystemException("Could not access setConfiguration method on extension: ${extension.javaClass.name}", iae) + throw SystemException( + "Could not access setConfiguration method on extension: ${extension.javaClass.name}", iae) } catch (iae: IllegalArgumentException) { - throw SystemException("Configuration on extension appears to be invalid: ${extension.javaClass.name}", iae) + throw SystemException( + "Configuration on extension appears to be invalid: ${extension.javaClass.name}", iae) } catch (ite: InvocationTargetException) { - throw SystemException("Failed to invoke setConfiguration on extension: ${extension.javaClass.name}", ite) + throw SystemException( + "Failed to invoke setConfiguration on extension: ${extension.javaClass.name}", ite) } } - ?: throw SystemException( - "Could not find configuration class '${resolvedType.getGeneric(0)}' for extension: ${extension.javaClass.name}") + ?: throw SystemException("Could not find configuration class " + + "'${resolvedType.getGeneric(0)}' for extension: ${extension.javaClass.name}") } } @@ -147,7 +151,7 @@ class SpringExtensionFactory( private fun createWithoutSpring(extensionClass: Class): T? { try { return extensionClass.newInstance() - } catch (e: Exception) { + } catch (@Suppress("TooGenericExceptionCaught") e: Exception) { log.error(e.message, e) } return null diff --git a/kork-plugins/src/main/kotlin/com/netflix/spinnaker/kork/plugins/config/SpringEnvironmentConfigResolver.kt b/kork-plugins/src/main/kotlin/com/netflix/spinnaker/kork/plugins/config/SpringEnvironmentConfigResolver.kt index 7b8650f4d..334917a1a 100644 --- a/kork-plugins/src/main/kotlin/com/netflix/spinnaker/kork/plugins/config/SpringEnvironmentConfigResolver.kt +++ b/kork-plugins/src/main/kotlin/com/netflix/spinnaker/kork/plugins/config/SpringEnvironmentConfigResolver.kt @@ -32,6 +32,7 @@ import org.slf4j.LoggerFactory import org.springframework.core.env.ConfigurableEnvironment import org.springframework.core.env.EnumerablePropertySource import java.lang.reflect.ParameterizedType +import java.lang.RuntimeException import java.util.Properties /** @@ -99,7 +100,7 @@ class SpringEnvironmentConfigResolver( throw IntegrationException("Failed reading extension config: Input appears invalid", pe) } catch (me: JsonMappingException) { throw IntegrationException("Failed reading extension config: Could not map provided config to expected shape", me) - } catch (e: Exception) { + } catch (@Suppress("TooGenericExceptionCaught") e: RuntimeException) { throw SystemException("Failed resolving extension config for an unexpected reason", e) } } diff --git a/kork-plugins/src/main/kotlin/com/netflix/spinnaker/kork/plugins/loaders/SpinnakerDefaultPluginLoader.kt b/kork-plugins/src/main/kotlin/com/netflix/spinnaker/kork/plugins/loaders/SpinnakerDefaultPluginLoader.kt index 5ea4c63d4..9957063a6 100644 --- a/kork-plugins/src/main/kotlin/com/netflix/spinnaker/kork/plugins/loaders/SpinnakerDefaultPluginLoader.kt +++ b/kork-plugins/src/main/kotlin/com/netflix/spinnaker/kork/plugins/loaders/SpinnakerDefaultPluginLoader.kt @@ -34,7 +34,8 @@ class SpinnakerDefaultPluginLoader( override fun createPluginClassLoader(pluginPath: Path, pluginDescriptor: PluginDescriptor): PluginClassLoader { if (pluginDescriptor !is SpinnakerPluginDescriptor) { - log.debug("Descriptor for ${pluginDescriptor.pluginId} is not SpinnakerPluginDescriptor: Falling back to default behavior") + log.debug("Descriptor for ${pluginDescriptor.pluginId} is not SpinnakerPluginDescriptor: " + + "Falling back to default behavior") return super.createPluginClassLoader(pluginPath, pluginDescriptor) } diff --git a/kork-sql/src/main/kotlin/com/netflix/spinnaker/kork/sql/JooqToSpringExceptionTransformer.kt b/kork-sql/src/main/kotlin/com/netflix/spinnaker/kork/sql/JooqToSpringExceptionTransformer.kt index aa2341b20..0e9ecc1c9 100644 --- a/kork-sql/src/main/kotlin/com/netflix/spinnaker/kork/sql/JooqToSpringExceptionTransformer.kt +++ b/kork-sql/src/main/kotlin/com/netflix/spinnaker/kork/sql/JooqToSpringExceptionTransformer.kt @@ -25,10 +25,11 @@ class JooqToSpringExceptionTransformer : DefaultExecuteListener() { override fun exception(ctx: ExecuteContext) { if (ctx.sqlException() != null) { val dialect = ctx.configuration().dialect() - val translator = if (dialect != null) + val translator = if (dialect != null) { SQLErrorCodeSQLExceptionTranslator(dialect.name) - else + } else { SQLStateSQLExceptionTranslator() + } ctx.exception(translator.translate("jOOQ", ctx.sql(), ctx.sqlException())) } } diff --git a/kork-sql/src/main/kotlin/com/netflix/spinnaker/kork/sql/config/ConnectionPoolProperties.kt b/kork-sql/src/main/kotlin/com/netflix/spinnaker/kork/sql/config/ConnectionPoolProperties.kt index 245c4a33d..13e1861fb 100644 --- a/kork-sql/src/main/kotlin/com/netflix/spinnaker/kork/sql/config/ConnectionPoolProperties.kt +++ b/kork-sql/src/main/kotlin/com/netflix/spinnaker/kork/sql/config/ConnectionPoolProperties.kt @@ -18,6 +18,7 @@ package com.netflix.spinnaker.kork.sql.config import org.jooq.SQLDialect import java.util.concurrent.TimeUnit +@Suppress("MagicNumber") data class ConnectionPoolProperties( var dialect: SQLDialect = SQLDialect.MYSQL, var jdbcUrl: String? = null, diff --git a/kork-sql/src/main/kotlin/com/netflix/spinnaker/kork/sql/config/DefaultSqlConfiguration.kt b/kork-sql/src/main/kotlin/com/netflix/spinnaker/kork/sql/config/DefaultSqlConfiguration.kt index a928f5e3c..a1470b7f2 100644 --- a/kork-sql/src/main/kotlin/com/netflix/spinnaker/kork/sql/config/DefaultSqlConfiguration.kt +++ b/kork-sql/src/main/kotlin/com/netflix/spinnaker/kork/sql/config/DefaultSqlConfiguration.kt @@ -40,10 +40,10 @@ import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration import org.springframework.boot.autoconfigure.jdbc.metadata.DataSourcePoolMetadataProvidersConfiguration import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Conditional import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.DependsOn import org.springframework.context.annotation.Import -import org.springframework.context.annotation.Conditional import org.springframework.jdbc.datasource.DataSourceTransactionManager import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy import sun.net.InetAddressCachePolicy @@ -78,6 +78,7 @@ class DefaultSqlConfiguration { fun secondaryLiquibase(properties: SqlProperties): SpringLiquibase = SpringLiquibaseProxy(properties.secondaryMigration) + @Suppress("ReturnCount", "ThrowsCount") @DependsOn("liquibase") @Bean fun dataSource(dataSourceFactory: DataSourceFactory, properties: SqlProperties): DataSource { @@ -174,8 +175,14 @@ class DefaultSqlConfiguration { @Bean(destroyMethod = "close") @Conditional(SecondaryPoolDialectCondition::class) - fun secondaryJooq(connectionProvider: DataSourceConnectionProvider, sqlProperties: SqlProperties): DSLContext { - val secondaryPool: ConnectionPoolProperties = sqlProperties.connectionPools.filter { !it.value.default }.values.first() + fun secondaryJooq( + connectionProvider: DataSourceConnectionProvider, + sqlProperties: SqlProperties + ): DSLContext { + val secondaryPool: ConnectionPoolProperties = sqlProperties.connectionPools + .filter { !it.value.default } + .values + .first() val secondaryJooqConfig: DefaultConfiguration = DefaultConfiguration().apply { set(*DefaultExecuteListenerProvider.providers( JooqToSpringExceptionTransformer(), @@ -224,6 +231,7 @@ private fun forceInetAddressCachePolicy() { class InetAddressOverrideFailure(cause: Throwable) : IllegalStateException(cause) +@Suppress("ThrowsCount") private fun validateDefaultTargetDataSources(targets: Collection) { if (targets.isEmpty()) { throw BeanCreationException("At least one connection pool must be configured") diff --git a/kork-sql/src/main/kotlin/com/netflix/spinnaker/kork/sql/config/SecondaryPoolDialectCondition.kt b/kork-sql/src/main/kotlin/com/netflix/spinnaker/kork/sql/config/SecondaryPoolDialectCondition.kt index eb96687c1..babe5932e 100644 --- a/kork-sql/src/main/kotlin/com/netflix/spinnaker/kork/sql/config/SecondaryPoolDialectCondition.kt +++ b/kork-sql/src/main/kotlin/com/netflix/spinnaker/kork/sql/config/SecondaryPoolDialectCondition.kt @@ -18,11 +18,11 @@ package com.netflix.spinnaker.kork.sql.config import org.springframework.boot.autoconfigure.condition.ConditionOutcome import org.springframework.boot.autoconfigure.condition.SpringBootCondition -import org.springframework.context.annotation.ConditionContext -import org.springframework.core.type.AnnotatedTypeMetadata -import org.springframework.boot.context.properties.source.ConfigurationPropertyName import org.springframework.boot.context.properties.bind.Bindable import org.springframework.boot.context.properties.bind.Binder +import org.springframework.boot.context.properties.source.ConfigurationPropertyName +import org.springframework.context.annotation.ConditionContext +import org.springframework.core.type.AnnotatedTypeMetadata class SecondaryPoolDialectCondition : SpringBootCondition() { @@ -39,9 +39,18 @@ class SecondaryPoolDialectCondition : SpringBootCondition() { return false } - val defaultPool: ConnectionPoolProperties = sqlProperties.connectionPools.filter { it.value.default }.values.first() - val secondaryPool: ConnectionPoolProperties = sqlProperties.connectionPools.filter { !it.value.default }.values.first() + val defaultPool: ConnectionPoolProperties = sqlProperties.connectionPools.first(default = true) + val secondaryPool: ConnectionPoolProperties = sqlProperties.connectionPools.first(default = false) return defaultPool.dialect != secondaryPool.dialect } + + private fun MutableMap.first(default: Boolean): ConnectionPoolProperties = + filter { + if (default) { + it.value.default + } else { + !it.value.default + } + }.values.first() } diff --git a/kork-sql/src/main/kotlin/com/netflix/spinnaker/kork/sql/config/SqlProperties.kt b/kork-sql/src/main/kotlin/com/netflix/spinnaker/kork/sql/config/SqlProperties.kt index 069146cd4..dc48687bc 100644 --- a/kork-sql/src/main/kotlin/com/netflix/spinnaker/kork/sql/config/SqlProperties.kt +++ b/kork-sql/src/main/kotlin/com/netflix/spinnaker/kork/sql/config/SqlProperties.kt @@ -35,10 +35,11 @@ data class SqlProperties( } return connectionPool!! } - if (connectionPools.size == 1) { - return connectionPools.values.first() + return if (connectionPools.size == 1) { + connectionPools.values.first() + } else { + connectionPools.values.first { it.default } } - return connectionPools.values.first { it.default } } } diff --git a/kork-sql/src/main/kotlin/com/netflix/spinnaker/kork/sql/health/SqlHealthProvider.kt b/kork-sql/src/main/kotlin/com/netflix/spinnaker/kork/sql/health/SqlHealthProvider.kt index e522a8bb1..92a90118f 100644 --- a/kork-sql/src/main/kotlin/com/netflix/spinnaker/kork/sql/health/SqlHealthProvider.kt +++ b/kork-sql/src/main/kotlin/com/netflix/spinnaker/kork/sql/health/SqlHealthProvider.kt @@ -34,6 +34,7 @@ class SqlHealthProvider( private val log = LoggerFactory.getLogger(javaClass) + @Suppress("VariableNaming") internal val _enabled = AtomicBoolean(false) private val _healthException: AtomicReference = AtomicReference() @@ -66,7 +67,7 @@ class SqlHealthProvider( } } unhealthyCounter.set(0) - } catch (e: Exception) { + } catch (@Suppress("TooGenericExceptionCaught") e: Exception) { _healthException.set(e) healthyCounter.set(0) unhealthyCounter.incrementAndGet().also { unhealthyCount ->