From ff54ca5cdd1e6da0f98fc81845ae4ecfe62b205a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Johnny=20Miller=20=28=E9=94=BA=E4=BF=8A=29?= Date: Fri, 8 May 2020 16:56:16 +0800 Subject: [PATCH] perf($API-Portal): use var and val for local variables Finally! Hassle-free final local variables. https://projectlombok.org/features/val Mutably! Hassle-free local variables. --- .../apiportal/ApiPortalApplication.java | 7 ++-- .../aspect/ExceptionControllerAdvice.java | 12 +++---- .../MethodArgumentValidationAspect.java | 33 ++++++++++--------- .../universal/aspect/WebRequestLogAspect.java | 13 ++++---- .../configuration/DruidConfiguration.java | 6 ++-- .../MyBatisPlusConfiguration.java | 3 +- .../configuration/ProjectProperty.java | 2 -- .../RedisClientConfiguration.java | 5 +-- .../configuration/ServerConfiguration.java | 9 ++--- .../SftpClientConfiguration.java | 8 ++--- .../configuration/SftpSubDirectoryRunner.java | 5 +-- .../configuration/Swagger2Configuration.java | 11 ++++--- .../WebSecurityConfiguration.java | 3 +- .../controller/CommonController.java | 3 +- .../universal/controller/ErrorController.java | 6 ++-- .../filter/JwtAuthenticationFilter.java | 21 ++++++------ .../controller/CommonController.java | 4 +-- 17 files changed, 78 insertions(+), 73 deletions(-) diff --git a/api-portal/src/main/java/com/jmsoftware/apiportal/ApiPortalApplication.java b/api-portal/src/main/java/com/jmsoftware/apiportal/ApiPortalApplication.java index b7c4bd2a..868697a9 100644 --- a/api-portal/src/main/java/com/jmsoftware/apiportal/ApiPortalApplication.java +++ b/api-portal/src/main/java/com/jmsoftware/apiportal/ApiPortalApplication.java @@ -3,6 +3,7 @@ import com.jmsoftware.apiportal.universal.configuration.ProjectProperty; import com.jmsoftware.apiportal.universal.configuration.ServerConfiguration; import lombok.extern.slf4j.Slf4j; +import lombok.val; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; @@ -35,10 +36,10 @@ public ApiPortalApplication(ProjectProperty projectProperty, ServerConfiguration } public static void main(String[] args) { - var startInstant = Instant.now(); + val startInstant = Instant.now(); SpringApplication.run(ApiPortalApplication.class, args); - var endInstant = Instant.now(); - var duration = Duration.between(startInstant, endInstant); + val endInstant = Instant.now(); + val duration = Duration.between(startInstant, endInstant); log.info("🥳 Congratulations! 🎉"); log.info("🖥 {}@{} started!", projectProperty.getProjectArtifactId(), projectProperty.getVersion()); log.info("⚙️ Environment: {} ({})", projectProperty.getEnvironment(), projectProperty.getEnvironmentAlias()); diff --git a/api-portal/src/main/java/com/jmsoftware/apiportal/universal/aspect/ExceptionControllerAdvice.java b/api-portal/src/main/java/com/jmsoftware/apiportal/universal/aspect/ExceptionControllerAdvice.java index 11e1aa62..071ea55b 100644 --- a/api-portal/src/main/java/com/jmsoftware/apiportal/universal/aspect/ExceptionControllerAdvice.java +++ b/api-portal/src/main/java/com/jmsoftware/apiportal/universal/aspect/ExceptionControllerAdvice.java @@ -7,6 +7,7 @@ import com.jmsoftware.common.exception.BaseException; import com.jmsoftware.common.util.RequestUtil; import lombok.extern.slf4j.Slf4j; +import lombok.val; import org.springframework.context.support.DefaultMessageSourceResolvable; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.validation.BindException; @@ -124,18 +125,17 @@ public ResponseBodyBean handleException(HttpServletRequest request, */ private String getFieldErrorMessageFromException(MethodArgumentNotValidException exception) { try { - DefaultMessageSourceResolvable firstErrorField = + val firstErrorField = (DefaultMessageSourceResolvable) Objects.requireNonNull(exception.getBindingResult() .getAllErrors() .get(0) .getArguments())[0]; - String firstErrorFieldName = firstErrorField.getDefaultMessage(); - String firstErrorFieldMessage = exception.getBindingResult().getAllErrors().get(0).getDefaultMessage(); - return firstErrorFieldName + " " + firstErrorFieldMessage; + val firstErrorFieldName = firstErrorField.getDefaultMessage(); + val firstErrorFieldMessage = exception.getBindingResult().getAllErrors().get(0).getDefaultMessage(); + return String.format("%s %s", firstErrorFieldName, firstErrorFieldMessage); } catch (Exception e) { log.error("Exception occurred when get field error message from exception. Exception message: {}", - e.getMessage(), - e); + e.getMessage(), e); return HttpStatus.INVALID_PARAM.getMessage(); } } diff --git a/api-portal/src/main/java/com/jmsoftware/apiportal/universal/aspect/MethodArgumentValidationAspect.java b/api-portal/src/main/java/com/jmsoftware/apiportal/universal/aspect/MethodArgumentValidationAspect.java index 3f24a2cd..1c5d8db7 100644 --- a/api-portal/src/main/java/com/jmsoftware/apiportal/universal/aspect/MethodArgumentValidationAspect.java +++ b/api-portal/src/main/java/com/jmsoftware/apiportal/universal/aspect/MethodArgumentValidationAspect.java @@ -4,6 +4,7 @@ import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.StrUtil; import lombok.extern.slf4j.Slf4j; +import lombok.val; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; @@ -41,9 +42,9 @@ public class MethodArgumentValidationAspect { private final Validator validator; public MethodArgumentValidationAspect() { - var validatorFactory = Validation.buildDefaultValidatorFactory(); + val validatorFactory = Validation.buildDefaultValidatorFactory(); this.validator = validatorFactory.getValidator(); - log.info("Validator for {} has been initiated.", this.getClass().getSimpleName()); + log.info("The validator for {} has been initiated.", this.getClass().getSimpleName()); } /** @@ -83,31 +84,31 @@ public void beforeMethodHandleArgument(JoinPoint joinPoint) { @Around("validateMethodArgumentPointcut()") public Object aroundMethodHandleArgument(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { log.info("======= METHOD'S ARGUMENT VALIDATION START ======="); - var args = proceedingJoinPoint.getArgs(); - var signature = (MethodSignature) proceedingJoinPoint.getSignature(); - var parameterAnnotations = signature.getMethod().getParameterAnnotations(); + val args = proceedingJoinPoint.getArgs(); + val signature = (MethodSignature) proceedingJoinPoint.getSignature(); + val parameterAnnotations = signature.getMethod().getParameterAnnotations(); // argumentIndexes is the array list that stores the index of argument we need to validate (the argument // annotated by `@Valid`) - var argumentIndexListThatNeedsToBeValidated = new LinkedList(); - for (var parameterAnnotation : parameterAnnotations) { - int paramIndex = ArrayUtil.indexOf(parameterAnnotations, parameterAnnotation); - for (var annotation : parameterAnnotation) { + val argumentIndexListThatNeedsToBeValidated = new LinkedList(); + for (val parameterAnnotation : parameterAnnotations) { + val paramIndex = ArrayUtil.indexOf(parameterAnnotations, parameterAnnotation); + for (val annotation : parameterAnnotation) { if (annotation instanceof Valid) { argumentIndexListThatNeedsToBeValidated.add(paramIndex); } } } - var errorMessageList = new LinkedList(); - for (var index : argumentIndexListThatNeedsToBeValidated) { - var constraintViolationSet = validator.validate(args[index]); + val errorMessageList = new LinkedList(); + for (val index : argumentIndexListThatNeedsToBeValidated) { + val constraintViolationSet = validator.validate(args[index]); if (CollUtil.isNotEmpty(constraintViolationSet)) { - var errorMessage = String.format("Argument validation failed: %s", + val errorMessage = String.format("Argument validation failed: %s", getAllFieldErrorMessage(constraintViolationSet)); errorMessageList.add(errorMessage); } } if (CollUtil.isNotEmpty(errorMessageList)) { - var joinedErrorMessage = StrUtil.join(", ", errorMessageList); + val joinedErrorMessage = StrUtil.join(", ", errorMessageList); log.info("Method : {}#{}", proceedingJoinPoint.getSignature().getDeclaringTypeName(), proceedingJoinPoint.getSignature().getName()); log.info("Argument : {}", args); @@ -149,8 +150,8 @@ public void afterThrowingException(JoinPoint joinPoint, Exception e) { * @return the all field error message */ private String getAllFieldErrorMessage(Set> constraintViolationSet) { - var allErrorMessageList = new LinkedList(); - for (var constraintViolation : constraintViolationSet) { + val allErrorMessageList = new LinkedList(); + for (val constraintViolation : constraintViolationSet) { allErrorMessageList.add(String.format("invalid field: %s, %s", constraintViolation.getPropertyPath(), constraintViolation.getMessage())); } diff --git a/api-portal/src/main/java/com/jmsoftware/apiportal/universal/aspect/WebRequestLogAspect.java b/api-portal/src/main/java/com/jmsoftware/apiportal/universal/aspect/WebRequestLogAspect.java index 0bab8beb..3ae1c4cb 100644 --- a/api-portal/src/main/java/com/jmsoftware/apiportal/universal/aspect/WebRequestLogAspect.java +++ b/api-portal/src/main/java/com/jmsoftware/apiportal/universal/aspect/WebRequestLogAspect.java @@ -7,6 +7,7 @@ import com.jmsoftware.common.util.RequestUtil; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import lombok.val; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; @@ -14,8 +15,6 @@ import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; -import javax.servlet.http.HttpServletRequest; - /** *

RequestLogAspect

*

Description:

@@ -61,9 +60,9 @@ public void requestLogPointcut() { */ @Before("requestLogPointcut()") public void beforeHandleRequest(JoinPoint joinPoint) { - ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + val attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); assert attributes != null; - HttpServletRequest request = attributes.getRequest(); + val request = attributes.getRequest(); log.info("============ WEB REQUEST LOG START ============"); log.info("URL : {}", request.getRequestURL().toString()); log.info("HTTP Method : {}", request.getMethod()); @@ -84,9 +83,9 @@ public void beforeHandleRequest(JoinPoint joinPoint) { */ @Around("requestLogPointcut()") public Object aroundHandleRequest(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { - long startTime = System.currentTimeMillis(); - Object result = proceedingJoinPoint.proceed(); - long elapsedTime = System.currentTimeMillis() - startTime; + val startTime = System.currentTimeMillis(); + val result = proceedingJoinPoint.proceed(); + val elapsedTime = System.currentTimeMillis() - startTime; try { var formattedStringifiedJson = JSONUtil.formatJsonStr(mapper.writeValueAsString(result)); if (formattedStringifiedJson.length() > 500) { diff --git a/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/DruidConfiguration.java b/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/DruidConfiguration.java index bd282057..6e518690 100644 --- a/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/DruidConfiguration.java +++ b/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/DruidConfiguration.java @@ -4,6 +4,7 @@ import com.alibaba.druid.support.http.StatViewServlet; import com.alibaba.druid.support.http.WebStatFilter; import lombok.RequiredArgsConstructor; +import lombok.val; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean; @@ -26,8 +27,7 @@ public class DruidConfiguration { @Bean public ServletRegistrationBean druidServlet() { - ServletRegistrationBean servletRegistrationBean = - new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*"); + val servletRegistrationBean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*"); servletRegistrationBean.addInitParameter("loginUsername", "admin"); servletRegistrationBean.addInitParameter("loginPassword", "admin"); servletRegistrationBean.addInitParameter("resetEnable", "false"); @@ -36,7 +36,7 @@ public ServletRegistrationBean druidServlet() { @Bean public FilterRegistrationBean filterRegistrationBean() { - FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean<>(); + val filterRegistrationBean = new FilterRegistrationBean(); filterRegistrationBean.setFilter(new WebStatFilter()); filterRegistrationBean.addUrlPatterns("/*"); // Ignored resources diff --git a/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/MyBatisPlusConfiguration.java b/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/MyBatisPlusConfiguration.java index 2a3cc369..5cde06b5 100644 --- a/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/MyBatisPlusConfiguration.java +++ b/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/MyBatisPlusConfiguration.java @@ -2,6 +2,7 @@ import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize; +import lombok.val; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.transaction.annotation.EnableTransactionManagement; @@ -24,7 +25,7 @@ public class MyBatisPlusConfiguration { */ @Bean public PaginationInterceptor paginationInterceptor() { - var paginationInterceptor = new PaginationInterceptor(); + val paginationInterceptor = new PaginationInterceptor(); // Set maximum query record count paginationInterceptor.setLimit(100L); // Enable JSQL Parser Count Optimizing (for left join) diff --git a/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/ProjectProperty.java b/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/ProjectProperty.java index 3d4817d4..18d39520 100644 --- a/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/ProjectProperty.java +++ b/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/ProjectProperty.java @@ -1,7 +1,6 @@ package com.jmsoftware.apiportal.universal.configuration; import lombok.Data; -import lombok.extern.slf4j.Slf4j; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @@ -13,7 +12,6 @@ * @author Johnny Miller (鍾俊), email: johnnysviva@outlook.com * @date 2019-04-18 13:01 **/ -@Slf4j @Data @Component @ConfigurationProperties(prefix = "project.property") diff --git a/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/RedisClientConfiguration.java b/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/RedisClientConfiguration.java index deefec63..a6a0cbde 100644 --- a/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/RedisClientConfiguration.java +++ b/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/RedisClientConfiguration.java @@ -1,5 +1,6 @@ package com.jmsoftware.apiportal.universal.configuration; +import lombok.val; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; import org.springframework.cache.annotation.CachingConfigurerSupport; @@ -22,15 +23,15 @@ * @date 5/2/20 11:41 PM **/ @Configuration -@AutoConfigureAfter(RedisAutoConfiguration.class) @EnableCaching +@AutoConfigureAfter(RedisAutoConfiguration.class) public class RedisClientConfiguration extends CachingConfigurerSupport { /** * Redis template. Support for <String, Serializable> */ @Bean public RedisTemplate redisFactory(LettuceConnectionFactory lettuceConnectionFactory) { - RedisTemplate template = new RedisTemplate<>(); + val template = new RedisTemplate(); template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); template.setConnectionFactory(lettuceConnectionFactory); diff --git a/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/ServerConfiguration.java b/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/ServerConfiguration.java index 4d5290ab..f6379304 100644 --- a/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/ServerConfiguration.java +++ b/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/ServerConfiguration.java @@ -3,6 +3,7 @@ import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import lombok.val; import org.springframework.boot.web.context.WebServerInitializedEvent; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; @@ -64,8 +65,8 @@ public String getPublicIp() { } try { // An API provided by https://whatismyipaddress.com/api - URL url = new URL("https://ipv4bot.whatismyipaddress.com/"); - BufferedReader sc = new BufferedReader(new InputStreamReader(url.openStream())); + val url = new URL("https://ipv4bot.whatismyipaddress.com/"); + val sc = new BufferedReader(new InputStreamReader(url.openStream())); // Read system IP Address return sc.readLine().trim(); } catch (Exception e) { @@ -80,9 +81,9 @@ public String getPublicIp() { * @return internet IP */ private String getInternetIp() { - String intranetIp = this.getIntranetIp(); + val intranetIp = this.getIntranetIp(); try { - Enumeration networks = NetworkInterface.getNetworkInterfaces(); + val networks = NetworkInterface.getNetworkInterfaces(); InetAddress ip; Enumeration addresses; while (networks.hasMoreElements()) { diff --git a/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/SftpClientConfiguration.java b/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/SftpClientConfiguration.java index 3216a6f2..68e044db 100644 --- a/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/SftpClientConfiguration.java +++ b/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/SftpClientConfiguration.java @@ -3,6 +3,7 @@ import com.jcraft.jsch.ChannelSftp; import lombok.Data; import lombok.extern.slf4j.Slf4j; +import lombok.val; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.core.io.Resource; @@ -69,7 +70,7 @@ public class SftpClientConfiguration { @Bean public SessionFactory sftpSessionFactory() { - DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory(true); + val factory = new DefaultSftpSessionFactory(true); factory.setHost(host); factory.setPort(port); factory.setUser(user); @@ -81,8 +82,7 @@ public SessionFactory sftpSessionFactory() { } factory.setAllowUnknownKeys(true); // We return a caching session factory, so that we don't have to reconnect to SFTP server for each time - CachingSessionFactory cachingSessionFactory = new CachingSessionFactory<>(factory, - sessionCacheSize); + val cachingSessionFactory = new CachingSessionFactory<>(factory, sessionCacheSize); cachingSessionFactory.setSessionWaitTimeout(sessionWaitTimeout); return cachingSessionFactory; } @@ -91,7 +91,7 @@ public SessionFactory sftpSessionFactory() { @ServiceActivator(inputChannel = "toSftpChannel") @SuppressWarnings("UnresolvedMessageChannel") public MessageHandler handler(SessionFactory sftpSessionFactory) { - SftpMessageHandler handler = new SftpMessageHandler(sftpSessionFactory); + val handler = new SftpMessageHandler(sftpSessionFactory); handler.setRemoteDirectoryExpression(new LiteralExpression(directory)); handler.setFileNameGenerator(message -> { if (message.getPayload() instanceof File) { diff --git a/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/SftpSubDirectoryRunner.java b/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/SftpSubDirectoryRunner.java index f51eae75..d9fc8778 100644 --- a/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/SftpSubDirectoryRunner.java +++ b/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/SftpSubDirectoryRunner.java @@ -3,6 +3,7 @@ import com.jmsoftware.apiportal.universal.domain.SftpSubDirectory; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import lombok.val; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.integration.sftp.session.SftpRemoteFileTemplate; @@ -39,8 +40,8 @@ public void run(ApplicationArguments args) { log.info("Staring to initial SFTP server sub directory."); sftpRemoteFileTemplate.execute(session -> { - for (SftpSubDirectory sftpSubDirectory : SftpSubDirectory.values()) { - String fullPath = sftpClientConfiguration.getDirectory() + sftpSubDirectory.getSubDirectory(); + for (val sftpSubDirectory : SftpSubDirectory.values()) { + val fullPath = sftpClientConfiguration.getDirectory() + sftpSubDirectory.getSubDirectory(); if (!session.exists(fullPath)) { log.info("SFTP server sub directory does not exist. Creating sub directory: {}", fullPath); session.mkdir(fullPath); diff --git a/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/Swagger2Configuration.java b/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/Swagger2Configuration.java index 2ae23c29..1fcd4dc2 100644 --- a/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/Swagger2Configuration.java +++ b/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/Swagger2Configuration.java @@ -1,6 +1,7 @@ package com.jmsoftware.apiportal.universal.configuration; import lombok.RequiredArgsConstructor; +import lombok.val; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; @@ -39,11 +40,11 @@ public Docket createRestApi() { } private ApiInfo apiInfo() { - var projectArtifactId = projectProperty.getProjectArtifactId(); - var version = projectProperty.getVersion(); - var developerEmail = projectProperty.getDeveloperEmail(); - var developerUrl = projectProperty.getDeveloperUrl(); - var environmentAlias = projectProperty.getEnvironmentAlias(); + val projectArtifactId = projectProperty.getProjectArtifactId(); + val version = projectProperty.getVersion(); + val developerEmail = projectProperty.getDeveloperEmail(); + val developerUrl = projectProperty.getDeveloperUrl(); + val environmentAlias = projectProperty.getEnvironmentAlias(); return new ApiInfoBuilder() .title(String.format("API for %s@%s (%s)", projectArtifactId, diff --git a/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/WebSecurityConfiguration.java b/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/WebSecurityConfiguration.java index 5784ba92..0fc8304c 100644 --- a/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/WebSecurityConfiguration.java +++ b/api-portal/src/main/java/com/jmsoftware/apiportal/universal/configuration/WebSecurityConfiguration.java @@ -4,6 +4,7 @@ import com.jmsoftware.apiportal.universal.service.impl.CustomUserDetailsServiceImpl; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import lombok.val; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; @@ -95,7 +96,7 @@ protected void configure(HttpSecurity http) throws Exception { */ @Override public void configure(WebSecurity web) { - WebSecurity and = web.ignoring().and(); + val and = web.ignoring().and(); Optional.ofNullable(customConfiguration.getIgnoredRequest()) .ifPresentOrElse((ignoredRequest -> { ignoredRequest.getGet().forEach(url -> and.ignoring().antMatchers(HttpMethod.GET, url)); diff --git a/api-portal/src/main/java/com/jmsoftware/apiportal/universal/controller/CommonController.java b/api-portal/src/main/java/com/jmsoftware/apiportal/universal/controller/CommonController.java index 04cb7512..a1e0b001 100644 --- a/api-portal/src/main/java/com/jmsoftware/apiportal/universal/controller/CommonController.java +++ b/api-portal/src/main/java/com/jmsoftware/apiportal/universal/controller/CommonController.java @@ -6,6 +6,7 @@ import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.RequiredArgsConstructor; +import lombok.val; import org.springframework.web.bind.annotation.*; import java.util.Map; @@ -28,7 +29,7 @@ public class CommonController { @GetMapping("/app-info") @ApiOperation(value = "/app-info", notes = "Retrieve application information") public ResponseBodyBean> applicationInformation() { - var data = commonService.getApplicationInfo(); + val data = commonService.getApplicationInfo(); return ResponseBodyBean.ofSuccess(data, "Succeed to retrieve app info."); } diff --git a/api-portal/src/main/java/com/jmsoftware/apiportal/universal/controller/ErrorController.java b/api-portal/src/main/java/com/jmsoftware/apiportal/universal/controller/ErrorController.java index 15d9c174..f834374c 100644 --- a/api-portal/src/main/java/com/jmsoftware/apiportal/universal/controller/ErrorController.java +++ b/api-portal/src/main/java/com/jmsoftware/apiportal/universal/controller/ErrorController.java @@ -2,11 +2,11 @@ import io.swagger.annotations.Api; import lombok.extern.slf4j.Slf4j; +import lombok.val; import org.springframework.boot.autoconfigure.web.ServerProperties; import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController; import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver; import org.springframework.boot.web.servlet.error.ErrorAttributes; -import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RestController; @@ -35,8 +35,8 @@ public ErrorController(ErrorAttributes errorAttributes, @Override public ResponseEntity> error(HttpServletRequest request) { - HttpStatus httpStatus = getStatus(request); - Map body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL)); + val httpStatus = getStatus(request); + val body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL)); body.put("message", httpStatus.getReasonPhrase()); log.error("Captured HTTP request error. Response body = {}", body); return new ResponseEntity<>(body, httpStatus); diff --git a/api-portal/src/main/java/com/jmsoftware/apiportal/universal/filter/JwtAuthenticationFilter.java b/api-portal/src/main/java/com/jmsoftware/apiportal/universal/filter/JwtAuthenticationFilter.java index cc6356fb..c142856d 100644 --- a/api-portal/src/main/java/com/jmsoftware/apiportal/universal/filter/JwtAuthenticationFilter.java +++ b/api-portal/src/main/java/com/jmsoftware/apiportal/universal/filter/JwtAuthenticationFilter.java @@ -3,7 +3,6 @@ import cn.hutool.core.collection.CollUtil; import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; -import com.google.common.collect.Sets; import com.jmsoftware.apiportal.universal.configuration.CustomConfiguration; import com.jmsoftware.apiportal.universal.service.impl.CustomUserDetailsServiceImpl; import com.jmsoftware.apiportal.universal.service.impl.JwtServiceImpl; @@ -13,6 +12,7 @@ import com.jmsoftware.common.util.ResponseUtil; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import lombok.val; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; @@ -28,8 +28,8 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; +import java.util.HashSet; import java.util.Optional; -import java.util.Set; /** *

JwtAuthenticationFilter

@@ -62,7 +62,7 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse filterChain.doFilter(request, response); return; } - String jwt = jwtServiceImpl.getJwtFromRequest(request); + val jwt = jwtServiceImpl.getJwtFromRequest(request); if (StrUtil.isBlank(jwt)) { log.error("Invalid JWT, the JWT of request is empty."); ResponseUtil.renderJson(response, HttpStatus.UNAUTHORIZED, null); @@ -86,8 +86,7 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse ResponseUtil.renderJson(response, HttpStatus.UNAUTHORIZED, null); return; } - UsernamePasswordAuthenticationToken authentication = - new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); + val authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); log.info("JWT authentication passed! Authentication: {}", authentication); SecurityContextHolder.getContext().setAuthentication(authentication); @@ -101,13 +100,13 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse * @return true - Ignored, false - Not ignored */ private boolean checkIgnores(HttpServletRequest request) { - String method = request.getMethod(); - HttpMethod httpMethod = HttpMethod.resolve(method); + val method = request.getMethod(); + var httpMethod = HttpMethod.resolve(method); if (ObjectUtil.isNull(httpMethod)) { httpMethod = HttpMethod.GET; } - Set ignoredRequestSet = Sets.newHashSet(); - HttpMethod finalHttpMethod = httpMethod; + val ignoredRequestSet = new HashSet(); + val finalHttpMethod = httpMethod; Optional.ofNullable(customConfiguration.getIgnoredRequest()) .ifPresentOrElse((ignoredRequest -> { ignoredRequestSet.addAll(ignoredRequest.getPattern()); @@ -142,8 +141,8 @@ private boolean checkIgnores(HttpServletRequest request) { }), () -> log.warn("Security warning: Ignored request is empty! The ignored request configuration " + "might be invalid!")); if (CollUtil.isNotEmpty(ignoredRequestSet)) { - for (String ignore : ignoredRequestSet) { - AntPathRequestMatcher matcher = new AntPathRequestMatcher(ignore, method); + for (val ignore : ignoredRequestSet) { + val matcher = new AntPathRequestMatcher(ignore, method); if (matcher.matches(request)) { return true; } diff --git a/muscle-mis/src/main/java/com/jmsoftware/exercisemis/universal/controller/CommonController.java b/muscle-mis/src/main/java/com/jmsoftware/exercisemis/universal/controller/CommonController.java index 3fb3741c..203a100b 100644 --- a/muscle-mis/src/main/java/com/jmsoftware/exercisemis/universal/controller/CommonController.java +++ b/muscle-mis/src/main/java/com/jmsoftware/exercisemis/universal/controller/CommonController.java @@ -29,13 +29,13 @@ public class CommonController { @ApiOperation(value = "/app-info", notes = "Retrieve application information") public ResponseBodyBean> applicationInformation() { var data = commonService.getApplicationInfo(); - return ResponseBodyBean.ofDataAndMessage(data, "Succeed to retrieve app info."); + return ResponseBodyBean.ofSuccess(data, "Succeed to retrieve app info."); } @PostMapping("/validation-test") @ApiOperation(value = "/validation-test", notes = "Validation of request payload test") public ResponseBodyBean validationTest(@RequestBody ValidationTestPayload payload) { commonService.validateObject(payload); - return ResponseBodyBean.ofDataAndMessage(payload.getName(), "validationTest()"); + return ResponseBodyBean.ofSuccess(payload.getName(), "validationTest()"); } }