Skip to content

Commit

Permalink
perf($Java): migrate java.util.Date to java.time.LocalDateTime
Browse files Browse the repository at this point in the history
  • Loading branch information
johnnymillergh committed Mar 31, 2021
1 parent e72e8de commit a354070
Show file tree
Hide file tree
Showing 9 changed files with 44 additions and 41 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import lombok.Data;

import java.io.Serializable;
import java.util.Date;
import java.time.LocalDateTime;

/**
* Permission.(Permission) Persistence object class
Expand Down Expand Up @@ -79,13 +79,13 @@ public class PermissionPersistence implements Serializable {
* Created time
*/
@TableField(value = "created_time", fill = FieldFill.INSERT)
private Date createdTime;
private LocalDateTime createdTime;

/**
* Modified time
*/
@TableField(value = "modified_time", fill = FieldFill.INSERT_UPDATE)
private Date modifiedTime;
private LocalDateTime modifiedTime;

public static final String COL_ID = "id";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import lombok.Data;

import java.io.Serializable;
import java.util.Date;
import java.time.LocalDateTime;

/**
* Role.(Role) Persistence object class
Expand Down Expand Up @@ -48,13 +48,13 @@ public class RolePersistence implements Serializable {
* Created time
*/
@TableField(value = "created_time", fill = FieldFill.INSERT)
private Date createdTime;
private LocalDateTime createdTime;

/**
* Modified time
*/
@TableField(value = "modified_time", fill = FieldFill.INSERT_UPDATE)
private Date modifiedTime;
private LocalDateTime modifiedTime;

public static final String COL_ID = "id";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
import lombok.Data;

import java.io.Serializable;
import java.util.Date;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
* <h1>UserPersistence</h1>
Expand Down Expand Up @@ -60,7 +61,7 @@ public class UserPersistence implements Serializable {
* Birthday
*/
@TableField(value = "birthday")
private Date birthday;
private LocalDate birthday;

/**
* 26 gender options
Expand Down Expand Up @@ -93,13 +94,13 @@ public class UserPersistence implements Serializable {
* Created time
*/
@TableField(value = "created_time", fill = FieldFill.INSERT)
private Date createdTime;
private LocalDateTime createdTime;

/**
* Modified time
*/
@TableField(value = "modified_time", fill = FieldFill.INSERT_UPDATE)
private Date modifiedTime;
private LocalDateTime modifiedTime;

public static final String COL_ID = "id";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.Date;

/**
* <h1>UserServiceImpl</h1>
Expand Down Expand Up @@ -69,9 +68,6 @@ public SignupResponse saveUserForSignup(@Valid SignupPayload payload) {
userPersistence.setEmail(payload.getEmail());
userPersistence.setPassword(bCryptPasswordEncoder.encode(payload.getPassword()));
userPersistence.setStatus(UserStatus.ENABLED.getStatus());
val currentTime = new Date();
userPersistence.setCreatedTime(currentTime);
userPersistence.setModifiedTime(currentTime);
this.save(userPersistence);
log.warn("Saved user for signup. {}", userPersistence);
val response = new SignupResponse();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import org.springframework.lang.Nullable;

import java.io.Serializable;
import java.util.Date;
import java.time.LocalDateTime;

/**
* <h1>ResponseBodyBean</h1>
Expand All @@ -35,7 +35,7 @@ public class ResponseBodyBean<ResponseBodyDataType> implements Serializable {
*/
@Setter(AccessLevel.NONE)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
Date timestamp = new Date();
LocalDateTime timestamp = LocalDateTime.now();
/**
* Default status is 200 OK.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

Expand Down Expand Up @@ -57,7 +59,7 @@ public class UserPrincipal implements UserDetails {
/**
* Birthday
*/
private Date birthday;
private LocalDate birthday;
/**
* Gender
*/
Expand All @@ -69,11 +71,11 @@ public class UserPrincipal implements UserDetails {
/**
* Create time
*/
private Date gmtCreated;
private LocalDateTime gmtCreated;
/**
* Modify time
*/
private Date gmtModified;
private LocalDateTime gmtModified;
/**
* Roles that user has
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

import lombok.Data;

import java.util.Date;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
* <h1>GetUserByLoginTokenResponse</h1>
Expand Down Expand Up @@ -41,7 +42,7 @@ public class GetUserByLoginTokenResponse {
/**
* Birthday (yyyy-MM-dd)
*/
private Date birthday;
private LocalDate birthday;
/**
* 58 gender options
*/
Expand All @@ -57,9 +58,9 @@ public class GetUserByLoginTokenResponse {
/**
* Create time
*/
private Date createdTime;
private LocalDateTime createdTime;
/**
* Modify time
*/
private Date modifiedTime;
private LocalDateTime modifiedTime;
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.http.client.utils.DateUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.*;
Expand All @@ -37,8 +36,10 @@
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;

/**
Expand Down Expand Up @@ -553,13 +554,17 @@ private File uploadTempFile(byte[] itemBytes, String fileName) {
* @see
* <a href='https://blog.sayem.dev/2017/07/upload-large-files-spring-boot-html/'>Upload large files : Spring Boot</a>
*/
@SuppressWarnings("AlibabaRemoveCommentedCode")
private File uploadFile(MultipartHttpServletRequest request) throws IOException {
val multipartFile = request.getFileMap().get(FILE_KEY);
// Don't do this.
// it loads all of the bytes in java heap memory that leads to OutOfMemoryError. We'll use stream instead.
// byte[] fileBytes = multipartFile.getBytes();
@Cleanup val fileStream = new BufferedInputStream(multipartFile.getInputStream());
val fileName = DateUtils.formatDate(new Date(), "yyyyMMddHHmmssSSS") + multipartFile.getOriginalFilename();
LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
val fileName = String.format("%s%s",
LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")),
multipartFile.getOriginalFilename());
val targetFile = new File(TEMP_FILE_PATH + fileName);
FileUtils.copyInputStreamToFile(fileStream, targetFile);
uploadFileToSftp(targetFile);
Expand Down Expand Up @@ -872,8 +877,8 @@ private void registerBindHandlerMethods() {
String.class,
Field.class,
Object.class);
val bindDateField = ReflectionUtils.findMethod(this.getClass(),
"bindDateField",
val bindLocalDateTimeField = ReflectionUtils.findMethod(this.getClass(),
"bindLocalDateTimeField",
String.class,
Field.class,
Object.class);
Expand All @@ -882,7 +887,7 @@ private void registerBindHandlerMethods() {
this.bindMethodMap.put(Long.class, bindLongField);
this.bindMethodMap.put(Float.class, bindFloatField);
this.bindMethodMap.put(Double.class, bindDoubleField);
this.bindMethodMap.put(Date.class, bindDateField);
this.bindMethodMap.put(LocalDateTime.class, bindLocalDateTimeField);
} catch (Exception e) {
log.error("The bindMethod required was not found in this class!", e);
}
Expand Down Expand Up @@ -1091,23 +1096,22 @@ private Boolean bindStringField(String value, Field field, Object bean) throws I
}

/**
* Bind date field boolean.
* Bind LocalDateTime field boolean.
*
* @param value the value
* @param field the field
* @param bean the bean
* @return the boolean
* @throws IllegalAccessException the illegal access exception
*/
private Boolean bindDateField(String value, Field field, Object bean) throws IllegalAccessException {
private Boolean bindLocalDateTimeField(String value, Field field, Object bean) throws IllegalAccessException {
try {
val simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
val date = value == null ? null : simpleDateFormat.parse(value);
val date = value == null ? null : LocalDateTime.parse(value, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
field.setAccessible(true);
field.set(bean, date);
field.setAccessible(false);
} catch (ParseException e) {
log.error("Exception occurred when binding Date field! Exception message: {}, value: {}, field: {}",
} catch (DateTimeParseException e) {
log.error("Exception occurred when binding LocalDateTime field! Exception message: {}, value: {}, field: {}",
e.getMessage(), value, field.getName());
val formattedMessage = String.format("Invalid data of the row %d, col %d, must be date",
rowLocation.get(), columnLocation.get());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,10 @@
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.jmsoftware.maf.common.domain.DeletedField;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.time.LocalDateTime;

/**
* <h1>MyBatisPlusConfiguration</h1>
Expand All @@ -28,17 +27,17 @@ public class MyBatisPlusMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
log.info("Starting to insert fill metaObject: {}", metaObject.getOriginalObject());
val now = new Date();
LocalDateTime now = LocalDateTime.now();
this.strictInsertFill(metaObject, DELETED_FIELD_NAME, Byte.class, DeletedField.NOT_DELETED.getValue())
.strictInsertFill(metaObject, CREATED_TIME_FIELD_NAME, Date.class, now)
.strictInsertFill(metaObject, MODIFIED_TIME_FIELD_NAME, Date.class, now);
.strictInsertFill(metaObject, CREATED_TIME_FIELD_NAME, LocalDateTime.class, now)
.strictInsertFill(metaObject, MODIFIED_TIME_FIELD_NAME, LocalDateTime.class, now);
log.info("Finished to insert fill metaObject: {}", metaObject.getOriginalObject());
}

@Override
public void updateFill(MetaObject metaObject) {
log.info("Starting to update fill metaObject: {}", metaObject.getOriginalObject());
this.strictUpdateFill(metaObject, MODIFIED_TIME_FIELD_NAME, Date.class, new Date());
this.strictUpdateFill(metaObject, MODIFIED_TIME_FIELD_NAME, LocalDateTime.class, LocalDateTime.now());
log.info("Finished to update fill metaObject: {}", metaObject.getOriginalObject());
}
}

0 comments on commit a354070

Please sign in to comment.