Skip to content

Commit

Permalink
fix: correct annotations for Spring Validation
Browse files Browse the repository at this point in the history
2022-04-17 22:45:12.564 ERROR [auth-center,84c36bf256e4a45e,3f2acdd760061cb6] 1 - [nio-8800-exec-6] c.j.m.s.aspect.CommonExceptionControllerAdvice : Internal server exception occurred! Exception message: HV000151: A method overriding another method must not redefine the parameter constraint configuration, but method JwtServiceImpl#createJwt(boolean, long, String, List, Collection) redefines the configuration of JwtService#createJwt(boolean, long, String, List, Collection).
javax.validation.ConstraintDeclarationException: HV000151: A method overriding another method must not redefine the parameter constraint configuration, but method JwtServiceImpl#createJwt(boolean, long, String, List, Collection) redefines the configuration of JwtService#createJwt(boolean, long, String, List, Collection).
  • Loading branch information
johnnymillergh committed Apr 18, 2022
1 parent cc2767b commit 5f0c38a
Show file tree
Hide file tree
Showing 45 changed files with 122 additions and 461 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,6 @@ import com.jmsoftware.maf.common.domain.authcenter.security.ParseJwtResponse
import com.jmsoftware.maf.common.domain.authcenter.user.GetUserByLoginTokenResponse
import org.springframework.stereotype.Service
import reactor.core.publisher.Mono
import javax.validation.Valid
import javax.validation.constraints.Min
import javax.validation.constraints.NotBlank
import javax.validation.constraints.NotNull

/**
* # AuthCenterWebClientServiceImpl
Expand All @@ -25,14 +21,14 @@ import javax.validation.constraints.NotNull
class AuthCenterWebClientServiceImpl(
private val authCenterWebClient: AuthCenterWebClient
) : AuthCenterWebClientService {
override fun getUserByLoginToken(loginToken: @NotBlank String): Mono<GetUserByLoginTokenResponse> =
override fun getUserByLoginToken(loginToken: String): Mono<GetUserByLoginTokenResponse> =
authCenterWebClient.getUserByLoginToken(loginToken)

override fun getRoleListByUserId(userId: @NotNull @Min(1L) Long): Mono<List<GetRoleListByUserIdSingleResponse>> =
override fun getRoleListByUserId(userId: Long): Mono<List<GetRoleListByUserIdSingleResponse>> =
authCenterWebClient.getRoleListByUserId(userId)

override fun getPermissionListByRoleIdList(
payload: @Valid @NotNull GetPermissionListByRoleIdListPayload
payload: GetPermissionListByRoleIdListPayload
): Mono<List<Permission>> = authCenterWebClient.getPermissionListByRoleIdList(payload)

override fun parse(authorization: String): Mono<ParseJwtResponse> = authCenterWebClient.parse(authorization)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,11 @@ import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration

/**
* <h1>OpenApiConfiguration</h1>
*
* # OpenApiConfiguration
*
* Change description here.
*
* @author Johnny Miller (鍾俊), email: johnnysviva@outlook.com, 2/1/22 11:51 PM
* @author Johnny Miller (锺俊), e-mail: johnnysviva@outlook.com, date: 4/18/22 9:18 PM
*/
@Configuration
class OpenApiConfiguration(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ import org.springframework.validation.annotation.Validated
import javax.validation.constraints.NotEmpty

/**
* <h1>SwaggerConfigurationProperties</h1>
* # SwaggerConfigurationProperties
*
* @author Johnny Miller (锺俊), email: johnnysviva@outlook.com, date: 2/7/2021 3:28 PM
* @author Johnny Miller (锺俊), e-mail: johnnysviva@outlook.com, date: 4/18/22 9:17 PM
*/
@Validated
@RefreshScope
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@ import org.springframework.cloud.client.discovery.DiscoveryClient
import org.springframework.stereotype.Service
import org.springframework.web.client.RestTemplate
import java.util.*
import javax.validation.Valid
import javax.validation.constraints.NotNull

/**
* # PermissionServiceImpl
Expand All @@ -49,7 +47,7 @@ class PermissionServiceImpl(
}

override fun getPermissionListByRoleIdList(
payload: @Valid @NotNull GetPermissionListByRoleIdListPayload
payload: GetPermissionListByRoleIdListPayload
): GetPermissionListByRoleIdListResponse {
val adminRole = roleDomainService.checkAdmin(payload.roleIdList)
val response = GetPermissionListByRoleIdListResponse()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import com.jmsoftware.maf.authcenter.permission.persistence.Permission
import com.jmsoftware.maf.authcenter.permission.service.PermissionDomainService
import com.jmsoftware.maf.common.domain.authcenter.permission.PermissionType
import org.springframework.stereotype.Service
import javax.validation.constraints.NotEmpty

/**
* # PermissionDomainServiceImpl
Expand All @@ -19,8 +18,8 @@ import javax.validation.constraints.NotEmpty
class PermissionDomainServiceImpl
: ServiceImpl<PermissionMapper, Permission>(), PermissionDomainService {
override fun getPermissionListByRoleIdList(
roleIdList: @NotEmpty List<Long>,
permissionTypeList: @NotEmpty List<PermissionType>
roleIdList: List<Long>,
permissionTypeList: List<PermissionType>
): List<Permission> {
return getBaseMapper().selectPermissionListByRoleIdList(roleIdList, permissionTypeList)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import com.jmsoftware.maf.common.util.logger
import org.springframework.stereotype.Service
import org.springframework.web.multipart.MultipartFile
import java.util.*
import javax.validation.constraints.NotNull

/**
* # OssCenterFeignServiceImpl
Expand All @@ -25,8 +24,8 @@ class OssCenterFeignServiceImpl(
private val log = logger()
}

override fun uploadSingleResource(multipartFile: @NotNull MultipartFile): ObjectResponse {
log.info("Uploading single resource to oss center. multipartFile: {}", multipartFile)
override fun uploadSingleResource(multipartFile: MultipartFile): ObjectResponse {
log.info("Uploading single resource to oss center. multipartFile: $multipartFile")
return Optional.ofNullable(ossCenterFeignClient.uploadSingleResource(multipartFile))
.map { response -> response.data!! }
.orElseThrow {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@ import org.springframework.data.redis.core.RedisTemplate
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.util.concurrent.TimeUnit
import javax.validation.constraints.NotEmpty
import javax.validation.constraints.NotNull

/**
* # RoleDomainServiceImpl
Expand All @@ -46,7 +44,7 @@ class RoleDomainServiceImpl(
private val logger = logger()
}

override fun getRoleList(userId: @NotNull Long): GetRoleListByUserIdResponse {
override fun getRoleList(userId: Long): GetRoleListByUserIdResponse {
val key = "${mafProjectProperties.projectParentArtifactId}${GET_ROLE_LIST_BY_USER_ID.keyInfixFormat}$userId"
val hadKey = redisTemplate.hasKey(key)
if (hadKey) {
Expand All @@ -63,7 +61,7 @@ class RoleDomainServiceImpl(
return getBaseMapper().selectRoleListByUserId(userId)
}

override fun checkAdmin(roleIdList: @NotEmpty List<Long>): Boolean {
override fun checkAdmin(roleIdList: List<Long>): Boolean {
// If roleNameSet is not empty (contains "admin")
return this.ktQuery()
.select(Role::name)
Expand Down Expand Up @@ -96,7 +94,7 @@ class RoleDomainServiceImpl(
}

@Transactional(rollbackFor = [Throwable::class])
override fun save(beanList: @NotEmpty List<RoleExcelBean>) {
override fun save(beanList: List<RoleExcelBean>) {
val roleList = beanList
.stream()
.map { roleExcelBean: RoleExcelBean -> RoleExcelBean.transformTo(roleExcelBean) }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@ import java.util.concurrent.TimeUnit
import javax.annotation.PostConstruct
import javax.crypto.SecretKey
import javax.servlet.http.HttpServletRequest
import javax.validation.constraints.NotBlank
import javax.validation.constraints.NotNull

/**
* # JwtServiceImpl
Expand Down Expand Up @@ -55,7 +53,7 @@ class JwtServiceImpl(
log.warn("Secret key for JWT parser was generated. Algorithm: ${secretKey.algorithm}")
}

override fun createJwt(@NotNull authentication: Authentication, @NotNull rememberMe: Boolean): String {
override fun createJwt(authentication: Authentication, rememberMe: Boolean): String {
val userPrincipal = authentication.principal as UserPrincipal
return this.createJwt(
rememberMe,
Expand All @@ -67,9 +65,9 @@ class JwtServiceImpl(
}

override fun createJwt(
@NotNull rememberMe: Boolean,
@NotNull id: Long,
@NotNull subject: String,
rememberMe: Boolean,
id: Long,
subject: String,
roles: List<String>,
authorities: Collection<GrantedAuthority>
): String {
Expand All @@ -95,7 +93,7 @@ class JwtServiceImpl(
return jwt
}

override fun parseJwt(@NotBlank jwt: String): Claims {
override fun parseJwt(jwt: String): Claims {
val claims: Claims = try {
Optional.ofNullable(jwtParser.parseClaimsJws(jwt).body)
.orElseThrow {
Expand Down Expand Up @@ -131,7 +129,7 @@ class JwtServiceImpl(
return claims
}

override fun invalidateJwt(@NotNull request: HttpServletRequest) {
override fun invalidateJwt(request: HttpServletRequest) {
val jwt = getJwtFromRequest(request)
val username = getUsernameFromJwt(jwt)
// Delete JWT from redis
Expand All @@ -140,17 +138,17 @@ class JwtServiceImpl(
log.error("Invalidate JWT. Redis key of JWT = $redisKeyOfJwt, deleted = $deletedKeyNumber")
}

override fun getUsernameFromJwt(@NotBlank jwt: String): String {
override fun getUsernameFromJwt(jwt: String): String {
val claims = parseJwt(jwt)
return claims.subject
}

override fun getUsernameFromRequest(@NotNull request: HttpServletRequest): String {
override fun getUsernameFromRequest(request: HttpServletRequest): String {
val jwt = getJwtFromRequest(request)
return getUsernameFromJwt(jwt)
}

override fun getJwtFromRequest(@NotNull request: HttpServletRequest): String {
override fun getJwtFromRequest(request: HttpServletRequest): String {
val bearerToken = request.getHeader(HttpHeaders.AUTHORIZATION)
return if (CharSequenceUtil.isNotBlank(bearerToken)
&& bearerToken.startsWith(JwtConfigurationProperties.TOKEN_PREFIX)
Expand All @@ -159,7 +157,7 @@ class JwtServiceImpl(
} else null.toString()
}

override fun parse(@NotNull request: HttpServletRequest): ParseJwtResponse {
override fun parse(request: HttpServletRequest): ParseJwtResponse {
val jwt = getJwtFromRequest(request)
val claims = parseJwt(jwt)
val parseJwtResponse = ParseJwtResponse()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import com.jmsoftware.maf.authcenter.user.service.UserDomainService
import com.jmsoftware.maf.authcenter.user.service.UserRoleDomainService
import com.jmsoftware.maf.common.bean.PageResponseBodyBean
import com.jmsoftware.maf.common.domain.authcenter.user.*
import com.jmsoftware.maf.common.enumeration.ValueDescriptionBaseEnum
import com.jmsoftware.maf.common.exception.SecurityException
import com.jmsoftware.maf.common.util.logger
import com.jmsoftware.maf.springcloudstarter.property.MafConfigurationProperties
Expand All @@ -37,9 +36,6 @@ import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.util.concurrent.TimeUnit
import javax.servlet.http.HttpServletRequest
import javax.validation.Valid
import javax.validation.constraints.NotBlank
import javax.validation.constraints.NotNull

/**
* # UserDomainServiceImpl
Expand All @@ -63,7 +59,7 @@ class UserDomainServiceImpl(
private val logger = logger()
}

override fun getUserByLoginToken(loginToken: @NotBlank String): GetUserByLoginTokenResponse? {
override fun getUserByLoginToken(loginToken: String): GetUserByLoginTokenResponse? {
val key =
"${mafProjectProperties.projectParentArtifactId}${UserRedisKey.GET_USER_BY_LOGIN_TOKEN.keyInfixFormat}$loginToken"
val hasKey = redisTemplate.hasKey(key)
Expand All @@ -80,7 +76,7 @@ class UserDomainServiceImpl(
}

@Transactional(rollbackFor = [Throwable::class])
override fun saveUserForSignup(payload: @Valid SignupPayload): SignupResponse {
override fun saveUserForSignup(payload: SignupPayload): SignupResponse {
val user = User()
user.username = payload.username
user.email = payload.email
Expand All @@ -94,7 +90,7 @@ class UserDomainServiceImpl(
return response
}

override fun login(payload: @Valid LoginPayload): LoginResponse {
override fun login(payload: LoginPayload): LoginResponse {
val user = getUserByLoginToken(payload.loginToken) ?: throw SecurityException(HttpStatus.UNAUTHORIZED)
logger.info("User login: $user")
val matched = bCryptPasswordEncoder.matches(payload.password, user.password)
Expand All @@ -117,12 +113,12 @@ class UserDomainServiceImpl(
return true
}

override fun getUserStatus(payload: @Valid @NotNull GetUserStatusPayload): String {
override fun getUserStatus(payload: GetUserStatusPayload): String {
logger.info("Current username: {}", currentUsername())
return ValueDescriptionBaseEnum.getDescriptionByValue(UserStatus::class.java, payload.status)
return payload.status.toString()
}

override fun getUserPageList(payload: @Valid @NotNull GetUserPageListPayload): PageResponseBodyBean<User> {
override fun getUserPageList(payload: GetUserPageListPayload): PageResponseBodyBean<User> {
logger.info("{}", payload)
val page = Page<User>(
payload.currentPage.toLong(), payload.pageSize.toLong()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import com.jmsoftware.maf.authcenter.user.persistence.User
import com.jmsoftware.maf.authcenter.user.service.UserRoleDomainService
import com.jmsoftware.maf.common.domain.authcenter.user.LoginPayload
import com.jmsoftware.maf.common.domain.authcenter.user.SignupPayload
import com.jmsoftware.maf.common.domain.authcenter.user.UserStatus
import com.jmsoftware.maf.common.exception.SecurityException
import com.jmsoftware.maf.common.util.logger
import com.jmsoftware.maf.springcloudstarter.property.MafConfigurationProperties
Expand Down Expand Up @@ -149,8 +150,7 @@ internal class UserDomainServiceImplTest {
@Test
fun getUserStatus() {
val payload = GetUserStatusPayload()
payload.status = 1.toByte()
payload.status2 = 0.toByte()
payload.status = UserStatus.ENABLED
val thrownException =
assertThrows(IllegalStateException::class.java) { userDomainService.getUserStatus(payload) }
log.warn("Thrown exception: ${thrownException.message}")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ interface OssCenterFeignClient {
private val log = logger()
}

override fun uploadSingleResource(multipartFile: @NotNull MultipartFile): ResponseBodyBean<ObjectResponse> {
override fun uploadSingleResource(multipartFile: MultipartFile): ResponseBodyBean<ObjectResponse> {
log.error("Fallback -> OssCenterFeignClient#uploadSingleResource()")
return ResponseBodyBean.ofFailureMessage("Fell back uploading single resource")
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package com.jmsoftware.maf.authcenter.user.payload

import com.jmsoftware.maf.common.bean.PaginationBase
import com.jmsoftware.maf.springcloudstarter.validation.annotation.DateTimeRangeGroup
import com.jmsoftware.maf.springcloudstarter.validation.annotation.DateTimeRangeType
import java.time.LocalDateTime

/**
Expand All @@ -15,9 +13,7 @@ import java.time.LocalDateTime
class GetUserPageListPayload : PaginationBase() {
var username: String? = null

@DateTimeRangeGroup(type = DateTimeRangeType.START_TIME)
val startTime: LocalDateTime? = null
var startTime: LocalDateTime? = null

@DateTimeRangeGroup(type = DateTimeRangeType.END_TIME)
val endTime: LocalDateTime? = null
var endTime: LocalDateTime? = null
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
package com.jmsoftware.maf.authcenter.user.payload

import com.jmsoftware.maf.common.domain.authcenter.user.UserStatus
import com.jmsoftware.maf.common.domain.authcenter.user.UserStatus2
import com.jmsoftware.maf.springcloudstarter.validation.annotation.ValidEnumValue
import javax.validation.constraints.NotNull

/**
* # GetUserStatusPayload
Expand All @@ -12,9 +11,6 @@ import com.jmsoftware.maf.springcloudstarter.validation.annotation.ValidEnumValu
* @author Johnny Miller (锺俊), e-mail: johnnysviva@outlook.com, date: 4/12/22 12:50 PM
*/
class GetUserStatusPayload {
@ValidEnumValue(targetEnum = UserStatus::class)
var status: Byte? = null

@ValidEnumValue(targetEnum = UserStatus2::class)
var status2: Byte? = null
@NotNull
lateinit var status: UserStatus
}
Loading

0 comments on commit 5f0c38a

Please sign in to comment.