Skip to content

Commit

Permalink
refactor($Hutool): use Hutool CharSequenceUtil.format() to replace St…
Browse files Browse the repository at this point in the history
…ring.format()

[skip ci]
  • Loading branch information
johnnymillergh committed Feb 19, 2022
1 parent 4e6debc commit c4e51eb
Show file tree
Hide file tree
Showing 24 changed files with 116 additions and 78 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
import javax.validation.constraints.NotNull;
import java.util.List;

import static cn.hutool.core.text.CharSequenceUtil.format;

/**
* <h1>AuthCenterRemoteApi</h1>
* <p>
Expand All @@ -48,7 +50,7 @@ public class AuthCenterRemoteApi {
public Mono<GetUserByLoginTokenResponse> getUserByLoginToken(@NotBlank String loginToken) {
return this.webClient
.get()
.uri(String.format("http://%s/user-remote-api/users/{loginToken}", SERVICE_NAME), loginToken)
.uri(format("http://{}/user-remote-api/users/{loginToken}", SERVICE_NAME), loginToken)
.retrieve()
.bodyToMono(ResponseBodyBean.class)
.map(ResponseBodyBean::getData)
Expand All @@ -64,7 +66,7 @@ public Mono<GetUserByLoginTokenResponse> getUserByLoginToken(@NotBlank String lo
public Mono<List<GetRoleListByUserIdSingleResponse>> getRoleListByUserId(@NotNull @Min(1L) Long userId) {
return this.webClient
.get()
.uri(String.format("http://%s/role-remote-api/roles/{userId}", SERVICE_NAME), userId)
.uri(format("http://{}/role-remote-api/roles/{userId}", SERVICE_NAME), userId)
.retrieve()
.bodyToMono(ResponseBodyBean.class)
.map(ResponseBodyBean::getData)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@

import java.util.List;

import static cn.hutool.core.text.CharSequenceUtil.format;

/**
* <h1>OpenApiConfiguration</h1>
* <p>
Expand All @@ -45,12 +47,12 @@ public OpenAPI openApi() {
return new OpenAPI()
.info(
new Info()
.title(String.format("API for %s@%s", projectArtifactId, version))
.title(format("API for {}@{}", projectArtifactId, version))
.description(
String.format("%s, artifact ID: %s, environment: %s",
this.mafProjectProperties.getDescription(),
projectArtifactId,
this.mafProjectProperties.getEnvironment())
format("{}, artifact ID: {}, environment: {}",
this.mafProjectProperties.getDescription(),
projectArtifactId,
this.mafProjectProperties.getEnvironment())
)
.contact(
new Contact()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@

import java.nio.charset.StandardCharsets;

import static cn.hutool.core.text.CharSequenceUtil.format;

/**
* <h1>GlobalExceptionHandler</h1>
* <p>
Expand Down Expand Up @@ -89,6 +91,6 @@ private ResponseBodyBean<?> setResponseBody(ServerHttpResponse response, Throwab
}
response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
return ResponseBodyBean.ofStatus(HttpStatus.INTERNAL_SERVER_ERROR,
String.format("Exception message: %s", ex.getMessage()));
format("Exception message: {}", ex.getMessage()));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import javax.validation.constraints.NotNull;
import java.util.stream.Collectors;

import static cn.hutool.core.text.CharSequenceUtil.format;
import static com.jmsoftware.maf.springcloudstarter.function.Slf4j.lazyDebug;

/**
Expand Down Expand Up @@ -94,14 +95,14 @@ public GetServicesInfoResponse getServicesInfo() {
.parallel()
.map(serviceId -> {
val responseBodyBean = this.restTemplate.getForObject(
String.format("http://%s/http-api-resources", serviceId), ResponseBodyBean.class);
format("http://{}/http-api-resources", serviceId), ResponseBodyBean.class);
assert responseBodyBean != null;
val data = responseBodyBean.getData();
val httpApiResourcesResponse = mapper.convertValue(data, HttpApiResourcesResponse.class);
val serviceInfo = new GetServicesInfoResponse.ServiceInfo();
serviceInfo.setServiceId(serviceId);
serviceInfo.setHttpApiResources(httpApiResourcesResponse);
lazyDebug(log, () -> String.format("Added serviceInfo: {}%s", serviceInfo));
lazyDebug(log, () -> format("Added serviceInfo: {}", serviceInfo));
return serviceInfo;
}).collect(Collectors.toList())
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static cn.hutool.core.text.CharSequenceUtil.format;
import static com.jmsoftware.maf.springcloudstarter.function.BooleanCheck.requireTrue;
import static com.jmsoftware.maf.springcloudstarter.function.Slf4j.lazyDebug;

Expand Down Expand Up @@ -70,9 +71,8 @@ public GetRoleListByUserIdResponse getRoleList(@NotNull Long userId) {
}
val response = new GetRoleListByUserIdResponse();
response.setRoleList(this.getRoleListByUserId(userId));
this.redisTemplate.opsForValue().set(key, this.objectMapper.writeValueAsString(response),
RandomUtil.randomLong(1, 7),
TimeUnit.DAYS);
this.redisTemplate.opsForValue()
.set(key, this.objectMapper.writeValueAsString(response), RandomUtil.randomLong(1, 7), TimeUnit.DAYS);
return response;
}

Expand Down Expand Up @@ -106,7 +106,7 @@ public void validateBeforeAddToBeanList(List<RoleExcelBean> beanList, RoleExcelB
log.warn("Validation failed! beanList: {}, bean: {}, index: {}", beanList, bean, index);
val firstErrorMessage = CollUtil.getFirst(beanValidationResult.getErrorMessages());
throw new IllegalArgumentException(
String.format("%s %s", firstErrorMessage.getPropertyName(), firstErrorMessage.getMessage()));
format("{} {}", firstErrorMessage.getPropertyName(), firstErrorMessage.getMessage()));
}
}

Expand All @@ -115,7 +115,7 @@ public void validateBeforeAddToBeanList(List<RoleExcelBean> beanList, RoleExcelB
@Transactional(rollbackFor = Throwable.class)
public void save(@NotEmpty List<@Valid RoleExcelBean> beanList) {
val roleList = beanList.stream().map(RoleExcelBean::transformTo).collect(Collectors.toList());
lazyDebug(log, () -> String.format("Saving roleList: %s", roleList));
lazyDebug(log, () -> format("Saving roleList: {}", roleList));
requireTrue(this.saveBatch(roleList), saved -> log.info("Saved role list: {}", saved))
.orElseThrow(() -> new InternalServerException("Failed to save roles! Transaction rollback"));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@
import java.util.Optional;
import java.util.concurrent.TimeUnit;

import static cn.hutool.core.text.CharSequenceUtil.format;

/**
* <h1>JwtServiceImpl</h1>
* Change description here.
Expand All @@ -51,7 +53,8 @@ public class JwtServiceImpl implements JwtService {
@PostConstruct
private void init() {
log.info("Start to init class members of {}.", this.getClass().getSimpleName());
this.secretKey = Keys.hmacShaKeyFor(this.jwtConfigurationProperties.getSigningKey().getBytes(StandardCharsets.UTF_8));
this.secretKey = Keys.hmacShaKeyFor(
this.jwtConfigurationProperties.getSigningKey().getBytes(StandardCharsets.UTF_8));
log.warn("Secret key for JWT was generated. Algorithm: {}", this.secretKey.getAlgorithm());
this.jwtParser = Jwts.parserBuilder().setSigningKey(this.secretKey).build();
}
Expand Down Expand Up @@ -84,7 +87,7 @@ public String createJwt(Boolean rememberMe, Long id, String subject, List<String
}
val jwt = builder.compact();
// Store new JWT in Redis
String redisKeyOfJwt = String.format("%s%s", this.jwtConfigurationProperties.getJwtRedisKeyPrefix(), subject);
String redisKeyOfJwt = format("{}{}", this.jwtConfigurationProperties.getJwtRedisKeyPrefix(), subject);
this.redisTemplate.opsForValue().set(redisKeyOfJwt, jwt, ttl, TimeUnit.MILLISECONDS);
log.info("Storing JWT in Redis. Key: {}, Value: {}", redisKeyOfJwt, jwt);
return jwt;
Expand Down Expand Up @@ -132,7 +135,7 @@ public void invalidateJwt(HttpServletRequest request) throws SecurityException {
val jwt = this.getJwtFromRequest(request);
val username = this.getUsernameFromJwt(jwt);
// Delete JWT from redis
String redisKeyOfJwt = String.format("%s%s", this.jwtConfigurationProperties.getJwtRedisKeyPrefix(), username);
String redisKeyOfJwt = format("{}{}", this.jwtConfigurationProperties.getJwtRedisKeyPrefix(), username);
val deletedKeyNumber = this.redisTemplate.opsForValue().getOperations().delete(redisKeyOfJwt);
log.error("Invalidate JWT. Redis key of JWT = {}, deleted = {}", redisKeyOfJwt, deletedKeyNumber);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import javax.validation.constraints.NotBlank;
import java.util.Optional;

import static cn.hutool.core.text.CharSequenceUtil.format;
import static com.jmsoftware.maf.springcloudstarter.function.BooleanCheck.requireTrue;

/**
Expand Down Expand Up @@ -47,7 +48,7 @@ public void assignRoleByRoleName(@NonNull User user, @NotBlank String roleName)
userRole.setRoleId(role.getId());
requireTrue(this.save(userRole), null)
.orElseThrow(() -> new InternalServerException(
String.format("Cannot assign role (%s) to user (%s)", roleName, user.getUsername())
format("Cannot assign role ({}) to user ({})", roleName, user.getUsername())
));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
import org.springframework.context.annotation.Configuration;
import org.springframework.mock.web.MockMultipartFile;

import static cn.hutool.core.text.CharSequenceUtil.format;

/**
* Description: OssConfiguration, change description here.
*
Expand All @@ -26,7 +28,7 @@ public OssUploader ossUploader() {
val multipartFile = new MockMultipartFile(name, name, null, inputStream);
val objectResponse = this.ossCenterFeignService.uploadSingleResource(multipartFile);
log.info("Uploaded multipartFile. objectResponse: {}", objectResponse);
return String.format("%s/%s", objectResponse.getBucket(), objectResponse.getObject());
return format("{}/{}", objectResponse.getBucket(), objectResponse.getObject());
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;

import static cn.hutool.core.text.CharSequenceUtil.format;

/**
* <h1>PaginationBase</h1>
* <p>
Expand Down Expand Up @@ -55,7 +57,7 @@ public class PaginationBase {
@JsonIgnore
public String getOrderByStatement() {
if (!CharSequenceUtil.isBlank(this.orderBy)) {
return String.format("%s `%s` %s", "ORDER BY", this.orderBy, this.orderRule);
return format("{} `{}` {}", "ORDER BY", this.orderBy, this.orderRule);
}
return this.orderByStatement;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
import org.springframework.context.annotation.Configuration;
import org.springframework.mock.web.MockMultipartFile;

import static cn.hutool.core.text.CharSequenceUtil.format;

/**
* Description: OssConfiguration, change description here.
*
Expand All @@ -26,7 +28,7 @@ public OssUploader ossUploader() {
val multipartFile = new MockMultipartFile(name, name, null, inputStream);
val response = this.ossCenterRemoteApi.uploadSingleResource(multipartFile);
log.info("Called {} to upload multipartFile. {}", OssCenterRemoteApi.SERVICE_NAME, response);
return String.format("%s/%s", response.getData().getBucket(), response.getData().getObject());
return format("{}/{}", response.getData().getBucket(), response.getData().getObject());
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import javax.validation.constraints.NotBlank;
import java.util.List;

import static cn.hutool.core.text.CharSequenceUtil.format;
import static com.jmsoftware.maf.osscenter.constant.Chunk.LARGE_CHUNK_SIZE;
import static com.jmsoftware.maf.osscenter.constant.Chunk.TINY_CHUNK_SIZE;

Expand Down Expand Up @@ -125,7 +126,7 @@ private ResponseEntity<StreamingResponseBody> asyncGetResourceRegion(String buck
val rangeLength = end - start + 1;
return ResponseEntity.status(HttpStatus.PARTIAL_CONTENT)
.header(HttpHeaders.ACCEPT_RANGES, ACCEPT_RANGES_VALUE)
.header(HttpHeaders.CONTENT_RANGE, String.format("bytes %d-%d/%d", start, end, resourceLength))
.header(HttpHeaders.CONTENT_RANGE, format("bytes {}-{}/{}", start, end, resourceLength))
.contentLength(rangeLength)
.contentType(MediaType.parseMediaType(statObjectResponse.contentType()))
.body(outputStream -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import java.util.Objects;
import java.util.stream.Collectors;

import static cn.hutool.core.text.CharSequenceUtil.format;
import static com.jmsoftware.maf.osscenter.constant.Chunk.TINY_CHUNK_SIZE;

/**
Expand Down Expand Up @@ -101,7 +102,7 @@ public ObjectResponse uploadResourceChunk(
// bucketName is either mediaType of given 'bucket'
val bucketName = CharSequenceUtil.isBlank(payload.getBucket()) ?
Objects.requireNonNull(mediaType).getType() : payload.getBucket();
val orderedFilename = String.format("%s.chunk%s", payload.getFilename(),
val orderedFilename = format("{}.chunk{}", payload.getFilename(),
NumberUtil.decimalFormat("000", payload.getChunkNumber()));
val objectResponse = new ObjectResponse();
objectResponse.setBucket(bucketName);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
import javax.validation.constraints.NotNull;
import java.nio.charset.StandardCharsets;

import static cn.hutool.core.text.CharSequenceUtil.format;

/**
* <h1>JwtConfigurationProperties</h1>
* <p>
Expand Down Expand Up @@ -50,11 +52,11 @@ public class JwtConfigurationProperties {
private Long ttlForRememberMe = 7 * 86400000L;

public JwtConfigurationProperties(MafProjectProperties mafProjectProperties) {
this.signingKey = String.format("%s:%s", mafProjectProperties.getGroupId(),
mafProjectProperties.getProjectParentArtifactId());
this.signingKey = format("{}:{}", mafProjectProperties.getGroupId(),
mafProjectProperties.getProjectParentArtifactId());
log.info("Initiated JWT signing key: {}. The specified key byte array is {} bits", this.signingKey,
this.signingKey.getBytes(StandardCharsets.UTF_8).length * 8);
this.jwtRedisKeyPrefix = String.format("%s:jwt:", mafProjectProperties.getProjectParentArtifactId());
this.jwtRedisKeyPrefix = format("{}:jwt:", mafProjectProperties.getProjectParentArtifactId());
log.warn("Initiated 'jwtRedisKeyPrefix': {}", this.jwtRedisKeyPrefix);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import static cn.hutool.core.text.CharSequenceUtil.format;

/**
* Description: ResponseUtil, change description here.
*
Expand Down Expand Up @@ -42,7 +44,7 @@ public Mono<Void> renderJson(@NonNull ServerWebExchange exchange, @NonNull HttpS
response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
return response.writeWith(Mono.fromSupplier(() -> {
val bufferFactory = response.bufferFactory();
val message2 = String.format("%s. %s", httpStatus.getReasonPhrase(), message);
val message2 = format("{}. {}", httpStatus.getReasonPhrase(), message);
val responseBody = ResponseBodyBean.ofStatus(httpStatus.value(), message2, data);
try {
return bufferFactory.wrap(this.objectMapper.writeValueAsBytes(responseBody));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@
import java.lang.reflect.UndeclaredThrowableException;
import java.util.Objects;

import static cn.hutool.core.text.CharSequenceUtil.format;

/**
* <h1>ExceptionControllerAdvice</h1>
* <p>
Expand Down Expand Up @@ -118,11 +120,11 @@ public ResponseBodyBean<?> handleException(HttpServletRequest request, BindExcep
String message;
if (exception.hasFieldErrors()) {
val fieldError = exception.getFieldError();
message = String.format("Field [%s] has error: %s", Objects.requireNonNull(fieldError).getField(),
fieldError.getDefaultMessage());
message = format("Field [{}] has error: {}", Objects.requireNonNull(fieldError).getField(),
fieldError.getDefaultMessage());
} else {
val globalError = exception.getGlobalError();
message = String.format("Bind error: %s", Objects.requireNonNull(globalError).getDefaultMessage());
message = format("Bind error: {}", Objects.requireNonNull(globalError).getDefaultMessage());
}
return ResponseBodyBean.ofStatus(HttpStatus.BAD_REQUEST, message);
}
Expand Down Expand Up @@ -187,12 +189,11 @@ public ResponseBodyBean<?> handleError(UndeclaredThrowableException exception) {
if (ObjectUtil.isNotNull(exception.getCause())
&& CharSequenceUtil.isNotEmpty(exception.getCause().getMessage())) {
return ResponseBodyBean.ofStatus(HttpStatus.INTERNAL_SERVER_ERROR,
String.format("Exception message: %s",
this.removeLineSeparator(
exception.getCause().getMessage())));
format("Exception message: {}",
this.removeLineSeparator(exception.getCause().getMessage())));
}
return ResponseBodyBean.ofStatus(HttpStatus.INTERNAL_SERVER_ERROR,
String.format("Exception message: %s",
format("Exception message: {}",
this.removeLineSeparator(exception.getMessage())));
}

Expand All @@ -201,7 +202,7 @@ public ResponseBodyBean<?> handleError(UndeclaredThrowableException exception) {
public ResponseBodyBean<?> handleError(Throwable ex) {
log.error("Internal server exception occurred! Exception message: {} ", ex.getMessage(), ex);
return ResponseBodyBean.ofStatus(HttpStatus.INTERNAL_SERVER_ERROR,
String.format("Exception message: %s",
format("Exception message: {}",
this.removeLineSeparator(ex.getMessage())));
}

Expand All @@ -226,7 +227,7 @@ private String getFieldErrorMessageFromException(MethodArgumentNotValidException
.getArguments())[0];
val firstErrorFieldName = firstErrorField.getDefaultMessage();
val firstErrorFieldMessage = exception.getBindingResult().getAllErrors().get(0).getDefaultMessage();
return String.format("%s %s", firstErrorFieldName, firstErrorFieldMessage);
return format("{} {}", firstErrorFieldName, firstErrorFieldMessage);
} catch (Exception e) {
log.error("Exception occurred when get field error message from exception. Exception message: {}",
e.getMessage(), e);
Expand Down
Loading

0 comments on commit c4e51eb

Please sign in to comment.