Skip to content

Commit f6643e4

Browse files
committed
Reduce SonarQube alert by cleaning the code a bit.
1 parent 1a8ece2 commit f6643e4

File tree

14 files changed

+78
-158
lines changed

14 files changed

+78
-158
lines changed

common/src/main/kotlin/com/cosmotech/common/config/CsmApiConfiguration.kt

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@ open class CsmApiConfiguration {
3434

3535
@Bean(name = ["csm-in-process-event-executor"])
3636
open fun inProcessEventHandlerExecutor(): Executor =
37-
// TODO A better strategy could be with a limited core pool size off an unbounded queue ?
3837
Executors.newCachedThreadPool(
3938
BasicThreadFactory.builder().namingPattern("csm-event-handler-%d").build()
4039
)
@@ -92,8 +91,8 @@ class YamlMessageConverter(objectMapper: ObjectMapper) :
9291
constructor() : this(yamlObjectMapper())
9392

9493
override fun setObjectMapper(objectMapper: ObjectMapper) {
95-
if (objectMapper.factory !is YAMLFactory) {
96-
throw IllegalArgumentException("ObjectMapper must be configured with YAMLFactory")
94+
require(objectMapper.factory is YAMLFactory) {
95+
"ObjectMapper must be configured with YAMLFactory"
9796
}
9897
super.setObjectMapper(objectMapper)
9998
}

common/src/main/kotlin/com/cosmotech/common/config/CsmOpenAPIConfiguration.kt

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,12 +28,12 @@ open class CsmOpenAPIConfiguration(val csmPlatformProperties: CsmPlatformPropert
2828
val openApiYamlContent =
2929
openApiYamlInputStream.use { it.bufferedReader().use(BufferedReader::readText) }
3030
val openApiYamlParseResult = OpenAPIV3Parser().readContents(openApiYamlContent)
31-
if (!openApiYamlParseResult.messages.isNullOrEmpty()) {
32-
throw IllegalStateException(
33-
"Unable to parse OpenAPI definition from 'classpath:/static/openapi.yaml' : " +
34-
openApiYamlParseResult.messages
35-
)
31+
32+
check(openApiYamlParseResult.messages.isNullOrEmpty()) {
33+
"Unable to parse OpenAPI definition from 'classpath:/static/openapi.yaml' : " +
34+
openApiYamlParseResult.messages
3635
}
36+
3737
val openAPI =
3838
openApiYamlParseResult.openAPI
3939
?: throw IllegalStateException(

common/src/main/kotlin/com/cosmotech/common/id/CsmIdGenerator.kt

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,8 @@ private const val MIN_HASH_LENGTH = 0
1111
private const val ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789"
1212

1313
fun generateId(scope: String, prependPrefix: String? = null): String {
14-
if (scope.isBlank()) {
15-
throw IllegalArgumentException("scope must not be blank")
16-
}
14+
15+
require(scope.isNotBlank()) { "scope must not be blank" }
1716

1817
// We do not intend to decode generated IDs afterwards => we can safely generate a unique salt.
1918
// This will give us different ids even with equal numbers to encode

common/src/main/kotlin/com/cosmotech/common/metrics/MonitorServiceAspect.kt

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,8 +50,9 @@ class MonitorServiceAspect(
5050
@Pointcut(
5151
"within(@org.springframework.web.bind.annotation.RestController *) && within(com.cosmotech..*Controller)"
5252
)
53-
@Suppress("EmptyFunctionBlock")
54-
fun cosmotechPointcut() {}
53+
fun cosmotechPointcut() {
54+
// Empty function block to define a pointcut
55+
}
5556

5657
@Before("cosmotechPointcut()")
5758
fun monitorBefore(joinPoint: JoinPoint) {

common/src/main/kotlin/com/cosmotech/common/rbac/CsmRbac.kt

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,8 @@ open class CsmRbac(
2929
// Check for duplicate identities
3030
val accessControls = mutableListOf<String>()
3131
objectSecurity.accessControlList.forEach {
32-
if (accessControls.contains(it.id)) {
33-
throw IllegalArgumentException(
34-
"Entity ${it.id} is referenced multiple times in the security"
35-
)
32+
require(!(accessControls.contains(it.id))) {
33+
"Entity ${it.id} is referenced multiple times in the security"
3634
}
3735
accessControls.add(it.id)
3836
}

common/src/main/kotlin/com/cosmotech/common/utils/AnyExtensions.kt

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -79,15 +79,13 @@ inline fun <reified T> T.compareToAndMutateIfNeeded(
7979
if (changed) {
8080
membersChanged.add(member.name)
8181
if (mutateIfChanged) {
82-
if (member !is KMutableProperty) {
83-
throw IllegalArgumentException(
84-
"Detected change but cannot mutate " +
85-
"this object because property ${member.name} " +
86-
"(on class ${T::class}) is not mutable. " +
87-
"Either exclude this field or call this function with " +
88-
"mutateIfChanged=false to view the changes detected"
89-
)
82+
require(member is KMutableProperty) {
83+
"""Detected change but cannot mutate this object
84+
because property ${member.name} (on class ${T::class}) is not mutable.
85+
Either exclude this field or call this function with mutateIfChanged=false
86+
to view the changes detected"""
9087
}
88+
9189
member.setter.call(this, newValue)
9290
}
9391
}

common/src/main/kotlin/com/cosmotech/common/utils/SecurityUtils.kt

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -56,35 +56,34 @@ fun getCurrentAccountIdentifier(configuration: CsmPlatformProperties): String {
5656
}
5757

5858
fun getCurrentAccountGroups(configuration: CsmPlatformProperties): List<String> {
59-
return (getValueFromAuthenticatedToken(configuration) {
59+
return getValueFromAuthenticatedToken(configuration) {
6060
try {
6161
val jwt = JWTParser.parse(it)
6262
jwt.jwtClaimsSet.getStringListClaim(configuration.authorization.groupJwtClaim)
6363
} catch (e: ParseException) {
6464
JSONObjectUtils.parse(it)[configuration.authorization.groupJwtClaim] as List<String>
6565
}
66-
} ?: emptyList())
66+
}
6767
}
6868

6969
fun getCurrentAuthenticatedRoles(configuration: CsmPlatformProperties): List<String> {
70-
return (getValueFromAuthenticatedToken(configuration) {
70+
return getValueFromAuthenticatedToken(configuration) {
7171
try {
7272
val jwt = JWTParser.parse(it)
7373
jwt.jwtClaimsSet.getStringListClaim(configuration.authorization.rolesJwtClaim)
7474
} catch (e: ParseException) {
7575
JSONObjectUtils.parse(it)[configuration.authorization.rolesJwtClaim] as List<String>
7676
}
77-
} ?: emptyList())
77+
}
7878
}
7979

8080
fun <T> getValueFromAuthenticatedToken(
8181
configuration: CsmPlatformProperties,
8282
actionLambda: (String) -> T,
8383
): T {
84-
if (getCurrentAuthentication() == null) {
85-
throw IllegalStateException("User Authentication not found in Security Context")
86-
}
8784
val authentication = getCurrentAuthentication()
85+
checkNotNull(authentication) { "User Authentication not found in Security Context" }
86+
8887
if (authentication is JwtAuthenticationToken) {
8988
return authentication.token.tokenValue.let { actionLambda(it) }
9089
}

dataset/src/main/kotlin/com/cosmotech/dataset/part/services/RelationalDatasetPartManagementService.kt

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ import java.io.BufferedReader
1111
import java.io.ByteArrayOutputStream
1212
import java.io.InputStream
1313
import java.sql.SQLException
14-
import kotlin.use
1514
import org.apache.commons.lang3.StringUtils
1615
import org.postgresql.copy.CopyManager
1716
import org.postgresql.core.BaseConnection
@@ -50,10 +49,8 @@ class RelationalDatasetPartManagementService(
5049

5150
val tableExists = writerJdbcTemplate.existTable(datasetPart.id)
5251

53-
if (tableExists && !overwrite) {
54-
throw IllegalArgumentException(
55-
"Table ${datasetPart.id} already exists and overwrite is set to false."
56-
)
52+
require(!tableExists || overwrite) {
53+
"Table ${datasetPart.id} already exists and overwrite is set to false."
5754
}
5855

5956
inputStream.bufferedReader().use { reader ->

dataset/src/main/kotlin/com/cosmotech/dataset/service/DatasetServiceImpl.kt

Lines changed: 35 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,6 @@ import com.cosmotech.workspace.WorkspaceApiServiceInterface
4444
import com.cosmotech.workspace.service.toGenericSecurity
4545
import java.io.ByteArrayOutputStream
4646
import java.time.Instant
47-
import kotlin.String
48-
import kotlin.use
4947
import org.apache.commons.lang3.StringUtils
5048
import org.postgresql.copy.CopyManager
5149
import org.postgresql.core.BaseConnection
@@ -671,16 +669,18 @@ class DatasetServiceImpl(
671669
val query =
672670
constructQuery(
673671
datasetPartId,
674-
selects,
675-
sums,
676-
avgs,
677-
counts,
678-
mins,
679-
maxs,
680-
offset,
681-
limit,
682-
groupBys,
683-
orderBys,
672+
QueryParams(
673+
selects,
674+
sums,
675+
avgs,
676+
counts,
677+
mins,
678+
maxs,
679+
offset,
680+
limit,
681+
groupBys,
682+
orderBys,
683+
),
684684
)
685685

686686
val outputStream = ByteArrayOutputStream()
@@ -715,28 +715,15 @@ class DatasetServiceImpl(
715715
}
716716
}
717717

718-
@Suppress("LongParameterList")
719-
private fun constructQuery(
720-
datasetPartId: String,
721-
selects: List<String>?,
722-
sums: List<String>?,
723-
avgs: List<String>?,
724-
counts: List<String>?,
725-
mins: List<String>?,
726-
maxs: List<String>?,
727-
offset: Int?,
728-
limit: Int?,
729-
groupBys: List<String>?,
730-
orderBys: List<String>?,
731-
): String {
718+
private fun constructQuery(datasetPartId: String, queryParams: QueryParams): String {
732719
val tableName = "${DATASET_INPUTS_SCHEMA}.${datasetPartId.sanitizeDatasetPartId()}"
733720

734-
val selectClauses = constructClause(selects, null, null)
735-
val sumClauses = constructClause(sums, AggregationType.Sum, "float8")
736-
val avgClauses = constructClause(avgs, AggregationType.Avg, "float8")
737-
val countClauses = constructClause(counts, AggregationType.Count, null)
738-
val minClauses = constructClause(mins, AggregationType.Min, "float8")
739-
val maxClauses = constructClause(maxs, AggregationType.Max, "float8")
721+
val selectClauses = constructClause(queryParams.selects, null, null)
722+
val sumClauses = constructClause(queryParams.sums, AggregationType.Sum, "float8")
723+
val avgClauses = constructClause(queryParams.avgs, AggregationType.Avg, "float8")
724+
val countClauses = constructClause(queryParams.counts, AggregationType.Count, null)
725+
val minClauses = constructClause(queryParams.mins, AggregationType.Min, "float8")
726+
val maxClauses = constructClause(queryParams.maxs, AggregationType.Max, "float8")
740727

741728
val allSelectClauses =
742729
mutableListOf(selectClauses, sumClauses, avgClauses, countClauses, minClauses, maxClauses)
@@ -746,17 +733,17 @@ class DatasetServiceImpl(
746733
val query =
747734
StringBuilder("SELECT %s FROM %s ".format(allSelectClauses.ifBlank { "*" }, tableName))
748735

749-
val groupByClauses = constructClause(groupBys, null, null)
736+
val groupByClauses = constructClause(queryParams.groupBys, null, null)
750737
if (groupByClauses.isNotBlank()) {
751738
query.append("GROUP BY $groupByClauses ")
752739
}
753740

754-
val orderByClauses = constructClause(orderBys, null, null, true)
741+
val orderByClauses = constructClause(queryParams.orderBys, null, null, true)
755742
if (orderByClauses.isNotBlank()) {
756743
query.append("ORDER BY $orderByClauses ")
757744
}
758745

759-
addLimitOffset(limit, offset, query)
746+
addLimitOffset(queryParams.limit, queryParams.offset, query)
760747

761748
logger.debug(query.toString())
762749
return query.toString()
@@ -1139,6 +1126,19 @@ class DatasetServiceImpl(
11391126
}
11401127
}
11411128

1129+
class QueryParams(
1130+
val selects: List<String>?,
1131+
val sums: List<String>?,
1132+
val avgs: List<String>?,
1133+
val counts: List<String>?,
1134+
val mins: List<String>?,
1135+
val maxs: List<String>?,
1136+
val offset: Int?,
1137+
val limit: Int?,
1138+
val groupBys: List<String>?,
1139+
val orderBys: List<String>?,
1140+
)
1141+
11421142
enum class AggregationType {
11431143
Sum,
11441144
Avg,

metrics/src/main/kotlin/com/cosmotech/metrics/MetricsService.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ package com.cosmotech.metrics
44

55
import com.cosmotech.common.metrics.PersistentMetric
66

7-
interface MetricsService {
7+
fun interface MetricsService {
88
/**
99
* Store a metric in the persistent database.
1010
*

0 commit comments

Comments
 (0)