Here are the examples of the java api @org.springframework.core.annotation.Order taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
84 Examples
19
View Source File : SecurityConfiguration.java
License : Apache License 2.0
Project Creator : zuihou
License : Apache License 2.0
Project Creator : zuihou
/**
* 权限认证配置类
*
* @author zuihou
* @date 2020年03月29日22:34:45
*/
@Order
@AllArgsConstructor
@EnableConfigurationProperties({ SecurityProperties.clreplaced })
public clreplaced SecurityConfiguration {
private final SecurityProperties securityProperties;
@Bean
@ConditionalOnProperty(prefix = SecurityProperties.PREFIX, name = "enabled", havingValue = "true", matchIfMissing = true)
public UriSecurityPreAuthAspect uriSecurityPreAuthAspect(VerifyAuthFunction verifyAuthFunction) {
return new UriSecurityPreAuthAspect(verifyAuthFunction);
}
@Bean("fun")
@ConditionalOnMissingBean(VerifyAuthFunction.clreplaced)
public VerifyAuthFunction getVerifyAuthFunction(UserResolverService userResolverService) {
return new VerifyAuthFunction(userResolverService, securityProperties);
}
}
19
View Source File : SysLogListener.java
License : Apache License 2.0
Project Creator : zuihou
License : Apache License 2.0
Project Creator : zuihou
@Async
@Order
@EventListener(SysLogEvent.clreplaced)
public void saveSysLog(SysLogEvent event) {
OptLogDTO sysLog = (OptLogDTO) event.getSource();
if (sysLog == null || StrUtil.isEmpty(sysLog.getTenantCode())) {
log.warn("租户编码不存在,忽略操作日志=={}", sysLog != null ? sysLog.getRequestUri() : "");
return;
}
ContextUtil.setTenant(sysLog.getTenantCode());
consumer.accept(sysLog);
}
19
View Source File : GlobalExceptionAdvice.java
License : MIT License
Project Creator : zidoshare
License : MIT License
Project Creator : zidoshare
/**
* server 异常处理,兜底处理
*
* @author zido
*/
@RestControllerAdvice
@Order
public clreplaced GlobalExceptionAdvice extends BaseGlobalExceptionHandler {
public GlobalExceptionAdvice(HttpResponseBodyFactory factory) {
super(factory);
}
/**
* parameter参数校验异常处理
*
* @param e 校验异常
* @return result
*/
@ExceptionHandler(value = ConstraintViolationException.clreplaced)
@Override
public ResponseEnreplacedy<Object> handleConstraintViolationException(ConstraintViolationException e, WebRequest request) {
return super.handleConstraintViolationException(e, request);
}
@ExceptionHandler(CommonBusinessException.clreplaced)
@Override
protected ResponseEnreplacedy<Object> handleCommonBusinessException(CommonBusinessException e, WebRequest request, HttpServletResponse response) {
return super.handleCommonBusinessException(e, request, response);
}
}
19
View Source File : AtomLockAspect.java
License : MIT License
Project Creator : yizzuide
License : MIT License
Project Creator : yizzuide
/**
* AtomLockAspect
*
* @author yizzuide
* @since 3.3.0
* @version 3.7.0
* Create at 2020/04/30 16:26
*/
@Slf4j
@Order
@Aspect
public clreplaced AtomLockAspect {
@Autowired
private Atom atom;
@Around("@annotation(atomLock) && execution(public * *(..))")
public Object pointCut(ProceedingJoinPoint joinPoint, AtomLock atomLock) throws Throwable {
String keyPath = ELContext.getValue(joinPoint, atomLock.key());
Object lock = null;
boolean isLocked = false;
try {
if (atomLock.waitTime() > 0) {
AtomLockInfo lockInfo = atom.tryLock(keyPath, atomLock.type(), atomLock.readOnly());
isLocked = lockInfo.isLocked();
lock = lockInfo.getLock();
if (!isLocked) {
lockInfo = atom.tryLock(keyPath, Duration.ofMillis(atomLock.waitTime()), Duration.ofMillis(atomLock.leaseTime()), atomLock.type(), atomLock.readOnly());
isLocked = lockInfo.isLocked();
lock = lockInfo.getLock();
}
if (isLocked) {
return joinPoint.proceed();
}
if (atomLock.waitTimeoutType() == AtomLockWaitTimeoutType.THROW_EXCEPTION) {
throw new AtomLockWaitTimeoutException();
} else if (atomLock.waitTimeoutType() == AtomLockWaitTimeoutType.FALLBACK) {
String fallback = atomLock.fallback();
return ELContext.getActualValue(joinPoint, fallback, ReflectUtil.getMethodReturnType(joinPoint));
}
// here is AtomLockWaitTimeoutType.WAIT_INFINITE
}
AtomLockInfo lockInfo = atom.lock(keyPath, Duration.ofMillis(atomLock.leaseTime()), atomLock.type(), atomLock.readOnly());
lock = lockInfo.getLock();
isLocked = lockInfo.isLocked();
return joinPoint.proceed();
} catch (InterruptedException e) {
log.error("Atom try lock error with msg: {}", e.getMessage(), e);
} finally {
// 只有加锁的线程需要解锁
if (isLocked && lock != null && atom.isLocked(lock)) {
atom.unlock(lock);
}
}
// unreachable code!
return null;
}
}
19
View Source File : TfaOtpRequestFilter.java
License : Apache License 2.0
Project Creator : xm-online
License : Apache License 2.0
Project Creator : xm-online
/**
* The {@link TfaOtpRequestFilter} clreplaced.
*/
@Order
public clreplaced TfaOtpRequestFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
HttpServletResponse responseToUse = response;
if ("/oauth/token".equals(request.getRequestURI())) {
responseToUse = wrapResponse(request, response);
}
filterChain.doFilter(request, responseToUse);
}
private HttpServletResponse wrapResponse(HttpServletRequest request, HttpServletResponse originalResponse) {
return new HttpServletResponseWrapper(originalResponse) {
@Override
public void setStatus(int sc) {
super.setStatus(sc);
handleStatus(sc);
}
@Override
@SuppressWarnings("deprecation")
public void setStatus(int sc, String sm) {
super.setStatus(sc, sm);
handleStatus(sc);
}
@Override
public void sendError(int sc, String msg) throws IOException {
super.sendError(sc, msg);
handleStatus(sc);
}
@Override
public void sendError(int sc) throws IOException {
super.sendError(sc);
handleStatus(sc);
}
@Override
public HttpServletResponse getResponse() {
return HttpServletResponse.clreplaced.cast(super.getResponse());
}
private void handleStatus(int statusCode) {
HttpStatus httpStatus = HttpStatus.valueOf(statusCode);
if (httpStatus.is2xxSuccessful()) {
Object encodedOtp = RequestContextHolder.getRequestAttributes().getAttribute(REQ_ATTR_TFA_VERIFICATION_OTP_KEY, SCOPE_REQUEST);
if (encodedOtp != null && encodedOtp instanceof String && StringUtils.isNotBlank((String) encodedOtp)) {
addOtpHeaders(getResponse());
}
}
}
};
}
private static void addOtpHeaders(HttpServletResponse response) {
response.setHeader(Constants.HTTP_HEADER_TFA_OTP, "required");
// add OTP channel type
Object otpChannelTypeObj = RequestContextHolder.getRequestAttributes().getAttribute(REQ_ATTR_TFA_OTP_CHANNEL_TYPE, SCOPE_REQUEST);
if (otpChannelTypeObj instanceof OtpChannelType) {
OtpChannelType otpChannelType = OtpChannelType.clreplaced.cast(otpChannelTypeObj);
response.setHeader(Constants.HTTP_HEADER_TFA_OTP_CHANNEL, otpChannelType.getTypeName());
}
}
}
19
View Source File : LogEventListener.java
License : GNU Lesser General Public License v3.0
Project Creator : xkcoding
License : GNU Lesser General Public License v3.0
Project Creator : xkcoding
/**
* 自定义日志事件处理
*
* @param event 事件
*/
@Async
@Order
@EventListener(CustomLogEvent.clreplaced)
public void handleCustomLogEvent(CustomLogEvent event) {
CustomLogModel model = wrapperLogModel(event);
logHandler.handleCustomLog(model);
}
19
View Source File : LogEventListener.java
License : GNU Lesser General Public License v3.0
Project Creator : xkcoding
License : GNU Lesser General Public License v3.0
Project Creator : xkcoding
/**
* 操作日志事件处理
*
* @param event 事件
*/
@Async
@Order
@EventListener(OperateLogEvent.clreplaced)
public void handleOperateLogEvent(OperateLogEvent event) {
OperateLogModel model = wrapperLogModel(event);
logHandler.handleOperateLog(model);
}
19
View Source File : LogEventListener.java
License : GNU Lesser General Public License v3.0
Project Creator : xkcoding
License : GNU Lesser General Public License v3.0
Project Creator : xkcoding
/**
* 错误日志事件处理
*
* @param event 事件
*/
@Async
@Order
@EventListener(ErrorLogEvent.clreplaced)
public void handleErrorLogEvent(ErrorLogEvent event) {
ErrorLogModel model = wrapperLogModel(event);
logHandler.handleErrorLog(model);
}
19
View Source File : JdbcConfig.java
License : MIT License
Project Creator : woowacourse-teams
License : MIT License
Project Creator : woowacourse-teams
@Bean
@Order
BeforeSaveCallback<?> validateBeforeSave(final Validator validator) {
return ((aggregate, aggregateChange) -> {
final Set<ConstraintViolation<Object>> violations = validator.validate(aggregate);
if (!violations.isEmpty()) {
throw new ConstraintViolationException(violations);
}
return aggregate;
});
}
19
View Source File : GlobalExceptionHandler.java
License : GNU General Public License v3.0
Project Creator : wlhbdp
License : GNU General Public License v3.0
Project Creator : wlhbdp
@ControllerAdvice
@Order
public clreplaced GlobalExceptionHandler {
private Log logger = LogFactory.getLog(GlobalExceptionHandler.clreplaced);
@ExceptionHandler(IllegalArgumentException.clreplaced)
@ResponseBody
public Object badArgumentHandler(IllegalArgumentException e) {
logger.error(e.getMessage(), e);
return ResponseUtil.badArgumentValue();
}
@ExceptionHandler(MethodArgumentTypeMismatchException.clreplaced)
@ResponseBody
public Object badArgumentHandler(MethodArgumentTypeMismatchException e) {
logger.error(e.getMessage(), e);
return ResponseUtil.badArgumentValue();
}
@ExceptionHandler(MissingServletRequestParameterException.clreplaced)
@ResponseBody
public Object badArgumentHandler(MissingServletRequestParameterException e) {
logger.error(e.getMessage(), e);
return ResponseUtil.badArgumentValue();
}
@ExceptionHandler(HttpMessageNotReadableException.clreplaced)
@ResponseBody
public Object badArgumentHandler(HttpMessageNotReadableException e) {
logger.error(e.getMessage(), e);
return ResponseUtil.badArgumentValue();
}
@ExceptionHandler(ValidationException.clreplaced)
@ResponseBody
public Object badArgumentHandler(ValidationException e) {
logger.error(e.getMessage(), e);
if (e instanceof ConstraintViolationException) {
ConstraintViolationException exs = (ConstraintViolationException) e;
Set<ConstraintViolation<?>> violations = exs.getConstraintViolations();
for (ConstraintViolation<?> item : violations) {
String message = ((PathImpl) item.getPropertyPath()).getLeafNode().getName() + item.getMessage();
return ResponseUtil.fail(402, message);
}
}
return ResponseUtil.badArgumentValue();
}
@ExceptionHandler(Exception.clreplaced)
@ResponseBody
public Object seriousHandler(Exception e) {
logger.error(e.getMessage(), e);
return ResponseUtil.serious();
}
}
19
View Source File : LogListener.java
License : MIT License
Project Creator : wells2333
License : MIT License
Project Creator : wells2333
/**
* 异步记录日志
*
* @param event event
*/
@Async
@Order
@EventListener(LogEvent.clreplaced)
public void saveSysLog(LogEvent event) {
Log log = (Log) event.getSource();
userServiceClient.saveLog(log);
}
19
View Source File : FastJsonViewResponseBodyAdvice.java
License : Apache License 2.0
Project Creator : uavorg
License : Apache License 2.0
Project Creator : uavorg
/**
* A convenient base clreplaced for {@code ResponseBodyAdvice} implementations
* that customize the response before JSON serialization with {@link FastJsonHttpMessageConverter4}'s concrete
* subclreplacedes.
* <p>
*
* @author yanquanyu
* @author liuming
*/
@Order
@ControllerAdvice
public clreplaced FastJsonViewResponseBodyAdvice implements ResponseBodyAdvice<Object> {
public boolean supports(MethodParameter returnType, Clreplaced<? extends HttpMessageConverter<?>> converterType) {
return FastJsonHttpMessageConverter.clreplaced.isreplacedignableFrom(converterType) && returnType.hasMethodAnnotation(FastJsonView.clreplaced);
}
public FastJsonContainer beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Clreplaced<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
FastJsonContainer container = getOrCreateContainer(body);
beforeBodyWriteInternal(container, selectedContentType, returnType, request, response);
return container;
}
private FastJsonContainer getOrCreateContainer(Object body) {
return (body instanceof FastJsonContainer ? (FastJsonContainer) body : new FastJsonContainer(body));
}
protected void beforeBodyWriteInternal(FastJsonContainer container, MediaType contentType, MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response) {
FastJsonView annotation = returnType.getMethodAnnotation(FastJsonView.clreplaced);
FastJsonFilter[] include = annotation.include();
FastJsonFilter[] exclude = annotation.exclude();
PropertyPreFilters filters = new PropertyPreFilters();
for (FastJsonFilter item : include) {
filters.addFilter(item.clazz(), item.props());
}
for (FastJsonFilter item : exclude) {
filters.addFilter(item.clazz()).addExcludes(item.props());
}
container.setFilters(filters);
}
}
19
View Source File : AwsRDSService.java
License : Apache License 2.0
Project Creator : ThalesGroup
License : Apache License 2.0
Project Creator : ThalesGroup
@Bean
@RefreshScope
@ConditionalOnMissingBean
@Order
AmazonEC2 amazonEC2(AWSCredentialsProvider awsStaticCredentialsProvider) {
log.info("Creating AWS EC2 Client");
return AmazonEC2ClientBuilder.standard().withCredentials(awsStaticCredentialsProvider).withRegion(region).build();
}
19
View Source File : NoRepeatSubmitInterceptor.java
License : Apache License 2.0
Project Creator : TDuckCloud
License : Apache License 2.0
Project Creator : TDuckCloud
/**
* @description: 不允许重复提交
* @author: smalljop.o
* @create: 2019-12-31 10:39
*/
@Component
@Order
@Slf4j
@AllArgsConstructor
public clreplaced NoRepeatSubmitInterceptor implements HandlerInterceptor {
private final RedisUtils redisUtils;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (!handler.getClreplaced().equals(HandlerMethod.clreplaced)) {
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) handler;
boolean repeatSubmit = handlerMethod.getMethod().isAnnotationPresent(NoRepeatSubmit.clreplaced);
if (repeatSubmit) {
BodyReaderHttpServletRequestWrapper wrapper = null;
if (request instanceof BodyReaderHttpServletRequestWrapper) {
wrapper = (BodyReaderHttpServletRequestWrapper) request;
} else {
return true;
}
String body = wrapper.getBodyJson();
String md5 = SecureUtil.md5(body);
String requestURI = wrapper.getRequestURI();
String key = new StringBuffer("repeat:").append(requestURI).append(":").append(md5).toString();
// 存在key认为是重复提交
synchronized (key) {
if (redisUtils.exists(key)) {
log.info("无效重复提交key:{} body:{}", key, body);
return false;
} else {
redisUtils.set(key, "", 2L, TimeUnit.SECONDS);
}
}
}
return true;
}
}
19
View Source File : UploaderConfiguration.java
License : MIT License
Project Creator : TaleLin
License : MIT License
Project Creator : TaleLin
/**
* @return 本地文件上传实现类
*/
@Bean
@Order
@ConditionalOnMissingBean
public Uploader uploader() {
return new LocalUploader();
}
19
View Source File : RestExceptionHandler.java
License : MIT License
Project Creator : TaleLin
License : MIT License
Project Creator : TaleLin
/**
* @author pedro@TaleLin
* @author colorful@TaleLin
* @author Juzi@TaleLin
*/
@Order
@RestControllerAdvice
@Slf4j
public clreplaced RestExceptionHandler {
@Value("${spring.servlet.multipart.max-file-size:20M}")
private String maxFileSize;
/**
* HttpException
*/
@ExceptionHandler({ HttpException.clreplaced })
public UnifyResponseVO processException(HttpException exception, HttpServletRequest request, HttpServletResponse response) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
UnifyResponseVO unifyResponse = new UnifyResponseVO();
unifyResponse.setRequest(getSimpleRequest(request));
int code = exception.getCode();
boolean defaultMessage = exception.ifDefaultMessage();
unifyResponse.setCode(code);
response.setStatus(exception.getHttpCode());
String errorMessage = CodeMessageConfiguration.getMessage(code);
if (StrUtil.isBlank(errorMessage) || !defaultMessage) {
unifyResponse.setMessage(exception.getMessage());
log.error("", exception);
} else {
unifyResponse.setMessage(errorMessage);
log.error("", exception.getClreplaced().getConstructor(int.clreplaced, String.clreplaced).newInstance(code, errorMessage));
}
return unifyResponse;
}
/**
* ConstraintViolationException
*/
@ExceptionHandler({ ConstraintViolationException.clreplaced })
public UnifyResponseVO processException(ConstraintViolationException exception, HttpServletRequest request, HttpServletResponse response) {
log.error("", exception);
Map<String, Object> msg = new HashMap<>();
exception.getConstraintViolations().forEach(constraintViolation -> {
String template = constraintViolation.getMessage();
String path = constraintViolation.getPropertyPath().toString();
msg.put(StrUtil.toUnderlineCase(path), template);
});
UnifyResponseVO unifyResponse = new UnifyResponseVO();
unifyResponse.setRequest(getSimpleRequest(request));
unifyResponse.setMessage(msg);
unifyResponse.setCode(Code.PARAMETER_ERROR.getCode());
response.setStatus(HttpStatus.BAD_REQUEST.value());
return unifyResponse;
}
/**
* NoHandlerFoundException
*/
@ExceptionHandler({ NoHandlerFoundException.clreplaced })
public UnifyResponseVO processException(NoHandlerFoundException exception, HttpServletRequest request, HttpServletResponse response) {
log.error("", exception);
UnifyResponseVO unifyResponse = new UnifyResponseVO();
unifyResponse.setRequest(getSimpleRequest(request));
String message = CodeMessageConfiguration.getMessage(10025);
if (StrUtil.isBlank(message)) {
unifyResponse.setMessage(exception.getMessage());
} else {
unifyResponse.setMessage(message);
}
unifyResponse.setCode(Code.NOT_FOUND.getCode());
response.setStatus(HttpStatus.NOT_FOUND.value());
return unifyResponse;
}
/**
* MissingServletRequestParameterException
*/
@ExceptionHandler({ MissingServletRequestParameterException.clreplaced })
public UnifyResponseVO processException(MissingServletRequestParameterException exception, HttpServletRequest request, HttpServletResponse response) {
log.error("", exception);
UnifyResponseVO result = new UnifyResponseVO();
result.setRequest(getSimpleRequest(request));
String errorMessage = CodeMessageConfiguration.getMessage(10150);
if (StrUtil.isBlank(errorMessage)) {
result.setMessage(exception.getMessage());
} else {
result.setMessage(errorMessage + exception.getParameterName());
}
result.setCode(Code.PARAMETER_ERROR.getCode());
response.setStatus(HttpStatus.BAD_REQUEST.value());
return result;
}
/**
* MethodArgumentTypeMismatchException
*/
@ExceptionHandler({ MethodArgumentTypeMismatchException.clreplaced })
public UnifyResponseVO processException(MethodArgumentTypeMismatchException exception, HttpServletRequest request, HttpServletResponse response) {
log.error("", exception);
UnifyResponseVO result = new UnifyResponseVO();
result.setRequest(getSimpleRequest(request));
String errorMessage = CodeMessageConfiguration.getMessage(10160);
if (StrUtil.isBlank(errorMessage)) {
result.setMessage(exception.getMessage());
} else {
result.setMessage(exception.getValue() + errorMessage);
}
result.setCode(Code.PARAMETER_ERROR.getCode());
response.setStatus(HttpStatus.BAD_REQUEST.value());
return result;
}
/**
* ServletException
*/
@ExceptionHandler({ ServletException.clreplaced })
public UnifyResponseVO processException(ServletException exception, HttpServletRequest request, HttpServletResponse response) {
log.error("", exception);
UnifyResponseVO result = new UnifyResponseVO();
result.setRequest(getSimpleRequest(request));
result.setMessage(exception.getMessage());
result.setCode(Code.FAIL.getCode());
response.setStatus(HttpStatus.BAD_REQUEST.value());
return result;
}
/**
* MethodArgumentNotValidException
*/
@ExceptionHandler({ MethodArgumentNotValidException.clreplaced })
public UnifyResponseVO processException(MethodArgumentNotValidException exception, HttpServletRequest request, HttpServletResponse response) {
log.error("", exception);
BindingResult bindingResult = exception.getBindingResult();
List<ObjectError> errors = bindingResult.getAllErrors();
Map<String, Object> msg = new HashMap<>();
errors.forEach(error -> {
if (error instanceof FieldError) {
FieldError fieldError = (FieldError) error;
msg.put(StrUtil.toUnderlineCase(fieldError.getField()), fieldError.getDefaultMessage());
} else {
msg.put(StrUtil.toUnderlineCase(error.getObjectName()), error.getDefaultMessage());
}
});
UnifyResponseVO result = new UnifyResponseVO();
result.setRequest(getSimpleRequest(request));
result.setMessage(msg);
result.setCode(Code.PARAMETER_ERROR.getCode());
response.setStatus(HttpStatus.BAD_REQUEST.value());
return result;
}
/**
* HttpMessageNotReadableException
*/
@ExceptionHandler({ HttpMessageNotReadableException.clreplaced })
public UnifyResponseVO processException(HttpMessageNotReadableException exception, HttpServletRequest request, HttpServletResponse response) {
log.error("", exception);
UnifyResponseVO result = new UnifyResponseVO();
result.setRequest(getSimpleRequest(request));
String errorMessage = CodeMessageConfiguration.getMessage(10170);
if (StrUtil.isBlank(errorMessage)) {
result.setMessage(exception.getMessage());
} else {
result.setMessage(errorMessage);
}
result.setCode(Code.PARAMETER_ERROR.getCode());
response.setStatus(HttpStatus.BAD_REQUEST.value());
return result;
}
/**
* TypeMismatchException
*/
@ExceptionHandler({ TypeMismatchException.clreplaced })
public UnifyResponseVO processException(TypeMismatchException exception, HttpServletRequest request, HttpServletResponse response) {
log.error("", exception);
UnifyResponseVO result = new UnifyResponseVO();
result.setRequest(getSimpleRequest(request));
result.setMessage(exception.getMessage());
result.setCode(Code.PARAMETER_ERROR.getCode());
response.setStatus(HttpStatus.BAD_REQUEST.value());
return result;
}
/**
* MaxUploadSizeExceededException
*/
@ExceptionHandler({ MaxUploadSizeExceededException.clreplaced })
public UnifyResponseVO processException(MaxUploadSizeExceededException exception, HttpServletRequest request, HttpServletResponse response) {
log.error("", exception);
UnifyResponseVO result = new UnifyResponseVO();
result.setRequest(getSimpleRequest(request));
String errorMessage = CodeMessageConfiguration.getMessage(10180);
if (StrUtil.isBlank(errorMessage)) {
result.setMessage(exception.getMessage());
} else {
result.setMessage(errorMessage + maxFileSize);
}
result.setCode(Code.FILE_TOO_LARGE.getCode());
response.setStatus(HttpStatus.PAYLOAD_TOO_LARGE.value());
return result;
}
/**
* Exception
*/
@ExceptionHandler({ Exception.clreplaced })
public UnifyResponseVO processException(Exception exception, HttpServletRequest request, HttpServletResponse response) {
log.error("", exception);
UnifyResponseVO result = new UnifyResponseVO();
result.setRequest(getSimpleRequest(request));
result.setMessage(Code.INTERNAL_SERVER_ERROR.getZhDescription());
result.setCode(Code.INTERNAL_SERVER_ERROR.getCode());
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
return result;
}
}
19
View Source File : EurekaServerListProcessor.java
License : Apache License 2.0
Project Creator : SpringCloud
License : Apache License 2.0
Project Creator : SpringCloud
@Order
@EventListener(RefreshScopeRefreshedEvent.clreplaced)
public void onApplicationEvent(RefreshScopeRefreshedEvent event) {
reloadAndRegister();
}
19
View Source File : GlobalClientInterceptorConfiguration.java
License : Apache License 2.0
Project Creator : SpringCloud
License : Apache License 2.0
Project Creator : SpringCloud
/**
* emil:[email protected]
* Created by forezp on 2018/8/11.
*/
@Order
@Configuration
public clreplaced GlobalClientInterceptorConfiguration {
@Bean
public GlobalClientInterceptorConfigurerAdapter globalInterceptorConfigurerAdapter() {
return new GlobalClientInterceptorConfigurerAdapter() {
@Override
public void addClientInterceptors(GlobalClientInterceptorRegistry registry) {
registry.addClientInterceptors(new LogGrpcInterceptor());
}
};
}
}
19
View Source File : SysLogListener.java
License : GNU Lesser General Public License v3.0
Project Creator : somowhere
License : GNU Lesser General Public License v3.0
Project Creator : somowhere
@Async
@Order
@EventListener(SysLogEvent.clreplaced)
public void saveSysLog(SysLogEvent event) {
log.debug("{}", event);
LogOperate logOperate = (LogOperate) event.getSource();
logOperate.setIpLocation(AddressUtils.getRealAddressByIp(logOperate.getIpAddress()));
remoteLogOperateService.save(logOperate, SecurityConstants.FROM_IN);
}
19
View Source File : SysUserOnlineListener.java
License : GNU Lesser General Public License v3.0
Project Creator : somowhere
License : GNU Lesser General Public License v3.0
Project Creator : somowhere
@Async
@Order
@EventListener(SysUserOnlineRefreshLastRequestEvent.clreplaced)
public void saveSysUserOnlineRefreshLastRequestEvent(SysUserOnlineRefreshLastRequestEvent event) {
SessionInformation sessionInformation = (SessionInformation) event.getSource();
UserOnline userOnline = userOnlineService.getById(sessionInformation.getSessionId());
if (userOnline != null) {
userOnline.setLastAccessTime(sessionInformation.getLastRequest());
userOnlineService.updateById(userOnline);
} else {
log.debug("sessionInformation sessionId " + sessionInformation.getSessionId() + ", onlineUser is null");
}
}
19
View Source File : SysUserOnlineListener.java
License : GNU Lesser General Public License v3.0
Project Creator : somowhere
License : GNU Lesser General Public License v3.0
Project Creator : somowhere
@Async
@Order
@EventListener(SysUserOnlineEvent.clreplaced)
public void saveSysUserOnline(SysUserOnlineEvent event) {
UserOnline userOnline = (UserOnline) event.getSource();
userOnlineService.saveByEvent(userOnline);
}
19
View Source File : SysLogListener.java
License : GNU Lesser General Public License v3.0
Project Creator : somowhere
License : GNU Lesser General Public License v3.0
Project Creator : somowhere
@Async
@Order
@EventListener(SysLogEvent.clreplaced)
public void saveSysLog(SysLogEvent event) {
LogOperate logOperate = (LogOperate) event.getSource();
logOperateService.saveOrUpdate(logOperate);
}
19
View Source File : LockAspect.java
License : MIT License
Project Creator : sika-code
License : MIT License
Project Creator : sika-code
/**
* 锁的切面
*
* @author daiqi
* @create 2019-07-30 10:38
*/
@Aspect
@Order
@Data
@AllArgsConstructor
@Slf4j
public clreplaced LockAspect {
protected DistributionLockHandler lockHandler;
protected DistributionLockProperties distributionLockProperties;
@Pointcut("@annotation(com.sika.code.lock.anotation.DistributionLock)")
public void lockAspect() {
}
@Around(value = "lockAspect()")
public Object annotationAround(ProceedingJoinPoint joinPoint) throws Throwable {
return doAround(joinPoint);
}
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
LockResult lockResult = null;
try {
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method targetMethod = methodSignature.getMethod();
// 获取分布式锁注解
DistributionLock lock = targetMethod.getAnnotation(DistributionLock.clreplaced);
Object keyValue = getKeyValue(lock, joinPoint);
lockResult = doLock(lock, keyValue);
return joinPoint.proceed();
} finally {
if (BaseUtil.isNotNull(lockResult) && BaseUtil.isNotNull(lockResult.getLock())) {
lockHandler.unlock(lockResult.getLock());
}
}
}
/**
* <p>
* 获取属性名称对应的keyValue
* </p>
*
* @param lock
* @param joinPoint
* @return java.lang.Object
* @author daiqi
* @date 2019/7/30 17:45
*/
public Object getKeyValue(DistributionLock lock, ProceedingJoinPoint joinPoint) {
int index = lock.index();
Object[] args = joinPoint.getArgs();
// 校验参数
verifyArgs(index, args);
// 分解属性名称
String fieldName = lock.fieldName();
Object keyValue = args[index];
if (StringUtil.isNotBlank(fieldName) && BaseUtil.isNotNull(keyValue)) {
String[] fieldNames = StringUtil.split(fieldName, StringConstant.Symbol.STOP);
for (String fieldNameItem : fieldNames) {
keyValue = ReflectionUtil.getFieldValue(keyValue, fieldNameItem);
if (BaseUtil.isNull(keyValue)) {
break;
}
}
}
replacedert.verifyObjNull(keyValue, "keyValue");
return keyValue;
}
/**
* <p>
* 校验参数
* </p>
*
* @param index
* @param args
* @return void
* @author daiqi
* @date 2019/7/30 17:46
*/
public void verifyArgs(int index, Object[] args) {
if (ArrayUtil.isEmpty(args)) {
throw new BusinessException(BaseErrorCodeEnum.DATA_ERROR, "target method args is null");
}
if (index < 0) {
throw new BusinessException(BaseErrorCodeEnum.DATA_ERROR).buildFormatValues("index:" + index);
}
int length = args.length;
if (index >= length) {
String errorMsg = "index:" + index + "大于等于 args.length:" + length;
throw new BusinessException(BaseErrorCodeEnum.DATA_ERROR, errorMsg);
}
}
/**
* <p>
* 执行加锁业务逻辑
* </p>
*
* @param lock
* @param keyValue
* @return com.sika.code.lock.pojo.result.LockResult
* @author daiqi
* @date 2019/7/30 17:46
*/
public LockResult doLock(DistributionLock lock, Object keyValue) {
if (BaseUtil.isNull(lock) || BaseUtil.isNull(keyValue)) {
return null;
}
LockType lockType = lock.lockType();
switch(lockType) {
case FAIR:
return fairLock(lock, keyValue);
case MULTI_LOCK:
return multiLock(lock, keyValue);
default:
return lock(lock, keyValue);
}
}
/**
* <p>
* 公平锁
* </p>
*
* @param lock
* @param keyValue
* @return com.sika.code.lock.pojo.result.LockResult
* @author daiqi
* @date 2019/7/31 9:42
*/
protected LockResult fairLock(DistributionLock lock, Object keyValue) {
String fullKey = buildFullKey(lock.modules(), keyValue);
int waitTime = buildWaitTime(lock.waitTime());
int leaseTime = buildWaitTime(lock.leaseTime());
if (LockTryType.TRY.equals(lock.lockTryType())) {
return lockHandler.tryFairLock(fullKey, waitTime, leaseTime, lock.timeUnit());
} else {
return lockHandler.fairLock(fullKey, leaseTime, lock.timeUnit());
}
}
/**
* <p>
* 非公平锁
* </p>
*
* @param lock
* @param keyValue
* @return com.sika.code.lock.pojo.result.LockResult
* @author daiqi
* @date 2019/7/31 9:42
*/
protected LockResult lock(DistributionLock lock, Object keyValue) {
String fullKey = buildFullKey(lock.modules(), keyValue);
int waitTime = buildWaitTime(lock.waitTime());
int leaseTime = buildWaitTime(lock.leaseTime());
if (LockTryType.TRY.equals(lock.lockTryType())) {
return lockHandler.tryLock(fullKey, waitTime, leaseTime, lock.timeUnit());
} else {
return lockHandler.lock(fullKey, leaseTime, lock.timeUnit());
}
}
/**
* <p>
* 级联锁
* </p>
*
* @param lock
* @param keyValue
* @return com.sika.code.lock.pojo.result.LockResult
* @author daiqi
* @date 2019/7/31 9:42
*/
protected LockResult multiLock(DistributionLock lock, Object keyValue) {
Collection keyValues = null;
if (keyValue instanceof Collection) {
keyValues = (Collection) keyValue;
}
if (CollUtil.isEmpty(keyValues)) {
return null;
}
List<String> keys = Lists.newArrayList();
for (Object key : keyValues) {
keys.add(buildFullKey(lock.modules(), key));
}
int waitTime = buildWaitTime(lock.waitTime());
int leaseTime = buildWaitTime(lock.leaseTime());
if (LockTryType.TRY.equals(lock.lockTryType())) {
return lockHandler.tryLock(keys, waitTime, leaseTime, lock.timeUnit());
} else {
return lockHandler.lock(keys, leaseTime, lock.timeUnit());
}
}
protected int buildWaitTime(final int waitTimeAnnotation) {
int waitTime = waitTimeAnnotation;
if (LockConstant.TIME_DEFAULT == waitTime) {
waitTime = distributionLockProperties.getWaitTime();
}
return waitTime;
}
protected int buildLeaseTime(int leaseTimeAnnotation) {
int leaseTime = leaseTimeAnnotation;
if (LockConstant.TIME_DEFAULT == leaseTime) {
leaseTime = distributionLockProperties.getLeaseTime();
}
return leaseTime;
}
/**
* <p>
* 构建完整的Key
* </p>
*
* @param modules : 模块名称列表
* @param key : key
* @return java.lang.String
* @author daiqi
* @date 2019/7/30 15:54
*/
private String buildFullKey(String[] modules, Object key) {
String prefix = distributionLockProperties.getPrefix();
List<String> fullKeyItems = Lists.newArrayList();
fullKeyItems.add(prefix);
fullKeyItems.addAll(Arrays.asList(modules));
StringBuilder stringBuilder = StringUtil.newStringBuilder();
fullKeyItems.stream().filter(item -> StringUtil.isNotBlank(item)).forEach(item -> stringBuilder.append(item).append(StringConstant.Symbol.COLON));
stringBuilder.append(key);
return stringBuilder.toString();
}
}
19
View Source File : RedisAspect.java
License : MIT License
Project Creator : sika-code
License : MIT License
Project Creator : sika-code
/**
* <p>
* redis切面类
* </p>
*
* @author daiqi 创建时间 2018年4月12日 下午1:51:49
*/
@Aspect
@Order
// @Component
@Data
public clreplaced RedisAspect {
private RedisProxySelector redisProxySelector;
public RedisAspect(RedisProxySelector redisProxySelector) {
replacedert.verifyObjNull(redisProxySelector, "redis代理选择器:redisProxySelector");
this.redisProxySelector = redisProxySelector;
}
@Pointcut("@annotation(com.sika.code.cache.redis.annotation.RedisAnnotation)")
public void redisAspect() {
}
public void daoAspect() {
}
@Around(value = "redisAspect()")
public Object annotationAround(ProceedingJoinPoint joinPoint) {
return doAround(joinPoint);
}
public Object doAround(ProceedingJoinPoint joinPoint) {
RedisBO redisBO = new RedisBO();
redisBO.buildRedisData(joinPoint).buildRedisProxySelector(redisProxySelector);
return redisBO.handle();
}
}
19
View Source File : RocketMQAutoConfiguration.java
License : Apache License 2.0
Project Creator : rocketmq
License : Apache License 2.0
Project Creator : rocketmq
/**
* 自动化配置类
*
* @author He Jialin
*/
@Configuration
@EnableConfigurationProperties(RocketMQProperties.clreplaced)
@ConditionalOnClreplaced(MQClientAPIImpl.clreplaced)
@Order
public clreplaced RocketMQAutoConfiguration {
@Autowired
private RocketMQProperties rocketMQProperties;
@Bean
@ConditionalOnClreplaced(DefaultMQProducer.clreplaced)
@ConditionalOnMissingBean(DefaultMQProducer.clreplaced)
@ConditionalOnProperty(prefix = "spring.rocketmq", value = { "nameServer", "producer.group" })
public DefaultMQProducer mqProducer(RocketMQProperties rocketMQProperties) {
RocketMQProperties.Producer producerConfig = rocketMQProperties.getProducer();
String groupName = producerConfig.getGroup();
replacedert.hasText(groupName, "[spring.rocketmq.producer.group] must not be null");
DefaultMQProducer producer = new DefaultMQProducer(producerConfig.getGroup());
producer.setNamesrvAddr(rocketMQProperties.getNameServer());
producer.setSendMsgTimeout(producerConfig.getSendMsgTimeout());
producer.setRetryTimesWhenSendFailed(producerConfig.getRetryTimesWhenSendFailed());
producer.setRetryTimesWhenSendAsyncFailed(producerConfig.getRetryTimesWhenSendAsyncFailed());
producer.setMaxMessageSize(producerConfig.getMaxMessageSize());
producer.setCompressMsgBodyOverHowmuch(producerConfig.getCompressMsgBodyOverHowmuch());
producer.setRetryAnotherBrokerWhenNotStoreOK(producerConfig.isRetryAnotherBrokerWhenNotStoreOk());
return producer;
}
@Bean
@ConditionalOnMissingBean(SimpleListenerFactory.clreplaced)
public InitBeanFactory initBeanFactory() {
return new InitBeanFactory();
}
@Bean
@ConditionalOnMissingBean(MethodInvoker.clreplaced)
public MethodInvoker methodInvoker() {
return new MethodInvoker();
}
@Bean
@ConditionalOnMissingBean(RocketMQProducerContainer.clreplaced)
public RocketMQProducerContainer mqProducerContainer() {
return new RocketMQProducerContainer();
}
@Bean
@ConditionalOnMissingBean(RocketMQMessageListenerContainer.clreplaced)
public RocketMQMessageListenerContainer mqMessageListenerContainer() {
return new RocketMQMessageListenerContainer(rocketMQProperties.getNameServer());
}
}
19
View Source File : RocketMqAutoConfiguration.java
License : Apache License 2.0
Project Creator : rhwayfun
License : Apache License 2.0
Project Creator : rhwayfun
@Bean
@ConditionalOnMissingBean
@ConditionalOnBean(value = AbstractRocketMqConsumer.clreplaced)
@Order
public RocketMqConsumerMBean rocketMqConsumerMBean(List<AbstractRocketMqConsumer> messageListeners) {
RocketMqConsumerMBean rocketMqConsumerMBean = new RocketMqConsumerMBean();
messageListeners.forEach(this::registerMQConsumer);
rocketMqConsumerMBean.setConsumers(messageListeners);
return rocketMqConsumerMBean;
}
19
View Source File : SysLogListener.java
License : MIT License
Project Creator : rexlin600
License : MIT License
Project Creator : rexlin600
/**
* On application event *
*
* @param event event
*/
@Async
@Order
@EventListener
public void onApplicationEvent(SysLogEvent event) {
SysLog source = event.getSysLog();
log.info("==> 注解版本:处理监听事件参数:{}, 时间戳:{}", source.toString(), Instant.now().toEpochMilli());
// 模拟调用远程服务实现增加操作日志
remoteSysLogService.add(source);
}
19
View Source File : SysLogListener.java
License : GNU Lesser General Public License v3.0
Project Creator : renzl321
License : GNU Lesser General Public License v3.0
Project Creator : renzl321
@Async
@Order
@EventListener(SysLogEvent.clreplaced)
public void saveSysLog(SysLogEvent event) {
SysLog sysLog = (SysLog) event.getSource();
remoteLogService.saveLog(sysLog, SecurityConstants.FROM_IN);
}
19
View Source File : RocketMQAutoConfiguration.java
License : Apache License 2.0
Project Creator : QianmiOpen
License : Apache License 2.0
Project Creator : QianmiOpen
/**
* RocketMqAutoConfiguration Created by aqlu on 2017/9/27.
*/
@Configuration
@EnableConfigurationProperties(RocketMQProperties.clreplaced)
@ConditionalOnClreplaced(MQClientAPIImpl.clreplaced)
@Order
@Slf4j
public clreplaced RocketMQAutoConfiguration {
@Bean
@ConditionalOnClreplaced(DefaultMQProducer.clreplaced)
@ConditionalOnMissingBean(DefaultMQProducer.clreplaced)
@ConditionalOnProperty(prefix = "spring.rocketmq", value = { "name-server", "producer.group" })
public DefaultMQProducer mqProducer(RocketMQProperties rocketMQProperties) {
RocketMQProperties.Producer producerConfig = rocketMQProperties.getProducer();
String groupName = producerConfig.getGroup();
replacedert.hasText(groupName, "[spring.rocketmq.producer.group] must not be null");
DefaultMQProducer producer = new DefaultMQProducer(producerConfig.getGroup());
producer.setNamesrvAddr(rocketMQProperties.getNameServer());
producer.setSendMsgTimeout(producerConfig.getSendMsgTimeout());
producer.setRetryTimesWhenSendFailed(producerConfig.getRetryTimesWhenSendFailed());
producer.setRetryTimesWhenSendAsyncFailed(producerConfig.getRetryTimesWhenSendAsyncFailed());
producer.setMaxMessageSize(producerConfig.getMaxMessageSize());
producer.setCompressMsgBodyOverHowmuch(producerConfig.getCompressMsgBodyOverHowmuch());
producer.setRetryAnotherBrokerWhenNotStoreOK(producerConfig.isRetryAnotherBrokerWhenNotStoreOk());
return producer;
}
@Bean
@ConditionalOnClreplaced(ObjectMapper.clreplaced)
@ConditionalOnMissingBean(name = "rocketMQMessageObjectMapper")
public ObjectMapper rocketMQMessageObjectMapper() {
return new ObjectMapper();
}
@Bean(destroyMethod = "destroy")
@ConditionalOnBean(DefaultMQProducer.clreplaced)
@ConditionalOnMissingBean(name = "rocketMQTemplate")
public RocketMQTemplate rocketMQTemplate(DefaultMQProducer mqProducer, @Autowired(required = false) @Qualifier("rocketMQMessageObjectMapper") ObjectMapper objectMapper) {
RocketMQTemplate rocketMQTemplate = new RocketMQTemplate();
rocketMQTemplate.setProducer(mqProducer);
if (Objects.nonNull(objectMapper)) {
rocketMQTemplate.setObjectMapper(objectMapper);
}
return rocketMQTemplate;
}
@Configuration
@ConditionalOnClreplaced(DefaultMQPushConsumer.clreplaced)
@EnableConfigurationProperties(RocketMQProperties.clreplaced)
@ConditionalOnProperty(prefix = "spring.rocketmq", value = "name-server")
@Order
public static clreplaced ListenerContainerConfiguration implements ApplicationContextAware, InitializingBean {
private ConfigurableApplicationContext applicationContext;
private AtomicLong counter = new AtomicLong(0);
@Resource
private StandardEnvironment environment;
@Resource
private RocketMQProperties rocketMQProperties;
private ObjectMapper objectMapper;
public ListenerContainerConfiguration() {
}
@Autowired(required = false)
public ListenerContainerConfiguration(@Qualifier("rocketMQMessageObjectMapper") ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = (ConfigurableApplicationContext) applicationContext;
}
@Override
public void afterPropertiesSet() {
Map<String, Object> beans = this.applicationContext.getBeansWithAnnotation(RocketMQMessageListener.clreplaced);
if (Objects.nonNull(beans)) {
beans.forEach(this::registerContainer);
}
}
private void registerContainer(String beanName, Object bean) {
Clreplaced<?> clazz = AopUtils.getTargetClreplaced(bean);
if (!RocketMQListener.clreplaced.isreplacedignableFrom(bean.getClreplaced())) {
throw new IllegalStateException(clazz + " is not instance of " + RocketMQListener.clreplaced.getName());
}
RocketMQListener rocketMQListener = (RocketMQListener) bean;
RocketMQMessageListener annotation = clazz.getAnnotation(RocketMQMessageListener.clreplaced);
BeanDefinitionBuilder beanBuilder = BeanDefinitionBuilder.rootBeanDefinition(DefaultRocketMQListenerContainer.clreplaced);
beanBuilder.addPropertyValue(PROP_NAMESERVER, rocketMQProperties.getNameServer());
beanBuilder.addPropertyValue(PROP_TOPIC, environment.resolvePlaceholders(annotation.topic()));
beanBuilder.addPropertyValue(PROP_CONSUMER_GROUP, environment.resolvePlaceholders(annotation.consumerGroup()));
beanBuilder.addPropertyValue(PROP_CONSUME_MODE, annotation.consumeMode());
beanBuilder.addPropertyValue(PROP_CONSUME_THREAD_MAX, annotation.consumeThreadMax());
beanBuilder.addPropertyValue(PROP_MESSAGE_MODEL, annotation.messageModel());
beanBuilder.addPropertyValue(PROP_SELECTOR_EXPRESS, environment.resolvePlaceholders(annotation.selectorExpress()));
beanBuilder.addPropertyValue(PROP_SELECTOR_TYPE, annotation.selectorType());
beanBuilder.addPropertyValue(PROP_ROCKETMQ_LISTENER, rocketMQListener);
beanBuilder.addPropertyValue(PROP_PULL_THRESHOLD_FOR_TOPIC, annotation.pullThresholdForTopic());
beanBuilder.addPropertyValue(PROP_PULL_THRESHOLD_SIZE_FOR_TOPIC, annotation.pullThresholdSizeForTopic());
if (Objects.nonNull(objectMapper)) {
beanBuilder.addPropertyValue(PROP_OBJECT_MAPPER, objectMapper);
}
beanBuilder.setDestroyMethodName(METHOD_DESTROY);
String containerBeanName = String.format("%s_%s", DefaultRocketMQListenerContainer.clreplaced.getName(), counter.incrementAndGet());
DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) applicationContext.getBeanFactory();
beanFactory.registerBeanDefinition(containerBeanName, beanBuilder.getBeanDefinition());
DefaultRocketMQListenerContainer container = beanFactory.getBean(containerBeanName, DefaultRocketMQListenerContainer.clreplaced);
if (!container.isStarted()) {
try {
container.start();
} catch (Exception e) {
log.error("started container failed. {}", container, e);
throw new RuntimeException(e);
}
}
log.info("register rocketMQ listener to container, listenerBeanName:{}, containerBeanName:{}", beanName, containerBeanName);
}
}
}
19
View Source File : ReadOnlyModeFilter.java
License : Apache License 2.0
Project Creator : provectus
License : Apache License 2.0
Project Creator : provectus
@Order
@Component
@RequiredArgsConstructor
public clreplaced ReadOnlyModeFilter implements WebFilter {
private static final Pattern CLUSTER_NAME_REGEX = Pattern.compile("/api/clusters/(?<clusterName>[^/]++)");
private final ClustersStorage clustersStorage;
@NotNull
@Override
public Mono<Void> filter(ServerWebExchange exchange, @NotNull WebFilterChain chain) {
var isSafeMethod = exchange.getRequest().getMethod() == HttpMethod.GET;
if (isSafeMethod) {
return chain.filter(exchange);
}
var path = exchange.getRequest().getURI().getPath();
var matcher = CLUSTER_NAME_REGEX.matcher(path);
if (!matcher.find()) {
return chain.filter(exchange);
}
var clusterName = matcher.group("clusterName");
var kafkaCluster = clustersStorage.getClusterByName(clusterName).orElseThrow(() -> new NotFoundException(String.format("No cluster for name '%s'", clusterName)));
if (!kafkaCluster.getReadOnly()) {
return chain.filter(exchange);
}
return Mono.error(ReadOnlyException::new);
}
}
19
View Source File : StartupMigrator.java
License : MIT License
Project Creator : Plajer
License : MIT License
Project Creator : Plajer
/**
* @author Plajer
* <p>
* Created at 04.05.2020
*/
@Component
@Order
public clreplaced StartupMigrator {
public static final int FILE_VERSION = 2;
private final Logger logger = Logger.getLogger("Migrator");
private final UserRepository userRepository;
private int version = -1;
private File versionFile;
@Autowired
public StartupMigrator(UserRepository userRepository) {
this.userRepository = userRepository;
}
@PostConstruct
public void attemptMigration() {
versionFile = new File("storage-data" + File.separator + ".version");
try {
// migration never happened, create file and start migrating
if (!versionFile.exists()) {
versionFile.createNewFile();
version = 1;
doAttemptMigration();
return;
}
String content = new String(Files.readAllBytes(versionFile.toPath()), StandardCharsets.UTF_8);
version = parseIntOrDefault(content, FILE_VERSION);
} catch (IOException e) {
logger.log(Level.WARNING, "Failed to get version file contents! Migrator will not run.");
e.printStackTrace();
}
if (version == FILE_VERSION) {
return;
}
doAttemptMigration();
}
private void doAttemptMigration() {
for (int i = version; i < FILE_VERSION; i++) {
switch(i) {
case 1:
logger.log(Level.INFO, "Migrating Feedbacky from version 1 to 2...");
for (User user : userRepository.findAll()) {
if (user.getMailPreferences() != null) {
continue;
}
MailPreferences defaultPreferences = new MailPreferences();
defaultPreferences.setNotifyFromModeratorsComments(true);
defaultPreferences.setNotifyFromStatusChange(true);
defaultPreferences.setNotifyFromTagsChange(true);
defaultPreferences.setUnsubscribeToken(RandomStringUtils.randomAlphanumeric(6));
defaultPreferences.setUser(user);
user.setMailPreferences(defaultPreferences);
userRepository.save(user);
}
logger.log(Level.INFO, "Migrated to version 2.");
break;
case -1:
break;
}
}
saveMigrationFile();
}
private void saveMigrationFile() {
try (PrintStream out = new PrintStream(versionFile)) {
out.print(FILE_VERSION + "");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private int parseIntOrDefault(String string, int defaultValue) {
if (string.equals("")) {
return defaultValue;
}
try {
return Integer.parseInt(string);
} catch (Exception ex) {
return defaultValue;
}
}
}
19
View Source File : RestExceptionHandler.java
License : MIT License
Project Creator : PedroGao
License : MIT License
Project Creator : PedroGao
@SuppressWarnings("Duplicates")
@Order
@RestControllerAdvice
@Slf4j
public clreplaced RestExceptionHandler {
@Value("${spring.servlet.multipart.max-file-size:20M}")
private String maxFileSize;
/**
* HttpException
*/
@ExceptionHandler({ HttpException.clreplaced })
public UnifyResponseVO processException(HttpException exception, HttpServletRequest request, HttpServletResponse response) {
log.error("", exception);
UnifyResponseVO unifyResponse = new UnifyResponseVO();
unifyResponse.setRequest(getSimpleRequest(request));
int code = exception.getCode();
unifyResponse.setCode(code);
response.setStatus(exception.getHttpCode());
String errorMessage = CodeConfig.getMessage(code);
if (StrUtil.isBlank(errorMessage)) {
unifyResponse.setMessage(exception.getMessage());
} else {
unifyResponse.setMessage(errorMessage);
}
return unifyResponse;
}
/**
* ConstraintViolationException
*/
@ExceptionHandler({ ConstraintViolationException.clreplaced })
public UnifyResponseVO processException(ConstraintViolationException exception, HttpServletRequest request, HttpServletResponse response) {
log.error("", exception);
Map<String, Object> msg = new HashMap<>();
exception.getConstraintViolations().forEach(constraintViolation -> {
String template = constraintViolation.getMessageTemplate();
String path = constraintViolation.getPropertyPath().toString();
msg.put(path, template);
});
UnifyResponseVO unifyResponse = new UnifyResponseVO();
unifyResponse.setRequest(getSimpleRequest(request));
unifyResponse.setMessage(msg);
unifyResponse.setCode(Code.PARAMETER_ERROR.getCode());
response.setStatus(HttpStatus.BAD_REQUEST.value());
return unifyResponse;
}
/**
* NoHandlerFoundException
*/
@ExceptionHandler({ NoHandlerFoundException.clreplaced })
public UnifyResponseVO processException(NoHandlerFoundException exception, HttpServletRequest request, HttpServletResponse response) {
log.error("", exception);
UnifyResponseVO unifyResponse = new UnifyResponseVO();
unifyResponse.setRequest(getSimpleRequest(request));
String message = CodeConfig.getMessage(10025);
if (StrUtil.isBlank(message)) {
unifyResponse.setMessage(exception.getMessage());
} else {
unifyResponse.setMessage(message);
}
unifyResponse.setCode(Code.NOT_FOUND.getCode());
response.setStatus(HttpStatus.NOT_FOUND.value());
return unifyResponse;
}
/**
* MissingServletRequestParameterException
*/
@ExceptionHandler({ MissingServletRequestParameterException.clreplaced })
public UnifyResponseVO processException(MissingServletRequestParameterException exception, HttpServletRequest request, HttpServletResponse response) {
log.error("", exception);
UnifyResponseVO result = new UnifyResponseVO();
result.setRequest(getSimpleRequest(request));
String errorMessage = CodeConfig.getMessage(10150);
if (StrUtil.isBlank(errorMessage)) {
result.setMessage(exception.getMessage());
} else {
result.setMessage(errorMessage + exception.getParameterName());
}
result.setCode(Code.PARAMETER_ERROR.getCode());
response.setStatus(HttpStatus.BAD_REQUEST.value());
return result;
}
/**
* MethodArgumentTypeMismatchException
*/
@ExceptionHandler({ MethodArgumentTypeMismatchException.clreplaced })
public UnifyResponseVO processException(MethodArgumentTypeMismatchException exception, HttpServletRequest request, HttpServletResponse response) {
log.error("", exception);
UnifyResponseVO result = new UnifyResponseVO();
result.setRequest(getSimpleRequest(request));
String errorMessage = CodeConfig.getMessage(10160);
if (StrUtil.isBlank(errorMessage)) {
result.setMessage(exception.getMessage());
} else {
result.setMessage(exception.getValue() + errorMessage);
}
result.setCode(Code.PARAMETER_ERROR.getCode());
response.setStatus(HttpStatus.BAD_REQUEST.value());
return result;
}
/**
* ServletException
*/
@ExceptionHandler({ ServletException.clreplaced })
public UnifyResponseVO processException(ServletException exception, HttpServletRequest request, HttpServletResponse response) {
log.error("", exception);
UnifyResponseVO result = new UnifyResponseVO();
result.setRequest(getSimpleRequest(request));
result.setMessage(exception.getMessage());
result.setCode(Code.FAIL.getCode());
response.setStatus(HttpStatus.BAD_REQUEST.value());
return result;
}
/**
* MethodArgumentNotValidException
*/
@ExceptionHandler({ MethodArgumentNotValidException.clreplaced })
public UnifyResponseVO processException(MethodArgumentNotValidException exception, HttpServletRequest request, HttpServletResponse response) {
log.error("", exception);
BindingResult bindingResult = exception.getBindingResult();
List<ObjectError> errors = bindingResult.getAllErrors();
Map<String, Object> msg = new HashMap<>();
errors.forEach(error -> {
if (error instanceof FieldError) {
FieldError fieldError = (FieldError) error;
msg.put(fieldError.getField(), fieldError.getDefaultMessage());
} else {
msg.put(error.getObjectName(), error.getDefaultMessage());
}
});
UnifyResponseVO result = new UnifyResponseVO();
result.setRequest(getSimpleRequest(request));
result.setMessage(msg);
result.setCode(Code.PARAMETER_ERROR.getCode());
response.setStatus(HttpStatus.BAD_REQUEST.value());
return result;
}
/**
* HttpMessageNotReadableException
*/
@ExceptionHandler({ HttpMessageNotReadableException.clreplaced })
public UnifyResponseVO processException(HttpMessageNotReadableException exception, HttpServletRequest request, HttpServletResponse response) {
log.error("", exception);
UnifyResponseVO result = new UnifyResponseVO();
result.setRequest(getSimpleRequest(request));
String errorMessage = CodeConfig.getMessage(10170);
if (StrUtil.isBlank(errorMessage)) {
result.setMessage(exception.getMessage());
} else {
result.setMessage(errorMessage);
}
result.setCode(Code.PARAMETER_ERROR.getCode());
response.setStatus(HttpStatus.BAD_REQUEST.value());
return result;
}
/**
* TypeMismatchException
*/
@ExceptionHandler({ TypeMismatchException.clreplaced })
public UnifyResponseVO processException(TypeMismatchException exception, HttpServletRequest request, HttpServletResponse response) {
log.error("", exception);
UnifyResponseVO result = new UnifyResponseVO();
result.setRequest(getSimpleRequest(request));
result.setMessage(exception.getMessage());
result.setCode(Code.PARAMETER_ERROR.getCode());
response.setStatus(HttpStatus.BAD_REQUEST.value());
return result;
}
/**
* MaxUploadSizeExceededException
*/
@ExceptionHandler({ MaxUploadSizeExceededException.clreplaced })
public UnifyResponseVO processException(MaxUploadSizeExceededException exception, HttpServletRequest request, HttpServletResponse response) {
log.error("", exception);
UnifyResponseVO result = new UnifyResponseVO();
result.setRequest(getSimpleRequest(request));
String errorMessage = CodeConfig.getMessage(10180);
if (StrUtil.isBlank(errorMessage)) {
result.setMessage(exception.getMessage());
} else {
result.setMessage(errorMessage + maxFileSize);
}
result.setCode(Code.FILE_TOO_LARGE.getCode());
response.setStatus(HttpStatus.PAYLOAD_TOO_LARGE.value());
return result;
}
/**
* Exception
*/
@ExceptionHandler({ Exception.clreplaced })
public UnifyResponseVO processException(Exception exception, HttpServletRequest request, HttpServletResponse response) {
log.error("", exception);
UnifyResponseVO result = new UnifyResponseVO();
result.setRequest(getSimpleRequest(request));
result.setMessage(Code.INTERNAL_SERVER_ERROR.getZhDescription());
result.setCode(Code.INTERNAL_SERVER_ERROR.getCode());
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
return result;
}
}
19
View Source File : PcPermissionAuthorizeConfigProvider.java
License : Apache License 2.0
Project Creator : paascloud
License : Apache License 2.0
Project Creator : paascloud
/**
* The clreplaced Pc permission authorize config provider.
*
* @author paascloud.net @gmail.com
*/
@Order
@Component
public clreplaced PcPermissionAuthorizeConfigProvider implements AuthorizeConfigProvider {
/**
* Config boolean.
*
* @param config the config
*
* @return the boolean
*/
@Override
public boolean config(ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry config) {
config.anyRequest().access("@permissionService.hasPermission(authentication,request)");
return true;
}
}
19
View Source File : ZookeeperInitRunner.java
License : Apache License 2.0
Project Creator : paascloud
License : Apache License 2.0
Project Creator : paascloud
/**
* The clreplaced Redis init runner.
*
* @author paascloud.net @gmail.com
*/
@Component
@Order
@Slf4j
public clreplaced ZookeeperInitRunner implements CommandLineRunner {
@Resource
private PaascloudProperties paascloudProperties;
@Value("${spring.application.name}")
private String applicationName;
/**
* Run.
*
* @param args the args
*
* @throws Exception the exception
*/
@Override
public void run(String... args) throws Exception {
String hostAddress = InetAddress.getLocalHost().getHostAddress();
log.info("###ZookeeperInitRunner,init. HostAddress={}, applicationName={}", hostAddress, applicationName);
RegistryCenterFactory.startup(paascloudProperties, hostAddress, applicationName);
log.info("###ZookeeperInitRunner,finish<<<<<<<<<<<<<");
}
}
19
View Source File : WechatPayConfiguredCondition.java
License : Apache License 2.0
Project Creator : NotFound403
License : Apache License 2.0
Project Creator : NotFound403
/**
* The type Wechat pay configured condition.
*
* @author felord.cn
* @since 1.0.3.RELEASE
*/
@Order
public clreplaced WechatPayConfiguredCondition extends SpringBootCondition {
/**
* The constant STRING_WECHAT_V3_MAP.
*/
private static final Bindable<Map<String, WechatPayProperties.V3>> STRING_WECHAT_V3_MAP = Bindable.mapOf(String.clreplaced, WechatPayProperties.V3.clreplaced);
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
ConditionMessage.Builder message = ConditionMessage.forCondition("Wechat Pay V3 Configured Condition");
Map<String, WechatPayProperties.V3> v3 = getV3(context.getEnvironment());
if (!v3.isEmpty()) {
return ConditionOutcome.match(message.foundExactly("registered wechat mchIds " + v3.values().stream().map(WechatPayProperties.V3::getMchId).collect(Collectors.joining(", "))));
}
return ConditionOutcome.noMatch(message.notAvailable("registered wechat pay configs"));
}
private Map<String, WechatPayProperties.V3> getV3(Environment environment) {
return Binder.get(environment).bind("wechat.pay.v3", STRING_WECHAT_V3_MAP).orElse(Collections.emptyMap());
}
}
19
View Source File : DataSourceConfig.java
License : Apache License 2.0
Project Creator : niuzhiweimr
License : Apache License 2.0
Project Creator : niuzhiweimr
@Order
@Bean("sqlSessionTemplate")
public SqlSessionTemplate sqlSessiontemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionTemplate) {
return new SqlSessionTemplate(sqlSessionTemplate);
}
19
View Source File : DataSourceConfig.java
License : Apache License 2.0
Project Creator : niuzhiweimr
License : Apache License 2.0
Project Creator : niuzhiweimr
@Order
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactory(@Qualifier("dateSource") DataSource datasource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(datasource);
bean.setMapperLocations(// 设置mybatis的xml所在位置
new PathMatchingResourcePatternResolver().getResources("clreplacedpath:mappers/*.xml"));
return bean.getObject();
}
19
View Source File : DataSourceConfig.java
License : Apache License 2.0
Project Creator : niuzhiweimr
License : Apache License 2.0
Project Creator : niuzhiweimr
@Order
@Bean(name = "dateSource")
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource getDateSourceFirst() {
DruidDataSource druidDataSource = DataSourceBuilder.create().type(DruidDataSource.clreplaced).build();
druidDataSource.setRemoveAbandoned(Boolean.TRUE);
druidDataSource.setRemoveAbandonedTimeout(180);
druidDataSource.setLogAbandoned(Boolean.TRUE);
return druidDataSource;
}
19
View Source File : SwaggerAutoConfiguration.java
License : GNU General Public License v3.0
Project Creator : nancheung97
License : GNU General Public License v3.0
Project Creator : nancheung97
@Order
@Bean
public CommandLineRunner docAddressTip() {
return commandLineRunner -> {
if (log.isInfoEnabled()) {
String hostAddress = InetAddress.getLocalHost().getHostAddress();
String port = environment.getProperty("local.server.port");
log.info("接口文档地址:http://{}:{}/doc.html", hostAddress, port);
}
};
}
19
View Source File : DefaultExceptionHandlerResolver.java
License : GNU General Public License v3.0
Project Creator : nancheung97
License : GNU General Public License v3.0
Project Creator : nancheung97
/**
* 默认异常处理解析器
*
* @author NanCheung
*/
@Slf4j
@Order
@RestControllerAdvice
public clreplaced DefaultExceptionHandlerResolver {
/**
* 默认的异常处理
*
* @param e {@link Exception}
*/
@ExceptionHandler(Exception.clreplaced)
public ApiResult<Void> handleException(Exception e) {
log.error("未捕获的异常", e);
return ApiResult.failed(SystemExceptionIEnum.SYSTEM_ERROR, e.getLocalizedMessage());
}
}
19
View Source File : RegisterSystemListener.java
License : Apache License 2.0
Project Creator : myxzjie
License : Apache License 2.0
Project Creator : myxzjie
@Async
@Order
@EventListener(EmailEvent.clreplaced)
public void emailListener(EmailEvent event) {
MimeMessagePreparator mailMessage = mimeMessage -> {
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);
message.setFrom(from, fromName);
for (String to : event.getTos()) {
message.addTo(to);
}
message.setSubject(event.getSubject());
message.setText(event.getContent(), true);
// String html = "<html><body><h4>Hello,SpringBoot</h4><img src='cid:boot' /></body></html>";
// mimeMessageHelper.setText(html, true);
// 设置内嵌元素 cid,第一个参数表示内联图片的标识符,第二个参数标识资源引用
// mimeMessageHelper.addInline("boot", new ClreplacedPathResource("public/images/boot.png"));
// 添加附件,第一个参数表示添加到 Email 中附件的名称,第二个参数是图片资源
};
mailSender.send(mailMessage);
}
19
View Source File : RegisterSystemListener.java
License : Apache License 2.0
Project Creator : myxzjie
License : Apache License 2.0
Project Creator : myxzjie
@Async
@Order
@EventListener(SystemLogEvent.clreplaced)
public void systemLogListener(SystemLogEvent event) {
SystemLog log = (SystemLog) event.getSource();
log.setCreateDate(LocalDateTime.now());
// 保存
systemLogService.save(log);
}
19
View Source File : ReceiverIteratorImpl.java
License : Apache License 2.0
Project Creator : muxiangqiu
License : Apache License 2.0
Project Creator : muxiangqiu
/**
* @author Kevin Yang (mailto:[email protected])
* @since 2017年9月13日
*/
@Order
@Component
public clreplaced ReceiverIteratorImpl implements ReceiverIterator {
@Autowired
private GroupService groupService;
@Override
public void each(Notice notice, MemberProcessor memberProcessor) {
List<String> memberIds = groupService.getMemberIds(notice.getGroupId());
for (String memberId : memberIds) {
memberProcessor.process(memberId);
}
}
@Override
public boolean support(Notice notice) {
return Constants.MESSAGE_TYPE.equals(notice.getType());
}
}
19
View Source File : MessageReceiveSrategy.java
License : Apache License 2.0
Project Creator : muxiangqiu
License : Apache License 2.0
Project Creator : muxiangqiu
/**
* @author Kevin Yang (mailto:[email protected])
* @since 2017年9月13日
*/
@Order
@Component
public clreplaced MessageReceiveSrategy implements ReceiveStrategy {
@Autowired
private SocketSource<Socket> socketSource;
@Autowired
private Pusher<Socket> pusher;
@Autowired
private NoticeService noticeService;
@Autowired
private List<ReceiverIterator> receiverIterators;
@Override
public void apply(Notice notice) {
for (ReceiverIterator receiverIterator : receiverIterators) {
if (receiverIterator.support(notice)) {
receiverIterator.each(notice, memberId -> {
Socket socket = socketSource.getSocket(memberId);
if (socket != null) {
pusher.push(socket, notice);
}
});
}
}
noticeService.addNotice(notice);
}
@Override
public boolean support(Notice notice) {
if (Constants.MESSAGE_TYPE.equals(notice.getType()) && !notice.isAll()) {
return true;
}
return false;
}
}
19
View Source File : MarkReadReceiveSrategy.java
License : Apache License 2.0
Project Creator : muxiangqiu
License : Apache License 2.0
Project Creator : muxiangqiu
/**
* @author Kevin Yang (mailto:[email protected])
* @since 2017年9月13日
*/
@Order
@Component
public clreplaced MarkReadReceiveSrategy implements ReceiveStrategy {
@Autowired
private SocketSource<Socket> socketSource;
@Autowired
private Pusher<Socket> pusher;
@Autowired
private NoticeService noticeService;
@Override
public void apply(Notice notice) {
Socket socket = socketSource.getSocket(notice.getSender());
if (socket != null) {
pusher.push(socket, notice);
}
noticeService.markRead(notice.getGroupId(), notice.getSender());
;
}
@Override
public boolean support(Notice notice) {
if (Constants.MARK_READ_TYPE.equals(notice.getType())) {
return true;
}
return false;
}
}
19
View Source File : CoreApplicationRunner.java
License : Apache License 2.0
Project Creator : momobaiduren
License : Apache License 2.0
Project Creator : momobaiduren
/**
* 容器生命周期监听程序
*/
@Order
public clreplaced CoreApplicationRunner implements org.springframework.boot.ApplicationRunner {
@Override
public void run(ApplicationArguments var1) throws Exception {
saveStatus("STARTED");
}
private void saveStatus(String status) {
HashMap<String, Object> map = new HashMap<>(2);
map.put("data", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
map.put("state", status);
FileUtils.writeAllText("status", JsonUtils.serialize(map));
LogUtils.info(CoreApplicationRunner.clreplaced, CoreProperties.Project, "应用已正常启动!");
}
}
19
View Source File : AspectConfiguration.java
License : Apache License 2.0
Project Creator : mercyblitz
License : Apache License 2.0
Project Creator : mercyblitz
/**
* Aspect 配置类
*
* @author <a href="mailto:[email protected]">Mercy</a>
* @since
*/
@Aspect
@Order
public clreplaced AspectConfiguration {
// 匹配 Join Point
@Pointcut("execution(public * *(..))")
private void anyPublicMethod() {
// 方法名即 Pointcut 名
System.out.println("@Pointcut at any public method.");
}
// Join Point 拦截动作
@Around("anyPublicMethod()")
public Object aroundAnyPublicMethod(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("@Around any public method.");
return pjp.proceed();
}
// Join Point 拦截动作
@Before("anyPublicMethod()")
public void beforeAnyPublicMethod() throws Throwable {
Random random = new Random();
if (random.nextBoolean()) {
throw new RuntimeException("For Purpose.");
}
System.out.println("@Before any public method.");
}
@After("anyPublicMethod()")
public void finalizeAnyPublicMethod() {
System.out.println("@After any public method.");
}
@AfterReturning("anyPublicMethod()")
public // -> AbstractAspectJAdvice#invokeAdviceMethodWithGivenArgs
void afterAnyPublicMethod() {
System.out.println("@AfterReturning any public method.");
}
@AfterThrowing("anyPublicMethod()")
public void afterThrowingAnyPublicMethod() {
System.out.println("@AfterThrowing any public method");
}
public String toString() {
return "AspectConfiguration";
}
private int getValue() {
return 0;
}
}
19
View Source File : LogListener.java
License : Apache License 2.0
Project Creator : matevip
License : Apache License 2.0
Project Creator : matevip
@Async
@Order
@EventListener(LogEvent.clreplaced)
public void saveSysLog(LogEvent event) {
CommonLog commonLog = (CommonLog) event.getSource();
// 发送日志到kafka
log.info("发送日志:{}", commonLog);
if (logProperties.getLogType().equals(LogType.KAFKA)) {
commonLogProvider.sendCommonLog(commonLog);
} else {
sysLogProvider.set(commonLog);
}
}
19
View Source File : ApplicationRunnerImpl.java
License : MIT License
Project Creator : linj6
License : MIT License
Project Creator : linj6
/**
* @author lnj
* createTime 2018-11-07 22:37
*/
@Order
@Component
public clreplaced ApplicationRunnerImpl implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("通过实现ApplicationRunner接口,在spring boot项目启动后打印参数");
String[] sourceArgs = args.getSourceArgs();
for (String arg : sourceArgs) {
System.out.print(arg + " ");
}
System.out.println();
}
}
19
View Source File : CEKSDKInformationBinderResponseBodyAdvice.java
License : Apache License 2.0
Project Creator : line
License : Apache License 2.0
Project Creator : line
/**
* {@link ResponseBodyAdvice} that sets this SDK information in the response body.
*/
@RestControllerAdvice(annotations = { RestController.clreplaced, RestControllerAdvice.clreplaced })
@Order
@Slf4j
public clreplaced CEKSDKInformationBinderResponseBodyAdvice extends CEKResponseMessageBodyAbstractAdvice {
static final String CEK_SDK_NAME = "clova-cek-sdk-java";
@Override
public Object beforeBodyWrite(@Nullable Object body, MethodParameter returnType, MediaType selectedContentType, Clreplaced<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
CEKResponseMessage responseMessage = body != null ? (CEKResponseMessage) body : new CEKResponseMessage(CEKResponse.empty());
try {
return new CEKResponseMessageWrapper(responseMessage);
} catch (Throwable t) {
// nop
}
return body;
}
@Getter
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
static clreplaced CEKResponseMessageWrapper extends CEKResponseMessage {
private static final long serialVersionUID = 1L;
private final Meta meta;
CEKResponseMessageWrapper(CEKResponseMessage message) {
super(message.getResponse());
BeanUtils.copyProperties(message, this);
this.meta = Meta.builder().customExtensionSdk(CEK_SDK_NAME).customExtensionSdkVersion(ClovaExtensionBootVersion.getVersion()).build();
}
@Getter
@EqualsAndHashCode
@ToString
@Builder
static clreplaced Meta implements Serializable {
private static final long serialVersionUID = 1L;
private final String customExtensionSdk;
private final String customExtensionSdkVersion;
}
}
}
See More Examples