Skip to content

Commit

Permalink
perf($API-Portal): use var and val for local variables
Browse files Browse the repository at this point in the history
Finally! Hassle-free final local variables.
https://projectlombok.org/features/val

Mutably! Hassle-free local variables.
  • Loading branch information
johnnymillergh committed May 8, 2020
1 parent 0c3c94b commit ff54ca5
Show file tree
Hide file tree
Showing 17 changed files with 78 additions and 73 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -124,18 +125,17 @@ public ResponseBodyBean<Object> 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();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.*;
Expand Down Expand Up @@ -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());
}

/**
Expand Down Expand Up @@ -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<Integer>();
for (var parameterAnnotation : parameterAnnotations) {
int paramIndex = ArrayUtil.indexOf(parameterAnnotations, parameterAnnotation);
for (var annotation : parameterAnnotation) {
val argumentIndexListThatNeedsToBeValidated = new LinkedList<Integer>();
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<String>();
for (var index : argumentIndexListThatNeedsToBeValidated) {
var constraintViolationSet = validator.validate(args[index]);
val errorMessageList = new LinkedList<String>();
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);
Expand Down Expand Up @@ -149,8 +150,8 @@ public void afterThrowingException(JoinPoint joinPoint, Exception e) {
* @return the all field error message
*/
private String getAllFieldErrorMessage(Set<ConstraintViolation<Object>> constraintViolationSet) {
var allErrorMessageList = new LinkedList<String>();
for (var constraintViolation : constraintViolationSet) {
val allErrorMessageList = new LinkedList<String>();
for (val constraintViolation : constraintViolationSet) {
allErrorMessageList.add(String.format("invalid field: %s, %s", constraintViolation.getPropertyPath(),
constraintViolation.getMessage()));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,14 @@
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.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
* <h1>RequestLogAspect</h1>
* <p><strong>Description</strong>:</p>
Expand Down Expand Up @@ -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());
Expand All @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -26,8 +27,7 @@
public class DruidConfiguration {
@Bean
public ServletRegistrationBean<StatViewServlet> druidServlet() {
ServletRegistrationBean<StatViewServlet> 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");
Expand All @@ -36,7 +36,7 @@ public ServletRegistrationBean<StatViewServlet> druidServlet() {

@Bean
public FilterRegistrationBean<WebStatFilter> filterRegistrationBean() {
FilterRegistrationBean<WebStatFilter> filterRegistrationBean = new FilterRegistrationBean<>();
val filterRegistrationBean = new FilterRegistrationBean<WebStatFilter>();
filterRegistrationBean.setFilter(new WebStatFilter());
filterRegistrationBean.addUrlPatterns("/*");
// Ignored resources
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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)
Expand Down
Original file line number Diff line number Diff line change
@@ -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;

Expand All @@ -13,7 +12,6 @@
* @author Johnny Miller (鍾俊), email: johnnysviva@outlook.com
* @date 2019-04-18 13:01
**/
@Slf4j
@Data
@Component
@ConfigurationProperties(prefix = "project.property")
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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 &lt;String, Serializable&gt;
*/
@Bean
public RedisTemplate<String, Serializable> redisFactory(LettuceConnectionFactory lettuceConnectionFactory) {
RedisTemplate<String, Serializable> template = new RedisTemplate<>();
val template = new RedisTemplate<String, Serializable>();
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setConnectionFactory(lettuceConnectionFactory);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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) {
Expand All @@ -80,9 +81,9 @@ public String getPublicIp() {
* @return internet IP
*/
private String getInternetIp() {
String intranetIp = this.getIntranetIp();
val intranetIp = this.getIntranetIp();
try {
Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
val networks = NetworkInterface.getNetworkInterfaces();
InetAddress ip;
Enumeration<InetAddress> addresses;
while (networks.hasMoreElements()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -69,7 +70,7 @@ public class SftpClientConfiguration {

@Bean
public SessionFactory<ChannelSftp.LsEntry> sftpSessionFactory() {
DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory(true);
val factory = new DefaultSftpSessionFactory(true);
factory.setHost(host);
factory.setPort(port);
factory.setUser(user);
Expand All @@ -81,8 +82,7 @@ public SessionFactory<ChannelSftp.LsEntry> 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<ChannelSftp.LsEntry> cachingSessionFactory = new CachingSessionFactory<>(factory,
sessionCacheSize);
val cachingSessionFactory = new CachingSessionFactory<>(factory, sessionCacheSize);
cachingSessionFactory.setSessionWaitTimeout(sessionWaitTimeout);
return cachingSessionFactory;
}
Expand All @@ -91,7 +91,7 @@ public SessionFactory<ChannelSftp.LsEntry> sftpSessionFactory() {
@ServiceActivator(inputChannel = "toSftpChannel")
@SuppressWarnings("UnresolvedMessageChannel")
public MessageHandler handler(SessionFactory<ChannelSftp.LsEntry> sftpSessionFactory) {
SftpMessageHandler handler = new SftpMessageHandler(sftpSessionFactory);
val handler = new SftpMessageHandler(sftpSessionFactory);
handler.setRemoteDirectoryExpression(new LiteralExpression(directory));
handler.setFileNameGenerator(message -> {
if (message.getPayload() instanceof File) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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));
Expand Down
Loading

0 comments on commit ff54ca5

Please sign in to comment.