diff --git a/blade-core-boot/src/main/java/org/springblade/core/boot/config/BladeBootAutoConfiguration.java b/blade-core-boot/src/main/java/org/springblade/core/boot/config/BladeBootAutoConfiguration.java index 9f83284..ed71df9 100644 --- a/blade-core-boot/src/main/java/org/springblade/core/boot/config/BladeBootAutoConfiguration.java +++ b/blade-core-boot/src/main/java/org/springblade/core/boot/config/BladeBootAutoConfiguration.java @@ -24,52 +24,56 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; +/** + * 配置类 + * @author smallchill + */ @Slf4j @Configuration @EnableConfigurationProperties({ - BladeProperties.class + BladeProperties.class }) @EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true) @AllArgsConstructor public class BladeBootAutoConfiguration { - private BladeProperties bladeProperties; + private BladeProperties bladeProperties; - /** - * 全局变量定义 - */ - @Bean - public SystemConstant fileConst() { - SystemConstant me = SystemConstant.me(); + /** + * 全局变量定义 + */ + @Bean + public SystemConstant fileConst() { + SystemConstant me = SystemConstant.me(); - //设定开发模式 - me.setDevMode((bladeProperties.getEnv().equals("dev") ? true : false)); + //设定开发模式 + me.setDevMode((bladeProperties.getEnv().equals("dev") ? true : false)); - //设定文件上传远程地址 - me.setDomain(bladeProperties.get("upload-domain", "http://localhost:8888")); + //设定文件上传远程地址 + me.setDomain(bladeProperties.get("upload-domain", "http://localhost:8888")); - //设定文件上传是否为远程模式 - me.setRemoteMode(bladeProperties.getBoolean("remote-mode", true)); + //设定文件上传是否为远程模式 + me.setRemoteMode(bladeProperties.getBoolean("remote-mode", true)); - //远程上传地址 - me.setRemotePath(bladeProperties.get("remote-path", System.getProperty("user.dir") + "/work/blade")); + //远程上传地址 + me.setRemotePath(bladeProperties.get("remote-path", System.getProperty("user.dir") + "/work/blade")); - //设定文件上传头文件夹 - me.setUploadPath(bladeProperties.get("upload-path", "/upload")); + //设定文件上传头文件夹 + me.setUploadPath(bladeProperties.get("upload-path", "/upload")); - //设定文件下载头文件夹 - me.setDownloadPath(bladeProperties.get("download-path", "/download")); + //设定文件下载头文件夹 + me.setDownloadPath(bladeProperties.get("download-path", "/download")); - //设定上传图片是否压缩 - me.setCompress(bladeProperties.getBoolean("compress", false)); + //设定上传图片是否压缩 + me.setCompress(bladeProperties.getBoolean("compress", false)); - //设定上传图片压缩比例 - me.setCompressScale(bladeProperties.getDouble("compress-scale", 2.00)); + //设定上传图片压缩比例 + me.setCompressScale(bladeProperties.getDouble("compress-scale", 2.00)); - //设定上传图片缩放选择:true放大;false缩小 - me.setCompressFlag(bladeProperties.getBoolean("compress-flag", false)); + //设定上传图片缩放选择:true放大;false缩小 + me.setCompressFlag(bladeProperties.getBoolean("compress-flag", false)); - return me; - } + return me; + } } diff --git a/blade-core-boot/src/main/java/org/springblade/core/boot/config/BladeWebMvcConfiguration.java b/blade-core-boot/src/main/java/org/springblade/core/boot/config/BladeWebMvcConfiguration.java index a903150..5f86727 100644 --- a/blade-core-boot/src/main/java/org/springblade/core/boot/config/BladeWebMvcConfiguration.java +++ b/blade-core-boot/src/main/java/org/springblade/core/boot/config/BladeWebMvcConfiguration.java @@ -33,6 +33,7 @@ import java.util.List; /** * WEB配置 + * @author smallchill */ @Slf4j @Configuration @@ -40,10 +41,10 @@ import java.util.List; @Order(Ordered.HIGHEST_PRECEDENCE) public class BladeWebMvcConfiguration implements WebMvcConfigurer { - @Override - public void addArgumentResolvers(List argumentResolvers) { - argumentResolvers.add(new TokenArgumentResolver()); - } + @Override + public void addArgumentResolvers(List argumentResolvers) { + argumentResolvers.add(new TokenArgumentResolver()); + } @Bean @ConditionalOnMissingBean diff --git a/blade-core-boot/src/main/java/org/springblade/core/boot/config/MybatisPlusConfiguration.java b/blade-core-boot/src/main/java/org/springblade/core/boot/config/MybatisPlusConfiguration.java index 1ed3dce..d18b760 100644 --- a/blade-core-boot/src/main/java/org/springblade/core/boot/config/MybatisPlusConfiguration.java +++ b/blade-core-boot/src/main/java/org/springblade/core/boot/config/MybatisPlusConfiguration.java @@ -27,6 +27,8 @@ import org.springframework.context.annotation.Profile; /** * mybatisplus 配置 + * + * @author smallchill */ @Configuration @MapperScan("org.springblade.**.mapper.**") @@ -42,14 +44,14 @@ public class MybatisPlusConfiguration { return new BladeMetaObjectHandler(); } - /** - * SQL执行效率插件 - */ - @Bean - @Profile({AppConstant.DEV_CDOE, AppConstant.TEST_CODE}) - public PerformanceInterceptor performanceInterceptor() { - return new PerformanceInterceptor(); - } + /** + * SQL执行效率插件 + */ + @Bean + @Profile({AppConstant.DEV_CDOE, AppConstant.TEST_CODE}) + public PerformanceInterceptor performanceInterceptor() { + return new PerformanceInterceptor(); + } } diff --git a/blade-core-boot/src/main/java/org/springblade/core/boot/config/RedisTemplateConfiguration.java b/blade-core-boot/src/main/java/org/springblade/core/boot/config/RedisTemplateConfiguration.java index a1ee36f..5ff6f04 100644 --- a/blade-core-boot/src/main/java/org/springblade/core/boot/config/RedisTemplateConfiguration.java +++ b/blade-core-boot/src/main/java/org/springblade/core/boot/config/RedisTemplateConfiguration.java @@ -35,6 +35,8 @@ import java.time.Duration; /** * RedisTemplate 配置 + * + * @author smallchill */ @EnableCaching @Configuration @@ -43,6 +45,7 @@ public class RedisTemplateConfiguration { /** * value 值 序列化 + * * @return RedisSerializer */ @Bean diff --git a/blade-core-boot/src/main/java/org/springblade/core/boot/config/RetryConfiguration.java b/blade-core-boot/src/main/java/org/springblade/core/boot/config/RetryConfiguration.java index bd825b5..25bb92c 100644 --- a/blade-core-boot/src/main/java/org/springblade/core/boot/config/RetryConfiguration.java +++ b/blade-core-boot/src/main/java/org/springblade/core/boot/config/RetryConfiguration.java @@ -24,23 +24,25 @@ import org.springframework.retry.interceptor.RetryOperationsInterceptor; /** * 重试机制 + * + * @author smallchill */ @Slf4j @Configuration public class RetryConfiguration { - @Bean - @ConditionalOnMissingBean(name = "configServerRetryInterceptor") - public RetryOperationsInterceptor configServerRetryInterceptor() { - log.info(String.format( - "configServerRetryInterceptor: Changing backOffOptions " + - "to initial: %s, multiplier: %s, maxInterval: %s", - 1000, 1.2, 5000)); - return RetryInterceptorBuilder - .stateless() - .backOffOptions(1000, 1.2, 5000) - .maxAttempts(10) - .build(); - } + @Bean + @ConditionalOnMissingBean(name = "configServerRetryInterceptor") + public RetryOperationsInterceptor configServerRetryInterceptor() { + log.info(String.format( + "configServerRetryInterceptor: Changing backOffOptions " + + "to initial: %s, multiplier: %s, maxInterval: %s", + 1000, 1.2, 5000)); + return RetryInterceptorBuilder + .stateless() + .backOffOptions(1000, 1.2, 5000) + .maxAttempts(10) + .build(); + } } diff --git a/blade-core-boot/src/main/java/org/springblade/core/boot/ctrl/BladeController.java b/blade-core-boot/src/main/java/org/springblade/core/boot/ctrl/BladeController.java index 8d18015..621c72b 100644 --- a/blade-core-boot/src/main/java/org/springblade/core/boot/ctrl/BladeController.java +++ b/blade-core-boot/src/main/java/org/springblade/core/boot/ctrl/BladeController.java @@ -33,177 +33,179 @@ import java.util.List; /** * Blade控制器封装类 + * + * @author smallchill */ public class BladeController { - /** - * ============================ BINDER ================================================= - */ + /** + * ============================ BINDER ================================================= + */ - @InitBinder - protected void initBinder(ServletRequestDataBinder binder) { - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - dateFormat.setLenient(false); - binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); - } + @InitBinder + protected void initBinder(ServletRequestDataBinder binder) { + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + dateFormat.setLenient(false); + binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); + } - /** - * ============================ REQUEST ================================================= - */ + /** + * ============================ REQUEST ================================================= + */ - @Autowired - private HttpServletRequest request; + @Autowired + private HttpServletRequest request; - /** - * 获取request - */ - public HttpServletRequest getRequest() { - return this.request; - } + /** + * 获取request + */ + public HttpServletRequest getRequest() { + return this.request; + } - /** - * 获取当前用户 - * - * @return - */ - public BladeUser getUser() { - return SecureUtil.getUser(); - } + /** + * 获取当前用户 + * + * @return + */ + public BladeUser getUser() { + return SecureUtil.getUser(); + } - /** ============================ API_RESULT ================================================= */ + /** ============================ API_RESULT ================================================= */ - /** - * 返回ApiResult - * - * @param data - * @return R - */ - public R data(T data) { - return R.data(data); - } + /** + * 返回ApiResult + * + * @param data + * @return R + */ + public R data(T data) { + return R.data(data); + } - /** - * 返回ApiResult - * - * @param data - * @param message - * @return R - */ - public R data(T data, String message) { - return R.data(data, message); - } + /** + * 返回ApiResult + * + * @param data + * @param message + * @return R + */ + public R data(T data, String message) { + return R.data(data, message); + } - /** - * 返回ApiResult - * - * @param data - * @param message - * @param code - * @return R - */ - public R data(T data, String message, int code) { - return R.data(code, data, message); - } + /** + * 返回ApiResult + * + * @param data + * @param message + * @param code + * @return R + */ + public R data(T data, String message, int code) { + return R.data(code, data, message); + } - /** - * 返回ApiResult - * - * @param message - * @return R - */ - public R success(String message) { - return R.success(message); - } + /** + * 返回ApiResult + * + * @param message + * @return R + */ + public R success(String message) { + return R.success(message); + } - /** - * 返回ApiResult - * - * @param message - * @return R - */ - public R failure(String message) { - return R.failure(message); - } + /** + * 返回ApiResult + * + * @param message + * @return R + */ + public R failure(String message) { + return R.failure(message); + } - /** - * 返回ApiResult - * - * @param flag - * @return R - */ - public R status(boolean flag) { - return R.status(flag); - } + /** + * 返回ApiResult + * + * @param flag + * @return R + */ + public R status(boolean flag) { + return R.status(flag); + } - /**============================ FILE ================================================= */ + /**============================ FILE ================================================= */ - /** - * 获取BladeFile封装类 - * - * @param file - * @return - */ - public BladeFile getFile(MultipartFile file) { - return BladeFileUtil.getFile(file); - } + /** + * 获取BladeFile封装类 + * + * @param file + * @return + */ + public BladeFile getFile(MultipartFile file) { + return BladeFileUtil.getFile(file); + } - /** - * 获取BladeFile封装类 - * - * @param file - * @param dir - * @return - */ - public BladeFile getFile(MultipartFile file, String dir) { - return BladeFileUtil.getFile(file, dir); - } + /** + * 获取BladeFile封装类 + * + * @param file + * @param dir + * @return + */ + public BladeFile getFile(MultipartFile file, String dir) { + return BladeFileUtil.getFile(file, dir); + } - /** - * 获取BladeFile封装类 - * - * @param file - * @param dir - * @param path - * @param virtualPath - * @return - */ - public BladeFile getFile(MultipartFile file, String dir, String path, String virtualPath) { - return BladeFileUtil.getFile(file, dir, path, virtualPath); - } + /** + * 获取BladeFile封装类 + * + * @param file + * @param dir + * @param path + * @param virtualPath + * @return + */ + public BladeFile getFile(MultipartFile file, String dir, String path, String virtualPath) { + return BladeFileUtil.getFile(file, dir, path, virtualPath); + } - /** - * 获取BladeFile封装类 - * - * @param files - * @return - */ - public List getFiles(List files) { - return BladeFileUtil.getFiles(files); - } + /** + * 获取BladeFile封装类 + * + * @param files + * @return + */ + public List getFiles(List files) { + return BladeFileUtil.getFiles(files); + } - /** - * 获取BladeFile封装类 - * - * @param files - * @param dir - * @return - */ - public List getFiles(List files, String dir) { - return BladeFileUtil.getFiles(files, dir); - } + /** + * 获取BladeFile封装类 + * + * @param files + * @param dir + * @return + */ + public List getFiles(List files, String dir) { + return BladeFileUtil.getFiles(files, dir); + } - /** - * 获取BladeFile封装类 - * - * @param files - * @param path - * @param virtualPath - * @return - */ - public List getFiles(List files, String dir, String path, String virtualPath) { - return BladeFileUtil.getFiles(files, dir, path, virtualPath); - } + /** + * 获取BladeFile封装类 + * + * @param files + * @param path + * @param virtualPath + * @return + */ + public List getFiles(List files, String dir, String path, String virtualPath) { + return BladeFileUtil.getFiles(files, dir, path, virtualPath); + } } diff --git a/blade-core-boot/src/main/java/org/springblade/core/boot/feign/BladeFeignRequestHeaderInterceptor.java b/blade-core-boot/src/main/java/org/springblade/core/boot/feign/BladeFeignRequestHeaderInterceptor.java index b1168df..bb3d9e8 100644 --- a/blade-core-boot/src/main/java/org/springblade/core/boot/feign/BladeFeignRequestHeaderInterceptor.java +++ b/blade-core-boot/src/main/java/org/springblade/core/boot/feign/BladeFeignRequestHeaderInterceptor.java @@ -26,6 +26,8 @@ import java.util.Enumeration; /** * feign 传递Request header + * + * @author smallchill */ @Slf4j public class BladeFeignRequestHeaderInterceptor implements RequestInterceptor { @@ -40,16 +42,10 @@ public class BladeFeignRequestHeaderInterceptor implements RequestInterceptor { while (headerNames.hasMoreElements()) { String name = headerNames.nextElement(); String value = request.getHeader(name); - /** - * 遍历请求头里面的属性字段,将Authorization添加到新的请求头中转发到下游服务 - * */ if ("Authorization".equals(name)) { - log.debug("添加自定义请求头key:" + name + ",value:" + value); requestTemplate.header(name, value); } } - } else { - log.warn("FeignHeadConfiguration", "获取请求头失败!"); } } } diff --git a/blade-core-boot/src/main/java/org/springblade/core/boot/feign/FeignHystrixConcurrencyStrategy.java b/blade-core-boot/src/main/java/org/springblade/core/boot/feign/FeignHystrixConcurrencyStrategy.java index 5db1400..e9e102a 100644 --- a/blade-core-boot/src/main/java/org/springblade/core/boot/feign/FeignHystrixConcurrencyStrategy.java +++ b/blade-core-boot/src/main/java/org/springblade/core/boot/feign/FeignHystrixConcurrencyStrategy.java @@ -38,6 +38,8 @@ import java.util.concurrent.TimeUnit; /** * 自定义Feign的隔离策略 + * + * @author smallchill */ public class FeignHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy { diff --git a/blade-core-boot/src/main/java/org/springblade/core/boot/file/BladeFile.java b/blade-core-boot/src/main/java/org/springblade/core/boot/file/BladeFile.java index 429f242..27926ac 100644 --- a/blade-core-boot/src/main/java/org/springblade/core/boot/file/BladeFile.java +++ b/blade-core-boot/src/main/java/org/springblade/core/boot/file/BladeFile.java @@ -23,44 +23,48 @@ import java.io.File; import java.io.IOException; import java.util.Date; +/** + * 上传文件封装 + * @author smallchill + */ public class BladeFile { /** * 上传文件在附件表中的id */ private Object fileId; - + /** * 上传文件 */ private MultipartFile file; - + /** * 上传分类文件夹 */ private String dir; - + /** * 上传物理路径 */ private String uploadPath; - + /** * 上传虚拟路径 */ private String uploadVirtualPath; - + /** * 文件名 */ private String fileName; - + /** * 真实文件名 */ private String originalFileName; public BladeFile() { - + } public BladeFile(MultipartFile file, String dir) { @@ -74,55 +78,57 @@ public class BladeFile { public BladeFile(MultipartFile file, String dir, String uploadPath, String uploadVirtualPath) { this(file, dir); - if (null != uploadPath){ + if (null != uploadPath) { this.uploadPath = BladeFileUtil.formatUrl(uploadPath); this.uploadVirtualPath = BladeFileUtil.formatUrl(uploadVirtualPath); } } - /** + /** * 图片上传 - */ + */ public void transfer() { transfer(SystemConstant.me().isCompress()); } - /** + /** * 图片上传 + * * @param compress 是否压缩 - */ + */ public void transfer(boolean compress) { IFileProxy fileFactory = FileProxyManager.me().getDefaultFileProxyFactory(); this.transfer(fileFactory, compress); } - - /** + + /** * 图片上传 + * * @param fileFactory 文件上传工厂类 - * @param compress 是否压缩 - */ + * @param compress 是否压缩 + */ public void transfer(IFileProxy fileFactory, boolean compress) { try { File file = new File(uploadPath); - - if(null != fileFactory){ - String [] path = fileFactory.path(file, dir); + + if (null != fileFactory) { + String[] path = fileFactory.path(file, dir); this.uploadPath = path[0]; this.uploadVirtualPath = path[1]; file = fileFactory.rename(file, path[0]); } - + File pfile = file.getParentFile(); if (!pfile.exists()) { pfile.mkdirs(); } - + this.file.transferTo(file); - + if (compress) { - fileFactory.compress(this.uploadPath); + fileFactory.compress(this.uploadPath); } - + } catch (IllegalStateException | IOException e) { e.printStackTrace(); } diff --git a/blade-core-boot/src/main/java/org/springblade/core/boot/file/BladeFileProxyFactory.java b/blade-core-boot/src/main/java/org/springblade/core/boot/file/BladeFileProxyFactory.java index 2f5be0f..1236818 100644 --- a/blade-core-boot/src/main/java/org/springblade/core/boot/file/BladeFileProxyFactory.java +++ b/blade-core-boot/src/main/java/org/springblade/core/boot/file/BladeFileProxyFactory.java @@ -18,12 +18,18 @@ package org.springblade.core.boot.file; import org.springblade.core.tool.constant.SystemConstant; import org.springblade.core.tool.date.DateUtil; import org.springblade.core.tool.utils.ImageUtil; +import org.springblade.core.tool.utils.StringPool; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.util.Date; +/** + * 文件代理类 + * + * @author smallchill + */ public class BladeFileProxyFactory implements IFileProxy { @Override @@ -34,55 +40,59 @@ public class BladeFileProxyFactory implements IFileProxy { } @Override - public String [] path(File f, String dir) { + public String[] path(File f, String dir) { //避免网络延迟导致时间不同步 long time = System.nanoTime(); - + StringBuilder uploadPath = new StringBuilder() - .append(getFileDir(dir, SystemConstant.me().getUploadRealPath())) - .append(time) - .append(getFileExt(f.getName())); - + .append(getFileDir(dir, SystemConstant.me().getUploadRealPath())) + .append(time) + .append(getFileExt(f.getName())); + StringBuilder virtualPath = new StringBuilder() - .append(getFileDir(dir, SystemConstant.me().getUploadCtxPath())) - .append(time) - .append(getFileExt(f.getName())); - - return new String [] {BladeFileUtil.formatUrl(uploadPath.toString()), BladeFileUtil.formatUrl(virtualPath.toString())}; + .append(getFileDir(dir, SystemConstant.me().getUploadCtxPath())) + .append(time) + .append(getFileExt(f.getName())); + + return new String[]{BladeFileUtil.formatUrl(uploadPath.toString()), BladeFileUtil.formatUrl(virtualPath.toString())}; } - + /** * 获取文件后缀 */ public static String getFileExt(String fileName) { - if (fileName.indexOf(".") == -1) + if (!fileName.contains(StringPool.DOT)) { return ".jpg"; - else - return fileName.substring(fileName.lastIndexOf('.'), fileName.length()); + } else { + return fileName.substring(fileName.lastIndexOf(StringPool.DOT)); + } } /** * 获取文件保存地址 + * * @param saveDir * @return */ public static String getFileDir(String dir, String saveDir) { StringBuilder newFileDir = new StringBuilder(); newFileDir.append(saveDir) - .append(File.separator).append(dir).append(File.separator).append(DateUtil.format(new Date(), "yyyyMMdd")) - .append(File.separator); + .append(File.separator).append(dir).append(File.separator).append(DateUtil.format(new Date(), "yyyyMMdd")) + .append(File.separator); return newFileDir.toString(); } /** * 图片压缩 + * * @param path 文件地址 * @return */ + @Override public void compress(String path) { try { - ImageUtil.zoomScale(ImageUtil.readImage(path), new FileOutputStream(new File(path)), null, SystemConstant.me().getCompressScale(), SystemConstant.me().isCompressFlag()); + ImageUtil.zoomScale(ImageUtil.readImage(path), new FileOutputStream(new File(path)), null, SystemConstant.me().getCompressScale(), SystemConstant.me().isCompressFlag()); } catch (FileNotFoundException e) { e.printStackTrace(); } diff --git a/blade-core-boot/src/main/java/org/springblade/core/boot/file/BladeFileUtil.java b/blade-core-boot/src/main/java/org/springblade/core/boot/file/BladeFileUtil.java index e1aa2f2..bdbaed5 100644 --- a/blade-core-boot/src/main/java/org/springblade/core/boot/file/BladeFileUtil.java +++ b/blade-core-boot/src/main/java/org/springblade/core/boot/file/BladeFileUtil.java @@ -20,12 +20,22 @@ import org.springframework.web.multipart.MultipartFile; import java.util.*; +/** + * 文件工具类 + * + * @author smallchill + */ public class BladeFileUtil { - // 定义允许上传的文件扩展名 + /** + * 定义允许上传的文件扩展名 + */ private static HashMap extMap = new HashMap(); - // 图片扩展名 - private static String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png", "bmp" }; + + /** + * 图片扩展名 + */ + private static String[] fileTypes = new String[]{"gif", "jpg", "jpeg", "png", "bmp"}; static { extMap.put("image", ".gif,.jpg,.jpeg,.png,.bmp,.JPG,.JPEG,.PNG"); @@ -34,21 +44,21 @@ public class BladeFileUtil { extMap.put("file", ".doc,.docx,.xls,.xlsx,.ppt,.htm,.html,.txt,.zip,.rar,.gz,.bz2"); extMap.put("allfile", ".gif,.jpg,.jpeg,.png,.bmp,.swf,.flv,.mp3,.mp4,.wav,.wma,.wmv,.mid,.avi,.mpg,.asf,.rm,.rmvb,.doc,.docx,.xls,.xlsx,.ppt,.htm,.html,.txt,.zip,.rar,.gz,.bz2"); } - + /** * 获取文件后缀 - * - * @param @param fileName + * + * @param @param fileName * @param @return 设定文件 * @return String 返回类型 */ public static String getFileExt(String fileName) { return fileName.substring(fileName.lastIndexOf('.'), fileName.length()); } - + /** * 测试文件后缀 只让指定后缀的文件上传,像jsp,war,sh等危险的后缀禁止 - * + * * @return */ public static boolean testExt(String dir, String fileName) { @@ -67,7 +77,12 @@ public class BladeFileUtil { public enum FileSort { size, type, name; - // 文本排序转换成枚举 + /** + * 文本排序转换成枚举 + * + * @param sort + * @return + */ public static FileSort of(String sort) { try { return FileSort.valueOf(sort); @@ -78,6 +93,7 @@ public class BladeFileUtil { } public static class NameComparator implements Comparator { + @Override public int compare(Object a, Object b) { Hashtable hashA = (Hashtable) a; Hashtable hashB = (Hashtable) b; @@ -92,6 +108,7 @@ public class BladeFileUtil { } public static class SizeComparator implements Comparator { + @Override public int compare(Object a, Object b) { Hashtable hashA = (Hashtable) a; Hashtable hashB = (Hashtable) b; @@ -112,6 +129,7 @@ public class BladeFileUtil { } public static class TypeComparator implements Comparator { + @Override public int compare(Object a, Object b) { Hashtable hashA = (Hashtable) a; Hashtable hashB = (Hashtable) b; @@ -128,70 +146,76 @@ public class BladeFileUtil { public static String formatUrl(String url) { return url.replaceAll("\\\\", "/"); } - - + + /********************************BladeFile封装********************************************************/ - + /** * 获取BladeFile封装类 + * * @param file * @return */ - public static BladeFile getFile(MultipartFile file){ + public static BladeFile getFile(MultipartFile file) { return getFile(file, "image", null, null); } - + /** * 获取BladeFile封装类 + * * @param file * @param dir * @return */ - public static BladeFile getFile(MultipartFile file, String dir){ + public static BladeFile getFile(MultipartFile file, String dir) { return getFile(file, dir, null, null); } - + /** * 获取BladeFile封装类 + * * @param file * @param dir * @param path * @param virtualPath * @return */ - public static BladeFile getFile(MultipartFile file, String dir, String path, String virtualPath){ + public static BladeFile getFile(MultipartFile file, String dir, String path, String virtualPath) { return new BladeFile(file, dir, path, virtualPath); } - + /** * 获取BladeFile封装类 + * * @param files * @return */ - public static List getFiles(List files){ + public static List getFiles(List files) { return getFiles(files, "image", null, null); } - + /** * 获取BladeFile封装类 + * * @param files * @param dir * @return */ - public static List getFiles(List files, String dir){ + public static List getFiles(List files, String dir) { return getFiles(files, dir, null, null); } - + /** * 获取BladeFile封装类 + * * @param files * @param path * @param virtualPath * @return */ - public static List getFiles(List files, String dir, String path, String virtualPath){ + public static List getFiles(List files, String dir, String path, String virtualPath) { List list = new ArrayList<>(); - for (MultipartFile file : files){ + for (MultipartFile file : files) { list.add(new BladeFile(file, dir, path, virtualPath)); } return list; diff --git a/blade-core-boot/src/main/java/org/springblade/core/boot/file/FileMaker.java b/blade-core-boot/src/main/java/org/springblade/core/boot/file/FileMaker.java deleted file mode 100644 index 81726ee..0000000 --- a/blade-core-boot/src/main/java/org/springblade/core/boot/file/FileMaker.java +++ /dev/null @@ -1,209 +0,0 @@ -/** - * Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com). - *

- * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE; - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

- * http://www.gnu.org/licenses/lgpl.html - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springblade.core.boot.file; - - -import org.springblade.core.tool.utils.StringUtil; -import org.springblade.core.tool.utils.StringPool; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.*; - -public class FileMaker { - private static final String DEFAULT_CONTENT_TYPE = "application/octet-stream"; - - private File file; - - private String fileName; - - private HttpServletRequest request; - - private HttpServletResponse response; - - public static FileMaker init(HttpServletRequest request, HttpServletResponse response, File file) { - return new FileMaker(request, response, file); - } - - public static FileMaker init(HttpServletRequest request, HttpServletResponse response, File file, String fileName) { - return new FileMaker(request, response, file, fileName); - } - - private FileMaker(HttpServletRequest request, HttpServletResponse response, File file) { - if (file == null) { - throw new IllegalArgumentException("file can not be null."); - } - this.file = file; - this.request = request; - this.response = response; - this.fileName = file.getName(); - } - - private FileMaker(HttpServletRequest request, HttpServletResponse response, File file, String fileName) { - if (file == null) { - throw new IllegalArgumentException("file can not be null."); - } - this.file = file; - this.request = request; - this.response = response; - this.fileName = fileName; - } - - public void start() { - if (file == null || !file.isFile()) { - throw new RuntimeException(); - } - - // --------- - response.setHeader("Accept-Ranges", "bytes"); - response.setHeader("Content-disposition", "attachment; filename=" + encodeFileName(fileName)); - response.setContentType(DEFAULT_CONTENT_TYPE); - - // --------- - if (StringUtil.isBlank(request.getHeader("Range"))) - normalStart(); - else - rangeStart(); - } - - private String encodeFileName(String fileName) { - try { - return new String(fileName.getBytes(StringPool.GBK), StringPool.ISO_8859_1); - } catch (UnsupportedEncodingException e) { - return fileName; - } - } - - private void normalStart() { - response.setHeader("Content-Length", String.valueOf(file.length())); - InputStream inputStream = null; - OutputStream outputStream = null; - try { - inputStream = new BufferedInputStream(new FileInputStream(file)); - outputStream = response.getOutputStream(); - byte[] buffer = new byte[1024]; - for (int len = -1; (len = inputStream.read(buffer)) != -1;) { - outputStream.write(buffer, 0, len); - } - outputStream.flush(); - } - catch (IOException e) { - throw new RuntimeException(e); - } - catch (Exception e) { - throw new RuntimeException(e); - } - finally { - if (inputStream != null) - try {inputStream.close();} catch (IOException e) {} - if (outputStream != null) - try {outputStream.close();} catch (IOException e) {} - } - } - - private void rangeStart() { - Long[] range = {null, null}; - processRange(range); - - String contentLength = String.valueOf(range[1].longValue() - range[0].longValue() + 1); - response.setHeader("Content-Length", contentLength); - response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // status = 206 - - // Content-Range: bytes 0-499/10000 - StringBuilder contentRange = new StringBuilder("bytes ").append(String.valueOf(range[0])).append("-").append(String.valueOf(range[1])).append("/").append(String.valueOf(file.length())); - response.setHeader("Content-Range", contentRange.toString()); - - InputStream inputStream = null; - OutputStream outputStream = null; - try { - long start = range[0]; - long end = range[1]; - inputStream = new BufferedInputStream(new FileInputStream(file)); - if (inputStream.skip(start) != start) - throw new RuntimeException("File skip error"); - outputStream = response.getOutputStream(); - byte[] buffer = new byte[1024]; - long position = start; - for (int len; position <= end && (len = inputStream.read(buffer)) != -1;) { - if (position + len <= end) { - outputStream.write(buffer, 0, len); - position += len; - } - else { - for (int i=0; i= fileLength) - range[i] = fileLength - 1; - } - } - - // Range format like: 9500- - if (range[0] != null && range[1] == null) { - range[1] = fileLength - 1; - } - // Range format like: -500 - else if (range[0] == null && range[1] != null) { - range[0] = fileLength - range[1]; - range[1] = fileLength - 1; - } - - // check final range - if (range[0] == null || range[1] == null || range[0].longValue() > range[1].longValue()) - throw new RuntimeException("Range error"); - } -} diff --git a/blade-core-boot/src/main/java/org/springblade/core/boot/file/FileProxyManager.java b/blade-core-boot/src/main/java/org/springblade/core/boot/file/FileProxyManager.java index a284684..1112057 100644 --- a/blade-core-boot/src/main/java/org/springblade/core/boot/file/FileProxyManager.java +++ b/blade-core-boot/src/main/java/org/springblade/core/boot/file/FileProxyManager.java @@ -17,29 +17,34 @@ package org.springblade.core.boot.file; import java.io.File; +/** + * 文件管理类 + * + * @author smallchill + */ public class FileProxyManager { - private IFileProxy defaultFileProxyFactory = new BladeFileProxyFactory(); + private IFileProxy defaultFileProxyFactory = new BladeFileProxyFactory(); - private static FileProxyManager me = new FileProxyManager(); + private static FileProxyManager me = new FileProxyManager(); - public static FileProxyManager me() { - return me; - } + public static FileProxyManager me() { + return me; + } - public IFileProxy getDefaultFileProxyFactory() { - return defaultFileProxyFactory; - } + public IFileProxy getDefaultFileProxyFactory() { + return defaultFileProxyFactory; + } - public void setDefaultFileProxyFactory(IFileProxy defaultFileProxyFactory) { - this.defaultFileProxyFactory = defaultFileProxyFactory; - } + public void setDefaultFileProxyFactory(IFileProxy defaultFileProxyFactory) { + this.defaultFileProxyFactory = defaultFileProxyFactory; + } - public String[] path(File file, String dir) { - return defaultFileProxyFactory.path(file, dir); - } + public String[] path(File file, String dir) { + return defaultFileProxyFactory.path(file, dir); + } - public File rename(File file, String path) { - return defaultFileProxyFactory.rename(file, path); - } + public File rename(File file, String path) { + return defaultFileProxyFactory.rename(file, path); + } } diff --git a/blade-core-boot/src/main/java/org/springblade/core/boot/file/IFileProxy.java b/blade-core-boot/src/main/java/org/springblade/core/boot/file/IFileProxy.java index 2162cbb..a79891a 100644 --- a/blade-core-boot/src/main/java/org/springblade/core/boot/file/IFileProxy.java +++ b/blade-core-boot/src/main/java/org/springblade/core/boot/file/IFileProxy.java @@ -17,27 +17,36 @@ package org.springblade.core.boot.file; import java.io.File; +/** + * 文件代理接口 + * + * @author smallchill + */ public interface IFileProxy { - + /** * 返回路径[物理路径][虚拟路径] + * * @param file * @param dir * @return */ - String [] path(File file, String dir); + String[] path(File file, String dir); /** * 文件重命名策略 + * * @param file * @param path * @return */ File rename(File file, String path); - - /** + + /** * 图片压缩 - */ + * + * @param path + */ void compress(String path); - + } diff --git a/blade-core-boot/src/main/java/org/springblade/core/boot/logger/RequestLogAspect.java b/blade-core-boot/src/main/java/org/springblade/core/boot/logger/RequestLogAspect.java index aec6faa..15c213d 100644 --- a/blade-core-boot/src/main/java/org/springblade/core/boot/logger/RequestLogAspect.java +++ b/blade-core-boot/src/main/java/org/springblade/core/boot/logger/RequestLogAspect.java @@ -40,9 +40,10 @@ public class RequestLogAspect { /** * AOP 环切 控制器 R 返回值 + * * @param point JoinPoint - * @throws Throwable 异常 * @return Object + * @throws Throwable 异常 */ @Around( "execution(!static org.springblade.core.tool.api.R<*> *(..)) && " + @@ -106,7 +107,7 @@ public class RequestLogAspect { needRemoveKeys.forEach(paraMap::remove); // 打印请求 if (paraMap.isEmpty()) { - log.info("===> {}: {}", requestMethod, requestURI); + log.info("===> {}: {}", requestMethod, requestURI); } else { log.info("===> {}: {} Parameters: {}", requestMethod, requestURI, JsonUtil.toJson(paraMap)); } @@ -125,7 +126,7 @@ public class RequestLogAspect { return result; } finally { long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); - log.info("<=== {}: {} ({} ms)", request.getMethod(), requestURI, tookMs); + log.info("<=== {}: {} ({} ms)", request.getMethod(), requestURI, tookMs); } } diff --git a/blade-core-boot/src/main/java/org/springblade/core/boot/redis/RedisKeySerializer.java b/blade-core-boot/src/main/java/org/springblade/core/boot/redis/RedisKeySerializer.java index 1b183b4..5b11cdd 100644 --- a/blade-core-boot/src/main/java/org/springblade/core/boot/redis/RedisKeySerializer.java +++ b/blade-core-boot/src/main/java/org/springblade/core/boot/redis/RedisKeySerializer.java @@ -29,7 +29,7 @@ import java.util.Objects; * 将redis key序列化为字符串 * *

- * spring cache中的简单基本类型直接使用 StringRedisSerializer 会有问题 + * spring cache中的简单基本类型直接使用 StringRedisSerializer 会有问题 *

* * @author L.cm diff --git a/blade-core-boot/src/main/java/org/springblade/core/boot/resolver/TokenArgumentResolver.java b/blade-core-boot/src/main/java/org/springblade/core/boot/resolver/TokenArgumentResolver.java index 5907b70..de982af 100644 --- a/blade-core-boot/src/main/java/org/springblade/core/boot/resolver/TokenArgumentResolver.java +++ b/blade-core-boot/src/main/java/org/springblade/core/boot/resolver/TokenArgumentResolver.java @@ -26,35 +26,37 @@ import org.springframework.web.method.support.ModelAndViewContainer; /** * Token转化BladeUser + * + * @author smallchill */ @Slf4j public class TokenArgumentResolver implements HandlerMethodArgumentResolver { - /** - * 1. 入参筛选 - * - * @param methodParameter 参数集合 - * @return 格式化后的参数 - */ - @Override - public boolean supportsParameter(MethodParameter methodParameter) { - return methodParameter.getParameterType().equals(BladeUser.class); - } + /** + * 1. 入参筛选 + * + * @param methodParameter 参数集合 + * @return 格式化后的参数 + */ + @Override + public boolean supportsParameter(MethodParameter methodParameter) { + return methodParameter.getParameterType().equals(BladeUser.class); + } - /** - * @param methodParameter 入参集合 - * @param modelAndViewContainer model 和 view - * @param nativeWebRequest web相关 - * @param webDataBinderFactory 入参解析 - * @return 包装对象 - * @throws Exception exception - */ - @Override - public Object resolveArgument(MethodParameter methodParameter, - ModelAndViewContainer modelAndViewContainer, - NativeWebRequest nativeWebRequest, - WebDataBinderFactory webDataBinderFactory) { - return SecureUtil.getUser(); - } + /** + * @param methodParameter 入参集合 + * @param modelAndViewContainer model 和 view + * @param nativeWebRequest web相关 + * @param webDataBinderFactory 入参解析 + * @return 包装对象 + * @throws Exception exception + */ + @Override + public Object resolveArgument(MethodParameter methodParameter, + ModelAndViewContainer modelAndViewContainer, + NativeWebRequest nativeWebRequest, + WebDataBinderFactory webDataBinderFactory) { + return SecureUtil.getUser(); + } } diff --git a/blade-core-launch/src/main/java/org/springblade/core/launch/BladeApplication.java b/blade-core-launch/src/main/java/org/springblade/core/launch/BladeApplication.java index 8f28ddf..8b72da5 100644 --- a/blade-core-launch/src/main/java/org/springblade/core/launch/BladeApplication.java +++ b/blade-core-launch/src/main/java/org/springblade/core/launch/BladeApplication.java @@ -28,6 +28,8 @@ import java.util.function.Function; /** * 项目启动器,搞定环境变量问题 + * + * @author smallchill */ public class BladeApplication { @@ -92,7 +94,7 @@ public class BladeApplication { props.setProperty("blade.service.version", AppConstant.APPLICATION_VERSION); // 加载自定义组件 ServiceLoader loader = ServiceLoader.load(LauncherService.class); - loader.forEach(launcherService -> launcherService.launcher(builder, appName, profile)); + loader.forEach(launcherService -> launcherService.launcher(builder, appName, profile)); return builder; } diff --git a/blade-core-launch/src/main/java/org/springblade/core/launch/BladeLineRunner.java b/blade-core-launch/src/main/java/org/springblade/core/launch/BladeLineRunner.java index a0b9fda..ee45952 100644 --- a/blade-core-launch/src/main/java/org/springblade/core/launch/BladeLineRunner.java +++ b/blade-core-launch/src/main/java/org/springblade/core/launch/BladeLineRunner.java @@ -20,13 +20,15 @@ import org.springframework.stereotype.Component; /** * 系统启动完毕后执行 + * + * @author smallchill */ @Component public class BladeLineRunner implements CommandLineRunner { - @Override - public void run(String... args) { + @Override + public void run(String... args) { - } + } } diff --git a/blade-core-launch/src/main/java/org/springblade/core/launch/StartEventListener.java b/blade-core-launch/src/main/java/org/springblade/core/launch/StartEventListener.java index 939f5fd..028dfe3 100644 --- a/blade-core-launch/src/main/java/org/springblade/core/launch/StartEventListener.java +++ b/blade-core-launch/src/main/java/org/springblade/core/launch/StartEventListener.java @@ -1,3 +1,18 @@ +/** + * Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com). + *

+ * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE; + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.springblade.core.launch; import lombok.extern.slf4j.Slf4j; @@ -11,6 +26,8 @@ import org.springframework.util.StringUtils; /** * 项目启动事件通知 + * + * @author smallchill */ @Slf4j @Configuration diff --git a/blade-core-launch/src/main/java/org/springblade/core/launch/config/BladeConsulServiceRegistryConfiguration.java b/blade-core-launch/src/main/java/org/springblade/core/launch/config/BladeConsulServiceRegistryConfiguration.java index 7b86567..433b32c 100644 --- a/blade-core-launch/src/main/java/org/springblade/core/launch/config/BladeConsulServiceRegistryConfiguration.java +++ b/blade-core-launch/src/main/java/org/springblade/core/launch/config/BladeConsulServiceRegistryConfiguration.java @@ -31,6 +31,8 @@ import org.springframework.context.annotation.Configuration; /** * Consul自定义注册规则 + * + * @author smallchill */ @Configuration @ConditionalOnConsulEnabled diff --git a/blade-core-launch/src/main/java/org/springblade/core/launch/config/BladeLaunchConfiguration.java b/blade-core-launch/src/main/java/org/springblade/core/launch/config/BladeLaunchConfiguration.java index c019f0c..c0c2c03 100644 --- a/blade-core-launch/src/main/java/org/springblade/core/launch/config/BladeLaunchConfiguration.java +++ b/blade-core-launch/src/main/java/org/springblade/core/launch/config/BladeLaunchConfiguration.java @@ -26,12 +26,16 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; - +/** + * 配置类 + * + * @author smallchill + */ @Configuration @AllArgsConstructor @Order(Ordered.HIGHEST_PRECEDENCE) @EnableConfigurationProperties({ - BladeProperties.class + BladeProperties.class }) public class BladeLaunchConfiguration { diff --git a/blade-core-launch/src/main/java/org/springblade/core/launch/constant/AppConstant.java b/blade-core-launch/src/main/java/org/springblade/core/launch/constant/AppConstant.java index c4b2b86..7466ca1 100644 --- a/blade-core-launch/src/main/java/org/springblade/core/launch/constant/AppConstant.java +++ b/blade-core-launch/src/main/java/org/springblade/core/launch/constant/AppConstant.java @@ -17,130 +17,132 @@ package org.springblade.core.launch.constant; /** * 系统常量 + * + * @author smallchill */ public interface AppConstant { - /** - * 应用版本 - */ - String APPLICATION_VERSION = "1.0.0"; + /** + * 应用版本 + */ + String APPLICATION_VERSION = "1.0.0"; - /** - * consul dev 地址 - */ - String CONSUL_DEV_HOST = "http://localhost"; + /** + * consul dev 地址 + */ + String CONSUL_DEV_HOST = "http://localhost"; /** * consul prod 地址 */ String CONSUL_PROD_HOST = "http://192.168.186.129"; - /** - * consul端口 - */ - String CONSUL_PORT = "8500"; + /** + * consul端口 + */ + String CONSUL_PORT = "8500"; - /** - * consul端口 - */ - String CONSUL_CONFIG_FORMAT = "yaml"; + /** + * consul端口 + */ + String CONSUL_CONFIG_FORMAT = "yaml"; - /** - * consul端口 - */ - String CONSUL_WATCH_DELAY = "1000"; + /** + * consul端口 + */ + String CONSUL_WATCH_DELAY = "1000"; - /** - * consul端口 - */ - String CONSUL_WATCH_ENABLED = "true"; + /** + * consul端口 + */ + String CONSUL_WATCH_ENABLED = "true"; - /** - * 基础包 - */ - String BASE_PACKAGES = "org.springblade"; + /** + * 基础包 + */ + String BASE_PACKAGES = "org.springblade"; - /** - * zookeeper id - */ - String ZOOKEEPER_ID = "zk"; + /** + * zookeeper id + */ + String ZOOKEEPER_ID = "zk"; - /** - * zookeeper connect string - */ - String ZOOKEEPER_CONNECT_STRING = "127.0.0.1:2181"; + /** + * zookeeper connect string + */ + String ZOOKEEPER_CONNECT_STRING = "127.0.0.1:2181"; - /** - * zookeeper address - */ - String ZOOKEEPER_ADDRESS = "zookeeper://" + ZOOKEEPER_CONNECT_STRING; + /** + * zookeeper address + */ + String ZOOKEEPER_ADDRESS = "zookeeper://" + ZOOKEEPER_CONNECT_STRING; - /** - * zookeeper root - */ - String ZOOKEEPER_ROOT = "/blade-services"; + /** + * zookeeper root + */ + String ZOOKEEPER_ROOT = "/blade-services"; - /** - * 应用名前缀 - */ - String APPLICATION_NAME_FREFIX = "blade-"; - /** - * 网关模块名称 - */ - String APPLICATION_GATEWAY_NAME = APPLICATION_NAME_FREFIX + "gateway"; - /** - * 授权模块名称 - */ - String APPLICATION_AUTH_NAME = APPLICATION_NAME_FREFIX + "auth"; - /** - * 监控模块名称 - */ - String APPLICATION_ADMIN_NAME = APPLICATION_NAME_FREFIX + "admin"; - /** - * 配置中心模块名称 - */ - String APPLICATION_CONFIG_NAME = APPLICATION_NAME_FREFIX + "config-server"; - /** - * TX模块名称 - */ - String APPLICATION_TX_MANAGER = "tx-manager"; - /** - * 首页模块名称 - */ - String APPLICATION_DESK_NAME = APPLICATION_NAME_FREFIX + "desk"; - /** - * 系统模块名称 - */ - String APPLICATION_SYSTEM_NAME = APPLICATION_NAME_FREFIX + "system"; - /** - * 用户模块名称 - */ - String APPLICATION_USER_NAME = APPLICATION_NAME_FREFIX + "user"; - /** - * 日志模块名称 - */ - String APPLICATION_LOG_NAME = APPLICATION_NAME_FREFIX + "log"; - /** - * 测试模块名称 - */ - String APPLICATION_TEST_NAME = APPLICATION_NAME_FREFIX + "test"; + /** + * 应用名前缀 + */ + String APPLICATION_NAME_FREFIX = "blade-"; + /** + * 网关模块名称 + */ + String APPLICATION_GATEWAY_NAME = APPLICATION_NAME_FREFIX + "gateway"; + /** + * 授权模块名称 + */ + String APPLICATION_AUTH_NAME = APPLICATION_NAME_FREFIX + "auth"; + /** + * 监控模块名称 + */ + String APPLICATION_ADMIN_NAME = APPLICATION_NAME_FREFIX + "admin"; + /** + * 配置中心模块名称 + */ + String APPLICATION_CONFIG_NAME = APPLICATION_NAME_FREFIX + "config-server"; + /** + * TX模块名称 + */ + String APPLICATION_TX_MANAGER = "tx-manager"; + /** + * 首页模块名称 + */ + String APPLICATION_DESK_NAME = APPLICATION_NAME_FREFIX + "desk"; + /** + * 系统模块名称 + */ + String APPLICATION_SYSTEM_NAME = APPLICATION_NAME_FREFIX + "system"; + /** + * 用户模块名称 + */ + String APPLICATION_USER_NAME = APPLICATION_NAME_FREFIX + "user"; + /** + * 日志模块名称 + */ + String APPLICATION_LOG_NAME = APPLICATION_NAME_FREFIX + "log"; + /** + * 测试模块名称 + */ + String APPLICATION_TEST_NAME = APPLICATION_NAME_FREFIX + "test"; - /** - * 开发环境 - */ - String DEV_CDOE = "dev"; - /** - * 生产环境 - */ - String PROD_CODE = "prod"; - /** - * 测试环境 - */ - String TEST_CODE = "test"; + /** + * 开发环境 + */ + String DEV_CDOE = "dev"; + /** + * 生产环境 + */ + String PROD_CODE = "prod"; + /** + * 测试环境 + */ + String TEST_CODE = "test"; - /** - * 代码部署于 linux 上,工作默认为 mac 和 Windows - */ - String OS_NAME_LINUX = "LINUX"; + /** + * 代码部署于 linux 上,工作默认为 mac 和 Windows + */ + String OS_NAME_LINUX = "LINUX"; } diff --git a/blade-core-launch/src/main/java/org/springblade/core/launch/consul/BladeConsulServiceRegistry.java b/blade-core-launch/src/main/java/org/springblade/core/launch/consul/BladeConsulServiceRegistry.java index b5d0492..e2ec039 100644 --- a/blade-core-launch/src/main/java/org/springblade/core/launch/consul/BladeConsulServiceRegistry.java +++ b/blade-core-launch/src/main/java/org/springblade/core/launch/consul/BladeConsulServiceRegistry.java @@ -25,6 +25,8 @@ import org.springframework.cloud.consul.serviceregistry.ConsulServiceRegistry; /** * Consul自定义注册规则 + * + * @author smallchill */ public class BladeConsulServiceRegistry extends ConsulServiceRegistry { diff --git a/blade-core-launch/src/main/java/org/springblade/core/launch/consul/ConsulLauncherService.java b/blade-core-launch/src/main/java/org/springblade/core/launch/consul/ConsulLauncherService.java index d0e7daf..3e7b419 100644 --- a/blade-core-launch/src/main/java/org/springblade/core/launch/consul/ConsulLauncherService.java +++ b/blade-core-launch/src/main/java/org/springblade/core/launch/consul/ConsulLauncherService.java @@ -1,3 +1,18 @@ +/** + * Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com). + *

+ * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE; + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.springblade.core.launch.consul; import org.springblade.core.launch.constant.AppConstant; @@ -8,6 +23,8 @@ import java.util.Properties; /** * consul启动拓展 + * + * @author smallchil */ public class ConsulLauncherService implements LauncherService { diff --git a/blade-core-launch/src/main/java/org/springblade/core/launch/props/BladeProperties.java b/blade-core-launch/src/main/java/org/springblade/core/launch/props/BladeProperties.java index f176944..b9bc744 100644 --- a/blade-core-launch/src/main/java/org/springblade/core/launch/props/BladeProperties.java +++ b/blade-core-launch/src/main/java/org/springblade/core/launch/props/BladeProperties.java @@ -25,6 +25,8 @@ import java.util.Map; /** * 配置文件 + * + * @author smallchill */ @ConfigurationProperties("blade") public class BladeProperties { @@ -36,19 +38,19 @@ public class BladeProperties { @Setter private String env; - /** - * 服务名 - */ - @Getter - @Setter - private String name; + /** + * 服务名 + */ + @Getter + @Setter + private String name; - /** - * 判断是否为 本地开发环境 - */ - @Getter - @Setter - private Boolean isLocal = Boolean.FALSE; + /** + * 判断是否为 本地开发环境 + */ + @Getter + @Setter + private Boolean isLocal = Boolean.FALSE; /** * 装载自定义配置blade.prop.xxx @@ -170,32 +172,32 @@ public class BladeProperties { return defaultValue; } - /** - * 获取配置 - * - * @param key key - * @return double value - */ + /** + * 获取配置 + * + * @param key key + * @return double value + */ @Nullable - public Double getDouble(String key) { - return getDouble(key, null); - } + public Double getDouble(String key) { + return getDouble(key, null); + } - /** - * 获取配置 - * - * @param key key - * @param defaultValue 默认值 - * @return double value - */ + /** + * 获取配置 + * + * @param key key + * @param defaultValue 默认值 + * @return double value + */ @Nullable - public Double getDouble(String key, @Nullable Double defaultValue) { - String value = prop.get(key); - if (value != null) { - return Double.parseDouble(value.trim()); - } - return defaultValue; - } + public Double getDouble(String key, @Nullable Double defaultValue) { + String value = prop.get(key); + if (value != null) { + return Double.parseDouble(value.trim()); + } + return defaultValue; + } /** * 判断是否存在key diff --git a/blade-core-launch/src/main/java/org/springblade/core/launch/server/ServerInfo.java b/blade-core-launch/src/main/java/org/springblade/core/launch/server/ServerInfo.java index d936385..dd2f9cd 100644 --- a/blade-core-launch/src/main/java/org/springblade/core/launch/server/ServerInfo.java +++ b/blade-core-launch/src/main/java/org/springblade/core/launch/server/ServerInfo.java @@ -20,43 +20,45 @@ import org.springframework.cloud.commons.util.InetUtils; /** * 服务器信息 + * + * @author smallchill */ public class ServerInfo { - private ServerProperties serverProperties; - private InetUtils inetUtils; - private String hostName; - private String ip; - private Integer prot; - private String ipWithPort; + private ServerProperties serverProperties; + private InetUtils inetUtils; + private String hostName; + private String ip; + private Integer prot; + private String ipWithPort; - public ServerInfo(ServerProperties serverProperties, InetUtils inetUtils) { - this.serverProperties = serverProperties; - this.inetUtils = inetUtils; - this.hostName = getHostInfo().getHostname(); - this.ip = getHostInfo().getIpAddress(); - this.prot = serverProperties.getPort(); - this.ipWithPort = String.format("%s:%d", ip, prot); - } + public ServerInfo(ServerProperties serverProperties, InetUtils inetUtils) { + this.serverProperties = serverProperties; + this.inetUtils = inetUtils; + this.hostName = getHostInfo().getHostname(); + this.ip = getHostInfo().getIpAddress(); + this.prot = serverProperties.getPort(); + this.ipWithPort = String.format("%s:%d", ip, prot); + } - public InetUtils.HostInfo getHostInfo() { - return inetUtils.findFirstNonLoopbackHostInfo(); - } + public InetUtils.HostInfo getHostInfo() { + return inetUtils.findFirstNonLoopbackHostInfo(); + } - public String getIP() { - return this.ip; - } + public String getIP() { + return this.ip; + } - public Integer getPort() { - return this.prot; - } + public Integer getPort() { + return this.prot; + } - public String getHostName() { - return this.hostName; - } + public String getHostName() { + return this.hostName; + } - public String getIPWithPort() { - return this.ipWithPort; - } + public String getIPWithPort() { + return this.ipWithPort; + } } diff --git a/blade-core-launch/src/main/java/org/springblade/core/launch/service/LauncherService.java b/blade-core-launch/src/main/java/org/springblade/core/launch/service/LauncherService.java index 9b24b1e..3ebd630 100644 --- a/blade-core-launch/src/main/java/org/springblade/core/launch/service/LauncherService.java +++ b/blade-core-launch/src/main/java/org/springblade/core/launch/service/LauncherService.java @@ -19,11 +19,14 @@ import org.springframework.boot.builder.SpringApplicationBuilder; /** * launcher 扩展 用于一些组件发现 + * + * @author smallchill */ public interface LauncherService { /** * 启动时 处理 SpringApplicationBuilder + * * @param builder SpringApplicationBuilder * @param appName SpringApplicationAppName * @param profile SpringApplicationProfile diff --git a/blade-core-log/src/main/java/org/springblade/core/log/annotation/ApiLog.java b/blade-core-log/src/main/java/org/springblade/core/log/annotation/ApiLog.java index b9563d4..328275f 100644 --- a/blade-core-log/src/main/java/org/springblade/core/log/annotation/ApiLog.java +++ b/blade-core-log/src/main/java/org/springblade/core/log/annotation/ApiLog.java @@ -20,6 +20,8 @@ import java.lang.annotation.*; /** * 操作日志注解 + * + * @author smallchill */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) diff --git a/blade-core-log/src/main/java/org/springblade/core/log/aspect/ApiLogAspect.java b/blade-core-log/src/main/java/org/springblade/core/log/aspect/ApiLogAspect.java index b55b9e1..b2685d0 100644 --- a/blade-core-log/src/main/java/org/springblade/core/log/aspect/ApiLogAspect.java +++ b/blade-core-log/src/main/java/org/springblade/core/log/aspect/ApiLogAspect.java @@ -25,6 +25,8 @@ import org.springblade.core.log.publisher.ApiLogPublisher; /** * 操作日志使用spring event异步入库 + * + * @author smallchill */ @Slf4j @Aspect @@ -32,18 +34,18 @@ public class ApiLogAspect { @Around("@annotation(apiLog)") public Object around(ProceedingJoinPoint point, ApiLog apiLog) throws Throwable { - //获取类名 + //获取类名 String className = point.getTarget().getClass().getName(); //获取方法 String methodName = point.getSignature().getName(); // 发送异步日志事件 - long beginTime = System.currentTimeMillis(); - //执行方法 - Object result = point.proceed(); - //执行时长(毫秒) - long time = System.currentTimeMillis() - beginTime; - //记录日志 - ApiLogPublisher.publishEvent(methodName, className, apiLog, time); + long beginTime = System.currentTimeMillis(); + //执行方法 + Object result = point.proceed(); + //执行时长(毫秒) + long time = System.currentTimeMillis() - beginTime; + //记录日志 + ApiLogPublisher.publishEvent(methodName, className, apiLog, time); return result; } diff --git a/blade-core-log/src/main/java/org/springblade/core/log/config/BladeErrorMvcAutoConfiguration.java b/blade-core-log/src/main/java/org/springblade/core/log/config/BladeErrorMvcAutoConfiguration.java index 918b1bd..0c21db9 100644 --- a/blade-core-log/src/main/java/org/springblade/core/log/config/BladeErrorMvcAutoConfiguration.java +++ b/blade-core-log/src/main/java/org/springblade/core/log/config/BladeErrorMvcAutoConfiguration.java @@ -38,26 +38,28 @@ import javax.servlet.Servlet; /** * 统一异常处理 + * + * @author smallchill */ @Configuration @AllArgsConstructor @ConditionalOnWebApplication @AutoConfigureBefore(ErrorMvcAutoConfiguration.class) -@ConditionalOnClass({ Servlet.class, DispatcherServlet.class }) +@ConditionalOnClass({Servlet.class, DispatcherServlet.class}) public class BladeErrorMvcAutoConfiguration { - private final ServerProperties serverProperties; + private final ServerProperties serverProperties; - @Bean - @ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT) - public DefaultErrorAttributes errorAttributes() { - return new BladeErrorAttributes(); - } + @Bean + @ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT) + public DefaultErrorAttributes errorAttributes() { + return new BladeErrorAttributes(); + } - @Bean - @ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT) - public BasicErrorController basicErrorController(ErrorAttributes errorAttributes) { - return new BladeErrorController(errorAttributes, serverProperties.getError()); - } + @Bean + @ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT) + public BasicErrorController basicErrorController(ErrorAttributes errorAttributes) { + return new BladeErrorController(errorAttributes, serverProperties.getError()); + } } diff --git a/blade-core-log/src/main/java/org/springblade/core/log/config/BladeLogToolAutoConfiguration.java b/blade-core-log/src/main/java/org/springblade/core/log/config/BladeLogToolAutoConfiguration.java index 095ce5a..07ddbe6 100644 --- a/blade-core-log/src/main/java/org/springblade/core/log/config/BladeLogToolAutoConfiguration.java +++ b/blade-core-log/src/main/java/org/springblade/core/log/config/BladeLogToolAutoConfiguration.java @@ -31,39 +31,41 @@ import org.springframework.context.annotation.Configuration; /** * 日志工具自动配置 + * + * @author smallchill */ @Configuration @AllArgsConstructor @ConditionalOnWebApplication public class BladeLogToolAutoConfiguration { - private final ILogClient logService; - private final ServerInfo serverInfo; - private final BladeProperties bladeProperties; + private final ILogClient logService; + private final ServerInfo serverInfo; + private final BladeProperties bladeProperties; - @Bean - public ApiLogAspect apiLogAspect() { - return new ApiLogAspect(); - } + @Bean + public ApiLogAspect apiLogAspect() { + return new ApiLogAspect(); + } - @Bean - public BladeLogger bladeLogger() { - return new BladeLogger(); - } + @Bean + public BladeLogger bladeLogger() { + return new BladeLogger(); + } - @Bean - public ApiLogListener apiLogListener() { - return new ApiLogListener(logService, serverInfo, bladeProperties); - } + @Bean + public ApiLogListener apiLogListener() { + return new ApiLogListener(logService, serverInfo, bladeProperties); + } - @Bean - public ErrorLogListener errorEventListener() { - return new ErrorLogListener(logService, serverInfo, bladeProperties); - } + @Bean + public ErrorLogListener errorEventListener() { + return new ErrorLogListener(logService, serverInfo, bladeProperties); + } - @Bean - public BladeLogListener bladeEventListener() { - return new BladeLogListener(logService, serverInfo, bladeProperties); - } + @Bean + public BladeLogListener bladeEventListener() { + return new BladeLogListener(logService, serverInfo, bladeProperties); + } } diff --git a/blade-core-log/src/main/java/org/springblade/core/log/constant/EventConstant.java b/blade-core-log/src/main/java/org/springblade/core/log/constant/EventConstant.java index 9d4fc37..e2b4e79 100644 --- a/blade-core-log/src/main/java/org/springblade/core/log/constant/EventConstant.java +++ b/blade-core-log/src/main/java/org/springblade/core/log/constant/EventConstant.java @@ -17,16 +17,18 @@ package org.springblade.core.log.constant; /** * 事件常量 + * + * @author smallchill */ public interface EventConstant { - /** - * log - */ - String EVENT_LOG = "log"; - /** - * request - */ - String EVENT_REQUEST = "request"; + /** + * log + */ + String EVENT_LOG = "log"; + /** + * request + */ + String EVENT_REQUEST = "request"; } diff --git a/blade-core-log/src/main/java/org/springblade/core/log/error/BladeErrorAttributes.java b/blade-core-log/src/main/java/org/springblade/core/log/error/BladeErrorAttributes.java index cb1dcb4..e0ce4f2 100644 --- a/blade-core-log/src/main/java/org/springblade/core/log/error/BladeErrorAttributes.java +++ b/blade-core-log/src/main/java/org/springblade/core/log/error/BladeErrorAttributes.java @@ -29,31 +29,33 @@ import java.util.Map; /** * 全局异常处理 + * + * @author smallchill */ @Slf4j public class BladeErrorAttributes extends DefaultErrorAttributes { - @Override - public Map getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) { - String requestUri = this.getAttr(webRequest, "javax.servlet.error.request_uri"); - Integer status = this.getAttr(webRequest, "javax.servlet.error.status_code"); - Throwable error = getError(webRequest); - R result; - if (error == null) { - log.error("URL:{} error status:{}", requestUri, status); - result = R.failure(ResultCode.FAILURE, "系统未知异常[HttpStatus]:" + status); - } else { - log.error(String.format("URL:%s error status:%d", requestUri, status), error); - result = R.failure(status, error.getMessage()); - } - //发送服务异常事件 - ErrorLogPublisher.publishEvent(error, requestUri); - return BeanUtil.toMap(result); - } + @Override + public Map getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) { + String requestUri = this.getAttr(webRequest, "javax.servlet.error.request_uri"); + Integer status = this.getAttr(webRequest, "javax.servlet.error.status_code"); + Throwable error = getError(webRequest); + R result; + if (error == null) { + log.error("URL:{} error status:{}", requestUri, status); + result = R.failure(ResultCode.FAILURE, "系统未知异常[HttpStatus]:" + status); + } else { + log.error(String.format("URL:%s error status:%d", requestUri, status), error); + result = R.failure(status, error.getMessage()); + } + //发送服务异常事件 + ErrorLogPublisher.publishEvent(error, requestUri); + return BeanUtil.toMap(result); + } - @Nullable - private T getAttr(WebRequest webRequest, String name) { - return (T) webRequest.getAttribute(name, RequestAttributes.SCOPE_REQUEST); - } + @Nullable + private T getAttr(WebRequest webRequest, String name) { + return (T) webRequest.getAttribute(name, RequestAttributes.SCOPE_REQUEST); + } } diff --git a/blade-core-log/src/main/java/org/springblade/core/log/error/BladeErrorController.java b/blade-core-log/src/main/java/org/springblade/core/log/error/BladeErrorController.java index d3b4c74..c88e32d 100644 --- a/blade-core-log/src/main/java/org/springblade/core/log/error/BladeErrorController.java +++ b/blade-core-log/src/main/java/org/springblade/core/log/error/BladeErrorController.java @@ -30,22 +30,24 @@ import java.util.Map; /** * 更改html请求异常为ajax + * + * @author smallchill */ public class BladeErrorController extends BasicErrorController { - public BladeErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties) { - super(errorAttributes, errorProperties); - } + public BladeErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties) { + super(errorAttributes, errorProperties); + } - @Override - public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) { - Map body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL)); - HttpStatus status = getStatus(request); - response.setStatus(status.value()); - MappingJackson2JsonView view = new MappingJackson2JsonView(); - view.setObjectMapper(JsonUtil.getInstance()); - view.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE); - return new ModelAndView(view, body); - } + @Override + public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) { + Map body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL)); + HttpStatus status = getStatus(request); + response.setStatus(status.value()); + MappingJackson2JsonView view = new MappingJackson2JsonView(); + view.setObjectMapper(JsonUtil.getInstance()); + view.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE); + return new ModelAndView(view, body); + } } diff --git a/blade-core-log/src/main/java/org/springblade/core/log/error/BladeRestExceptionTranslator.java b/blade-core-log/src/main/java/org/springblade/core/log/error/BladeRestExceptionTranslator.java index 24dca6e..fc5dc6c 100644 --- a/blade-core-log/src/main/java/org/springblade/core/log/error/BladeRestExceptionTranslator.java +++ b/blade-core-log/src/main/java/org/springblade/core/log/error/BladeRestExceptionTranslator.java @@ -51,110 +51,112 @@ import java.util.Set; /** * 全局异常处理,处理可预见的异常 + * + * @author smallchill */ @Slf4j @Configuration -@ConditionalOnClass({ Servlet.class, DispatcherServlet.class }) +@ConditionalOnClass({Servlet.class, DispatcherServlet.class}) @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) @RestControllerAdvice public class BladeRestExceptionTranslator { - @ExceptionHandler(MissingServletRequestParameterException.class) - @ResponseStatus(HttpStatus.BAD_REQUEST) - public R handleError(MissingServletRequestParameterException e) { - log.warn("缺少请求参数", e.getMessage()); - String message = String.format("缺少必要的请求参数: %s", e.getParameterName()); - return R.failure(ResultCode.PARAM_MISS, message); - } + @ExceptionHandler(MissingServletRequestParameterException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public R handleError(MissingServletRequestParameterException e) { + log.warn("缺少请求参数", e.getMessage()); + String message = String.format("缺少必要的请求参数: %s", e.getParameterName()); + return R.failure(ResultCode.PARAM_MISS, message); + } - @ExceptionHandler(MethodArgumentTypeMismatchException.class) - @ResponseStatus(HttpStatus.BAD_REQUEST) - public R handleError(MethodArgumentTypeMismatchException e) { - log.warn("请求参数格式错误", e.getMessage()); - String message = String.format("请求参数格式错误: %s", e.getName()); - return R.failure(ResultCode.PARAM_TYPE_ERROR, message); - } + @ExceptionHandler(MethodArgumentTypeMismatchException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public R handleError(MethodArgumentTypeMismatchException e) { + log.warn("请求参数格式错误", e.getMessage()); + String message = String.format("请求参数格式错误: %s", e.getName()); + return R.failure(ResultCode.PARAM_TYPE_ERROR, message); + } - @ExceptionHandler(MethodArgumentNotValidException.class) - @ResponseStatus(HttpStatus.BAD_REQUEST) - public R handleError(MethodArgumentNotValidException e) { - log.warn("参数验证失败", e.getMessage()); - return handleError(e.getBindingResult()); - } + @ExceptionHandler(MethodArgumentNotValidException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public R handleError(MethodArgumentNotValidException e) { + log.warn("参数验证失败", e.getMessage()); + return handleError(e.getBindingResult()); + } - @ExceptionHandler(BindException.class) - @ResponseStatus(HttpStatus.BAD_REQUEST) - public R handleError(BindException e) { - log.warn("参数绑定失败", e.getMessage()); - return handleError(e.getBindingResult()); - } + @ExceptionHandler(BindException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public R handleError(BindException e) { + log.warn("参数绑定失败", e.getMessage()); + return handleError(e.getBindingResult()); + } - private R handleError(BindingResult result) { - FieldError error = result.getFieldError(); - String message = String.format("%s:%s", error.getField(), error.getDefaultMessage()); - return R.failure(ResultCode.PARAM_BIND_ERROR, message); - } + private R handleError(BindingResult result) { + FieldError error = result.getFieldError(); + String message = String.format("%s:%s", error.getField(), error.getDefaultMessage()); + return R.failure(ResultCode.PARAM_BIND_ERROR, message); + } - @ExceptionHandler(ConstraintViolationException.class) - @ResponseStatus(HttpStatus.BAD_REQUEST) - public R handleError(ConstraintViolationException e) { - log.warn("参数验证失败", e.getMessage()); - Set> violations = e.getConstraintViolations(); - ConstraintViolation violation = violations.iterator().next(); - String path = ((PathImpl) violation.getPropertyPath()).getLeafNode().getName(); - String message = String.format("%s:%s", path, violation.getMessage()); - return R.failure(ResultCode.PARAM_VALID_ERROR, message); - } + @ExceptionHandler(ConstraintViolationException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public R handleError(ConstraintViolationException e) { + log.warn("参数验证失败", e.getMessage()); + Set> violations = e.getConstraintViolations(); + ConstraintViolation violation = violations.iterator().next(); + String path = ((PathImpl) violation.getPropertyPath()).getLeafNode().getName(); + String message = String.format("%s:%s", path, violation.getMessage()); + return R.failure(ResultCode.PARAM_VALID_ERROR, message); + } - @ExceptionHandler(NoHandlerFoundException.class) - @ResponseStatus(HttpStatus.NOT_FOUND) - public R handleError(NoHandlerFoundException e) { - log.error("404没找到请求:{}", e.getMessage()); - return R.failure(ResultCode.NOT_FOUND, e.getMessage()); - } + @ExceptionHandler(NoHandlerFoundException.class) + @ResponseStatus(HttpStatus.NOT_FOUND) + public R handleError(NoHandlerFoundException e) { + log.error("404没找到请求:{}", e.getMessage()); + return R.failure(ResultCode.NOT_FOUND, e.getMessage()); + } - @ExceptionHandler(HttpMessageNotReadableException.class) - @ResponseStatus(HttpStatus.BAD_REQUEST) - public R handleError(HttpMessageNotReadableException e) { - log.error("消息不能读取:{}", e.getMessage()); - return R.failure(ResultCode.MSG_NOT_READABLE, e.getMessage()); - } + @ExceptionHandler(HttpMessageNotReadableException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public R handleError(HttpMessageNotReadableException e) { + log.error("消息不能读取:{}", e.getMessage()); + return R.failure(ResultCode.MSG_NOT_READABLE, e.getMessage()); + } - @ExceptionHandler(HttpRequestMethodNotSupportedException.class) - @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED) - public R handleError(HttpRequestMethodNotSupportedException e) { - log.error("不支持当前请求方法:{}", e.getMessage()); - return R.failure(ResultCode.METHOD_NOT_SUPPORTED, e.getMessage()); - } + @ExceptionHandler(HttpRequestMethodNotSupportedException.class) + @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED) + public R handleError(HttpRequestMethodNotSupportedException e) { + log.error("不支持当前请求方法:{}", e.getMessage()); + return R.failure(ResultCode.METHOD_NOT_SUPPORTED, e.getMessage()); + } - @ExceptionHandler(HttpMediaTypeNotSupportedException.class) - @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE) - public R handleError(HttpMediaTypeNotSupportedException e) { - log.error("不支持当前媒体类型:{}", e.getMessage()); - return R.failure(ResultCode.MEDIA_TYPE_NOT_SUPPORTED, e.getMessage()); - } + @ExceptionHandler(HttpMediaTypeNotSupportedException.class) + @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE) + public R handleError(HttpMediaTypeNotSupportedException e) { + log.error("不支持当前媒体类型:{}", e.getMessage()); + return R.failure(ResultCode.MEDIA_TYPE_NOT_SUPPORTED, e.getMessage()); + } - @ExceptionHandler(ServiceException.class) - @ResponseStatus(HttpStatus.BAD_REQUEST) - public R handleError(ServiceException e) { - log.error("业务异常", e); - return R.failure(e.getResultCode(), e.getMessage()); - } + @ExceptionHandler(ServiceException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public R handleError(ServiceException e) { + log.error("业务异常", e); + return R.failure(e.getResultCode(), e.getMessage()); + } - @ExceptionHandler(SecureException.class) - @ResponseStatus(HttpStatus.UNAUTHORIZED) - public R handleError(SecureException e) { - log.error("认证异常", e); - return R.failure(e.getResultCode(), e.getMessage()); - } + @ExceptionHandler(SecureException.class) + @ResponseStatus(HttpStatus.UNAUTHORIZED) + public R handleError(SecureException e) { + log.error("认证异常", e); + return R.failure(e.getResultCode(), e.getMessage()); + } - @ExceptionHandler(Throwable.class) - @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) - public R handleError(Throwable e) { - log.error("服务器异常", e); - //发送服务异常事件 - ErrorLogPublisher.publishEvent(e, URLUtil.getPath(WebUtil.getRequest().getRequestURI())); - return R.failure(ResultCode.INTERNAL_SERVER_ERROR, (Func.isEmpty(e.getMessage()) ? ResultCode.INTERNAL_SERVER_ERROR.getMessage() : e.getMessage())); - } + @ExceptionHandler(Throwable.class) + @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) + public R handleError(Throwable e) { + log.error("服务器异常", e); + //发送服务异常事件 + ErrorLogPublisher.publishEvent(e, URLUtil.getPath(WebUtil.getRequest().getRequestURI())); + return R.failure(ResultCode.INTERNAL_SERVER_ERROR, (Func.isEmpty(e.getMessage()) ? ResultCode.INTERNAL_SERVER_ERROR.getMessage() : e.getMessage())); + } } diff --git a/blade-core-log/src/main/java/org/springblade/core/log/event/ApiLogEvent.java b/blade-core-log/src/main/java/org/springblade/core/log/event/ApiLogEvent.java index 1254bd4..b0297a3 100644 --- a/blade-core-log/src/main/java/org/springblade/core/log/event/ApiLogEvent.java +++ b/blade-core-log/src/main/java/org/springblade/core/log/event/ApiLogEvent.java @@ -22,11 +22,13 @@ import java.util.Map; /** * 系统日志事件 + * + * @author smallchill */ public class ApiLogEvent extends ApplicationEvent { - public ApiLogEvent(Map source) { - super(source); - } + public ApiLogEvent(Map source) { + super(source); + } } diff --git a/blade-core-log/src/main/java/org/springblade/core/log/event/ApiLogListener.java b/blade-core-log/src/main/java/org/springblade/core/log/event/ApiLogListener.java index 8f50044..931fdf5 100644 --- a/blade-core-log/src/main/java/org/springblade/core/log/event/ApiLogListener.java +++ b/blade-core-log/src/main/java/org/springblade/core/log/event/ApiLogListener.java @@ -38,36 +38,38 @@ import java.util.Map; /** * 异步监听日志事件 + * + * @author smallchill */ @Slf4j @Component @AllArgsConstructor public class ApiLogListener { - private final ILogClient logService; - private final ServerInfo serverInfo; - private final BladeProperties bladeProperties; + private final ILogClient logService; + private final ServerInfo serverInfo; + private final BladeProperties bladeProperties; @Async @Order @EventListener(ApiLogEvent.class) public void saveApiLog(ApiLogEvent event) { - Map source = (Map) event.getSource(); - LogApi logApi = (LogApi) source.get(EventConstant.EVENT_LOG); - HttpServletRequest request = (HttpServletRequest) source.get(EventConstant.EVENT_REQUEST); - logApi.setServiceId(bladeProperties.getName()); - logApi.setServerHost(serverInfo.getHostName()); - logApi.setServerIp(serverInfo.getIPWithPort()); - logApi.setEnv(bladeProperties.getEnv()); - logApi.setRemoteIp(WebUtil.getIP(request)); - logApi.setUserAgent(request.getHeader(WebUtil.USER_AGENT_HEADER)); - logApi.setRequestUri(URLUtil.getPath(request.getRequestURI())); - logApi.setMethod(request.getMethod()); - logApi.setParams(WebUtil.getRequestParamString(request)); - logApi.setCreateBy(SecureUtil.getUserAccount(request)); - logApi.setCreateTime(LocalDateTime.now()); - logService.saveApiLog(logApi); + Map source = (Map) event.getSource(); + LogApi logApi = (LogApi) source.get(EventConstant.EVENT_LOG); + HttpServletRequest request = (HttpServletRequest) source.get(EventConstant.EVENT_REQUEST); + logApi.setServiceId(bladeProperties.getName()); + logApi.setServerHost(serverInfo.getHostName()); + logApi.setServerIp(serverInfo.getIPWithPort()); + logApi.setEnv(bladeProperties.getEnv()); + logApi.setRemoteIp(WebUtil.getIP(request)); + logApi.setUserAgent(request.getHeader(WebUtil.USER_AGENT_HEADER)); + logApi.setRequestUri(URLUtil.getPath(request.getRequestURI())); + logApi.setMethod(request.getMethod()); + logApi.setParams(WebUtil.getRequestParamString(request)); + logApi.setCreateBy(SecureUtil.getUserAccount(request)); + logApi.setCreateTime(LocalDateTime.now()); + logService.saveApiLog(logApi); } } diff --git a/blade-core-log/src/main/java/org/springblade/core/log/event/BladeLogEvent.java b/blade-core-log/src/main/java/org/springblade/core/log/event/BladeLogEvent.java index c8bc540..48d5e6f 100644 --- a/blade-core-log/src/main/java/org/springblade/core/log/event/BladeLogEvent.java +++ b/blade-core-log/src/main/java/org/springblade/core/log/event/BladeLogEvent.java @@ -22,11 +22,13 @@ import java.util.Map; /** * 系统日志事件 + * + * @author smallchill */ public class BladeLogEvent extends ApplicationEvent { - public BladeLogEvent(Map source) { - super(source); - } + public BladeLogEvent(Map source) { + super(source); + } } diff --git a/blade-core-log/src/main/java/org/springblade/core/log/event/BladeLogListener.java b/blade-core-log/src/main/java/org/springblade/core/log/event/BladeLogListener.java index cd85b57..b75cf11 100644 --- a/blade-core-log/src/main/java/org/springblade/core/log/event/BladeLogListener.java +++ b/blade-core-log/src/main/java/org/springblade/core/log/event/BladeLogListener.java @@ -37,34 +37,36 @@ import java.util.Map; /** * 异步监听日志事件 + * + * @author smallchill */ @Slf4j @Component @AllArgsConstructor public class BladeLogListener { - private final ILogClient logService; - private final ServerInfo serverInfo; - private final BladeProperties bladeProperties; + private final ILogClient logService; + private final ServerInfo serverInfo; + private final BladeProperties bladeProperties; - @Async - @Order - @EventListener(BladeLogEvent.class) - public void saveBladeLog(BladeLogEvent event) { - Map source = (Map) event.getSource(); - LogBlade logBlade = (LogBlade) source.get(EventConstant.EVENT_LOG); - HttpServletRequest request = (HttpServletRequest) source.get(EventConstant.EVENT_REQUEST); - logBlade.setRequestUri(URLUtil.getPath(request.getRequestURI())); - logBlade.setUserAgent(request.getHeader(WebUtil.USER_AGENT_HEADER)); - logBlade.setMethod(request.getMethod()); - logBlade.setParams(WebUtil.getRequestParamString(request)); - logBlade.setServerHost(serverInfo.getHostName()); - logBlade.setServiceId(bladeProperties.getName()); - logBlade.setEnv(bladeProperties.getEnv()); - logBlade.setServerIp(serverInfo.getIPWithPort()); - logBlade.setCreateBy(SecureUtil.getUserAccount(request)); - logBlade.setCreateTime(LocalDateTime.now()); - logService.saveBladeLog(logBlade); - } + @Async + @Order + @EventListener(BladeLogEvent.class) + public void saveBladeLog(BladeLogEvent event) { + Map source = (Map) event.getSource(); + LogBlade logBlade = (LogBlade) source.get(EventConstant.EVENT_LOG); + HttpServletRequest request = (HttpServletRequest) source.get(EventConstant.EVENT_REQUEST); + logBlade.setRequestUri(URLUtil.getPath(request.getRequestURI())); + logBlade.setUserAgent(request.getHeader(WebUtil.USER_AGENT_HEADER)); + logBlade.setMethod(request.getMethod()); + logBlade.setParams(WebUtil.getRequestParamString(request)); + logBlade.setServerHost(serverInfo.getHostName()); + logBlade.setServiceId(bladeProperties.getName()); + logBlade.setEnv(bladeProperties.getEnv()); + logBlade.setServerIp(serverInfo.getIPWithPort()); + logBlade.setCreateBy(SecureUtil.getUserAccount(request)); + logBlade.setCreateTime(LocalDateTime.now()); + logService.saveBladeLog(logBlade); + } } diff --git a/blade-core-log/src/main/java/org/springblade/core/log/event/ErrorLogEvent.java b/blade-core-log/src/main/java/org/springblade/core/log/event/ErrorLogEvent.java index 9c4c7db..13d1f61 100644 --- a/blade-core-log/src/main/java/org/springblade/core/log/event/ErrorLogEvent.java +++ b/blade-core-log/src/main/java/org/springblade/core/log/event/ErrorLogEvent.java @@ -22,11 +22,13 @@ import java.util.Map; /** * 错误日志事件 + * + * @author smallchill */ public class ErrorLogEvent extends ApplicationEvent { - public ErrorLogEvent(Map source) { - super(source); - } + public ErrorLogEvent(Map source) { + super(source); + } } diff --git a/blade-core-log/src/main/java/org/springblade/core/log/event/ErrorLogListener.java b/blade-core-log/src/main/java/org/springblade/core/log/event/ErrorLogListener.java index 67e5424..c947d35 100644 --- a/blade-core-log/src/main/java/org/springblade/core/log/event/ErrorLogListener.java +++ b/blade-core-log/src/main/java/org/springblade/core/log/event/ErrorLogListener.java @@ -36,33 +36,35 @@ import java.util.Map; /** * 异步监听错误日志事件 + * + * @author smallchill */ @Slf4j @Component @AllArgsConstructor public class ErrorLogListener { - private final ILogClient logService; - private final ServerInfo serverInfo; - private final BladeProperties bladeProperties; + private final ILogClient logService; + private final ServerInfo serverInfo; + private final BladeProperties bladeProperties; - @Async - @Order - @EventListener(ErrorLogEvent.class) - public void saveErrorLog(ErrorLogEvent event) { - Map source = (Map) event.getSource(); - LogError logError = (LogError) source.get(EventConstant.EVENT_LOG); - HttpServletRequest request = (HttpServletRequest) source.get(EventConstant.EVENT_REQUEST); - logError.setUserAgent(request.getHeader(WebUtil.USER_AGENT_HEADER)); - logError.setMethod(request.getMethod()); - logError.setParams(WebUtil.getRequestParamString(request)); - logError.setServiceId(bladeProperties.getName()); - logError.setServerHost(serverInfo.getHostName()); - logError.setServerIp(serverInfo.getIPWithPort()); - logError.setEnv(bladeProperties.getEnv()); - logError.setCreateBy(SecureUtil.getUserAccount(request)); - logError.setCreateTime(LocalDateTime.now()); - logService.saveErrorLog(logError); - } + @Async + @Order + @EventListener(ErrorLogEvent.class) + public void saveErrorLog(ErrorLogEvent event) { + Map source = (Map) event.getSource(); + LogError logError = (LogError) source.get(EventConstant.EVENT_LOG); + HttpServletRequest request = (HttpServletRequest) source.get(EventConstant.EVENT_REQUEST); + logError.setUserAgent(request.getHeader(WebUtil.USER_AGENT_HEADER)); + logError.setMethod(request.getMethod()); + logError.setParams(WebUtil.getRequestParamString(request)); + logError.setServiceId(bladeProperties.getName()); + logError.setServerHost(serverInfo.getHostName()); + logError.setServerIp(serverInfo.getIPWithPort()); + logError.setEnv(bladeProperties.getEnv()); + logError.setCreateBy(SecureUtil.getUserAccount(request)); + logError.setCreateTime(LocalDateTime.now()); + logService.saveErrorLog(logError); + } } diff --git a/blade-core-log/src/main/java/org/springblade/core/log/exception/ServiceException.java b/blade-core-log/src/main/java/org/springblade/core/log/exception/ServiceException.java index 74d5008..55e1a23 100644 --- a/blade-core-log/src/main/java/org/springblade/core/log/exception/ServiceException.java +++ b/blade-core-log/src/main/java/org/springblade/core/log/exception/ServiceException.java @@ -22,6 +22,8 @@ import org.springblade.core.tool.api.ResultCode; /** * 业务异常 + * + * @author smallchill */ public class ServiceException extends RuntimeException { private static final long serialVersionUID = 2359767895161832954L; @@ -29,23 +31,24 @@ public class ServiceException extends RuntimeException { @Getter private final IResultCode resultCode; - public ServiceException(String message) { - super(message); - this.resultCode = ResultCode.INTERNAL_SERVER_ERROR; - } + public ServiceException(String message) { + super(message); + this.resultCode = ResultCode.INTERNAL_SERVER_ERROR; + } - public ServiceException(IResultCode resultCode) { - super(resultCode.getMessage()); - this.resultCode = resultCode; - } + public ServiceException(IResultCode resultCode) { + super(resultCode.getMessage()); + this.resultCode = resultCode; + } public ServiceException(IResultCode resultCode, Throwable cause) { super(cause); - this.resultCode = resultCode; + this.resultCode = resultCode; } /** * 提高性能 + * * @return Throwable */ @Override diff --git a/blade-core-log/src/main/java/org/springblade/core/log/feign/ILogClient.java b/blade-core-log/src/main/java/org/springblade/core/log/feign/ILogClient.java index 59f4b8d..276641c 100644 --- a/blade-core-log/src/main/java/org/springblade/core/log/feign/ILogClient.java +++ b/blade-core-log/src/main/java/org/springblade/core/log/feign/ILogClient.java @@ -26,39 +26,41 @@ import org.springframework.web.bind.annotation.RequestBody; /** * Feign接口类 + * + * @author smallchill */ @FeignClient( - value = AppConstant.APPLICATION_LOG_NAME + value = AppConstant.APPLICATION_LOG_NAME ) public interface ILogClient { - String API_PREFIX = "/log"; + String API_PREFIX = "/log"; - /** - * 保存错误日志 - * - * @param log - * @return - */ - @PostMapping(API_PREFIX + "/saveBladeLog") + /** + * 保存错误日志 + * + * @param log + * @return + */ + @PostMapping(API_PREFIX + "/saveBladeLog") R saveBladeLog(@RequestBody LogBlade log); - /** - * 保存操作日志 - * - * @param log - * @return - */ - @PostMapping(API_PREFIX + "/saveApiLog") + /** + * 保存操作日志 + * + * @param log + * @return + */ + @PostMapping(API_PREFIX + "/saveApiLog") R saveApiLog(@RequestBody LogApi log); - /** - * 保存错误日志 - * - * @param log - * @return - */ - @PostMapping(API_PREFIX + "/saveErrorLog") + /** + * 保存错误日志 + * + * @param log + * @return + */ + @PostMapping(API_PREFIX + "/saveErrorLog") R saveErrorLog(@RequestBody LogError log); } diff --git a/blade-core-log/src/main/java/org/springblade/core/log/logger/BladeLogger.java b/blade-core-log/src/main/java/org/springblade/core/log/logger/BladeLogger.java index 778a6c2..063d678 100644 --- a/blade-core-log/src/main/java/org/springblade/core/log/logger/BladeLogger.java +++ b/blade-core-log/src/main/java/org/springblade/core/log/logger/BladeLogger.java @@ -22,32 +22,34 @@ import org.springframework.beans.factory.annotation.Value; /** * 日志工具类 + * + * @author smallchill */ @Slf4j public class BladeLogger implements InitializingBean { - @Value("${spring.application.name}") - private String serviceId; + @Value("${spring.application.name}") + private String serviceId; - public void info(String id, String data) { - BladeLogPublisher.publishEvent("info", id, data); - } + public void info(String id, String data) { + BladeLogPublisher.publishEvent("info", id, data); + } - public void debug(String id, String data) { - BladeLogPublisher.publishEvent("debug", id, data); - } + public void debug(String id, String data) { + BladeLogPublisher.publishEvent("debug", id, data); + } - public void warn(String id, String data) { - BladeLogPublisher.publishEvent("warn", id, data); - } + public void warn(String id, String data) { + BladeLogPublisher.publishEvent("warn", id, data); + } - public void error(String id, String data) { - BladeLogPublisher.publishEvent("error", id, data); - } + public void error(String id, String data) { + BladeLogPublisher.publishEvent("error", id, data); + } - @Override - public void afterPropertiesSet() throws Exception { - log.info(serviceId + ": BladeLogger init success!"); - } + @Override + public void afterPropertiesSet() throws Exception { + log.info(serviceId + ": BladeLogger init success!"); + } } diff --git a/blade-core-log/src/main/java/org/springblade/core/log/model/LogApi.java b/blade-core-log/src/main/java/org/springblade/core/log/model/LogApi.java index 1fdd101..6bf3d08 100644 --- a/blade-core-log/src/main/java/org/springblade/core/log/model/LogApi.java +++ b/blade-core-log/src/main/java/org/springblade/core/log/model/LogApi.java @@ -28,94 +28,94 @@ import java.io.Serializable; import java.time.LocalDateTime; /** - * 实体类 + * 实体类 * - * @author Blade + * @author smallchill */ @Data @TableName("blade_log_api") public class LogApi implements Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - /** - * 主键id - */ - @TableId(value = "id", type = IdType.ID_WORKER) - private Long id; + /** + * 主键id + */ + @TableId(value = "id", type = IdType.ID_WORKER) + private Long id; - /** - * 日志类型 - */ - private String type; - /** - * 日志标题 - */ - private String title; - /** - * 服务ID - */ - private String serviceId; - /** - * 服务器 ip - */ - private String serverIp; - /** - * 服务器名 - */ - private String serverHost; - /** - * 环境 - */ - private String env; - /** - * 操作IP地址 - */ - private String remoteIp; - /** - * 用户代理 - */ - private String userAgent; - /** - * 请求URI - */ - private String requestUri; - /** - * 操作方式 - */ - private String method; - /** - * 方法类 - */ - private String methodClass; - /** - * 方法名 - */ - private String methodName; - /** - * 操作提交的数据 - */ - private String params; - /** - * 执行时间 - */ - private String time; - /** - * 异常信息 - */ - private String exception; + /** + * 日志类型 + */ + private String type; + /** + * 日志标题 + */ + private String title; + /** + * 服务ID + */ + private String serviceId; + /** + * 服务器 ip + */ + private String serverIp; + /** + * 服务器名 + */ + private String serverHost; + /** + * 环境 + */ + private String env; + /** + * 操作IP地址 + */ + private String remoteIp; + /** + * 用户代理 + */ + private String userAgent; + /** + * 请求URI + */ + private String requestUri; + /** + * 操作方式 + */ + private String method; + /** + * 方法类 + */ + private String methodClass; + /** + * 方法名 + */ + private String methodName; + /** + * 操作提交的数据 + */ + private String params; + /** + * 执行时间 + */ + private String time; + /** + * 异常信息 + */ + private String exception; - /** - * 创建人 - */ - private String createBy; + /** + * 创建人 + */ + private String createBy; - /** - * 创建时间 - */ - @DateTimeFormat(pattern = DatePattern.NORM_DATETIME_PATTERN) - @JsonFormat(pattern = DatePattern.NORM_DATETIME_PATTERN) - private LocalDateTime createTime; + /** + * 创建时间 + */ + @DateTimeFormat(pattern = DatePattern.NORM_DATETIME_PATTERN) + @JsonFormat(pattern = DatePattern.NORM_DATETIME_PATTERN) + private LocalDateTime createTime; } diff --git a/blade-core-log/src/main/java/org/springblade/core/log/model/LogBlade.java b/blade-core-log/src/main/java/org/springblade/core/log/model/LogBlade.java index cd90e45..7b4ebb8 100644 --- a/blade-core-log/src/main/java/org/springblade/core/log/model/LogBlade.java +++ b/blade-core-log/src/main/java/org/springblade/core/log/model/LogBlade.java @@ -28,76 +28,76 @@ import java.io.Serializable; import java.time.LocalDateTime; /** - * 实体类 + * 实体类 * - * @author Blade + * @author smallchill * @since 2018-10-12 */ @Data @TableName("blade_log") public class LogBlade implements Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - /** - * 主键id - */ - @TableId(value = "id", type = IdType.ID_WORKER) - private Long id; - /** - * 服务ID - */ - private String serviceId; - /** - * 服务器名 - */ - private String serverHost; - /** - * 服务器IP地址 - */ - private String serverIp; - /** - * 系统环境 - */ - private String env; - /** - * 日志级别 - */ - private String logLevel; - /** - * 日志业务id - */ - private String logId; - /** - * 日志数据 - */ - private String logData; - /** - * 操作方式 - */ - private String method; - /** - * 请求URI - */ - private String requestUri; - /** - * 用户代理 - */ - private String userAgent; - /** - * 操作提交的数据 - */ - private String params; - /** - * 创建者 - */ - private String createBy; - /** - * 创建时间 - */ - @DateTimeFormat(pattern = DatePattern.NORM_DATETIME_PATTERN) - @JsonFormat(pattern = DatePattern.NORM_DATETIME_PATTERN) - private LocalDateTime createTime; + /** + * 主键id + */ + @TableId(value = "id", type = IdType.ID_WORKER) + private Long id; + /** + * 服务ID + */ + private String serviceId; + /** + * 服务器名 + */ + private String serverHost; + /** + * 服务器IP地址 + */ + private String serverIp; + /** + * 系统环境 + */ + private String env; + /** + * 日志级别 + */ + private String logLevel; + /** + * 日志业务id + */ + private String logId; + /** + * 日志数据 + */ + private String logData; + /** + * 操作方式 + */ + private String method; + /** + * 请求URI + */ + private String requestUri; + /** + * 用户代理 + */ + private String userAgent; + /** + * 操作提交的数据 + */ + private String params; + /** + * 创建者 + */ + private String createBy; + /** + * 创建时间 + */ + @DateTimeFormat(pattern = DatePattern.NORM_DATETIME_PATTERN) + @JsonFormat(pattern = DatePattern.NORM_DATETIME_PATTERN) + private LocalDateTime createTime; } diff --git a/blade-core-log/src/main/java/org/springblade/core/log/model/LogError.java b/blade-core-log/src/main/java/org/springblade/core/log/model/LogError.java index 287798e..7ebfb48 100644 --- a/blade-core-log/src/main/java/org/springblade/core/log/model/LogError.java +++ b/blade-core-log/src/main/java/org/springblade/core/log/model/LogError.java @@ -30,89 +30,91 @@ import java.time.LocalDateTime; /** * 服务 异常 + * + * @author smallchill */ @Data @TableName("blade_log_error") public class LogError implements Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - /** - * 主键id - */ - @TableId(value = "id", type = IdType.ID_WORKER) - private Long id; - /** - * 应用名 - */ - private String serviceId; - /** - * 环境 - */ - private String env; - /** - * 服务器 ip - */ - private String serverIp; - /** - * 服务器名 - */ - private String serverHost; - /** - * 用户代理 - */ - private String userAgent; - /** - * 请求url - */ - @Nullable - private String requestUri; - /** - * 操作方式 - */ - private String method; - /** - * 堆栈信息 - */ - private String stackTrace; - /** - * 异常名 - */ - private String exceptionName; - /** - * 异常消息 - */ - private String message; - /** - * 类名 - */ - private String methodClass; - /** - * 文件名 - */ - private String fileName; - /** - * 方法名 - */ - private String methodName; - /** - * 操作提交的数据 - */ - private String params; - /** - * 代码行数 - */ - private Integer lineNumber; + /** + * 主键id + */ + @TableId(value = "id", type = IdType.ID_WORKER) + private Long id; + /** + * 应用名 + */ + private String serviceId; + /** + * 环境 + */ + private String env; + /** + * 服务器 ip + */ + private String serverIp; + /** + * 服务器名 + */ + private String serverHost; + /** + * 用户代理 + */ + private String userAgent; + /** + * 请求url + */ + @Nullable + private String requestUri; + /** + * 操作方式 + */ + private String method; + /** + * 堆栈信息 + */ + private String stackTrace; + /** + * 异常名 + */ + private String exceptionName; + /** + * 异常消息 + */ + private String message; + /** + * 类名 + */ + private String methodClass; + /** + * 文件名 + */ + private String fileName; + /** + * 方法名 + */ + private String methodName; + /** + * 操作提交的数据 + */ + private String params; + /** + * 代码行数 + */ + private Integer lineNumber; - /** - * 创建人 - */ - private String createBy; + /** + * 创建人 + */ + private String createBy; - /** - * 创建时间 - */ - @DateTimeFormat(pattern = DatePattern.NORM_DATETIME_PATTERN) - @JsonFormat(pattern = DatePattern.NORM_DATETIME_PATTERN) - private LocalDateTime createTime; + /** + * 创建时间 + */ + @DateTimeFormat(pattern = DatePattern.NORM_DATETIME_PATTERN) + @JsonFormat(pattern = DatePattern.NORM_DATETIME_PATTERN) + private LocalDateTime createTime; } diff --git a/blade-core-log/src/main/java/org/springblade/core/log/publisher/ApiLogPublisher.java b/blade-core-log/src/main/java/org/springblade/core/log/publisher/ApiLogPublisher.java index 2c4b690..7476c17 100644 --- a/blade-core-log/src/main/java/org/springblade/core/log/publisher/ApiLogPublisher.java +++ b/blade-core-log/src/main/java/org/springblade/core/log/publisher/ApiLogPublisher.java @@ -30,21 +30,23 @@ import java.util.Map; /** * API日志信息事件发送 + * + * @author smallchill */ public class ApiLogPublisher { - public static void publishEvent(String methodName, String methodClass, ApiLog apiLog, long time) { - HttpServletRequest request = WebUtil.getRequest(); - LogApi logApi = new LogApi(); - logApi.setType(BladeConstant.LOG_NORMAL_TYPE); - logApi.setTitle(apiLog.value()); - logApi.setTime(String.valueOf(time)); - logApi.setMethodClass(methodClass); - logApi.setMethodName(methodName); - Map event = new HashMap<>(); - event.put(EventConstant.EVENT_LOG, logApi); - event.put(EventConstant.EVENT_REQUEST, request); - SpringUtil.publishEvent(new ApiLogEvent(event)); - } + public static void publishEvent(String methodName, String methodClass, ApiLog apiLog, long time) { + HttpServletRequest request = WebUtil.getRequest(); + LogApi logApi = new LogApi(); + logApi.setType(BladeConstant.LOG_NORMAL_TYPE); + logApi.setTitle(apiLog.value()); + logApi.setTime(String.valueOf(time)); + logApi.setMethodClass(methodClass); + logApi.setMethodName(methodName); + Map event = new HashMap<>(); + event.put(EventConstant.EVENT_LOG, logApi); + event.put(EventConstant.EVENT_REQUEST, request); + SpringUtil.publishEvent(new ApiLogEvent(event)); + } } diff --git a/blade-core-log/src/main/java/org/springblade/core/log/publisher/BladeLogPublisher.java b/blade-core-log/src/main/java/org/springblade/core/log/publisher/BladeLogPublisher.java index 918800b..c851dab 100644 --- a/blade-core-log/src/main/java/org/springblade/core/log/publisher/BladeLogPublisher.java +++ b/blade-core-log/src/main/java/org/springblade/core/log/publisher/BladeLogPublisher.java @@ -28,19 +28,21 @@ import java.util.Map; /** * BLADE日志信息事件发送 + * + * @author smallchill */ public class BladeLogPublisher { - public static void publishEvent(String level, String id, String data) { - HttpServletRequest request = WebUtil.getRequest(); - LogBlade logBlade = new LogBlade(); - logBlade.setLogLevel(level); - logBlade.setLogId(id); - logBlade.setLogData(data); - Map event = new HashMap<>(); - event.put(EventConstant.EVENT_LOG, logBlade); - event.put(EventConstant.EVENT_REQUEST, request); - SpringUtil.publishEvent(new BladeLogEvent(event)); - } + public static void publishEvent(String level, String id, String data) { + HttpServletRequest request = WebUtil.getRequest(); + LogBlade logBlade = new LogBlade(); + logBlade.setLogLevel(level); + logBlade.setLogId(id); + logBlade.setLogData(data); + Map event = new HashMap<>(); + event.put(EventConstant.EVENT_LOG, logBlade); + event.put(EventConstant.EVENT_REQUEST, request); + SpringUtil.publishEvent(new BladeLogEvent(event)); + } } diff --git a/blade-core-log/src/main/java/org/springblade/core/log/publisher/ErrorLogPublisher.java b/blade-core-log/src/main/java/org/springblade/core/log/publisher/ErrorLogPublisher.java index 4748509..3e899ed 100644 --- a/blade-core-log/src/main/java/org/springblade/core/log/publisher/ErrorLogPublisher.java +++ b/blade-core-log/src/main/java/org/springblade/core/log/publisher/ErrorLogPublisher.java @@ -27,30 +27,32 @@ import java.util.Map; /** * 异常信息事件发送 + * + * @author smallchill */ public class ErrorLogPublisher { - public static void publishEvent(Throwable error, String requestUri) { - HttpServletRequest request = WebUtil.getRequest(); - LogError logError = new LogError(); - logError.setRequestUri(requestUri); - if (Func.isNotEmpty(error)) { - logError.setStackTrace(Exceptions.getStackTraceAsString(error)); - logError.setExceptionName(error.getClass().getName()); - logError.setMessage(error.getMessage()); - StackTraceElement[] elements = error.getStackTrace(); - if (Func.isNotEmpty(elements)) { - StackTraceElement element = elements[0]; - logError.setMethodName(element.getMethodName()); - logError.setMethodClass(element.getClassName()); - logError.setFileName(element.getFileName()); - logError.setLineNumber(element.getLineNumber()); - } - } - Map event = new HashMap<>(); - event.put(EventConstant.EVENT_LOG, logError); - event.put(EventConstant.EVENT_REQUEST, request); - SpringUtil.publishEvent(new ErrorLogEvent(event)); - } + public static void publishEvent(Throwable error, String requestUri) { + HttpServletRequest request = WebUtil.getRequest(); + LogError logError = new LogError(); + logError.setRequestUri(requestUri); + if (Func.isNotEmpty(error)) { + logError.setStackTrace(Exceptions.getStackTraceAsString(error)); + logError.setExceptionName(error.getClass().getName()); + logError.setMessage(error.getMessage()); + StackTraceElement[] elements = error.getStackTrace(); + if (Func.isNotEmpty(elements)) { + StackTraceElement element = elements[0]; + logError.setMethodName(element.getMethodName()); + logError.setMethodClass(element.getClassName()); + logError.setFileName(element.getFileName()); + logError.setLineNumber(element.getLineNumber()); + } + } + Map event = new HashMap<>(16); + event.put(EventConstant.EVENT_LOG, logError); + event.put(EventConstant.EVENT_REQUEST, request); + SpringUtil.publishEvent(new ErrorLogEvent(event)); + } } diff --git a/blade-core-mybatis/src/main/java/org/springblade/core/mp/BladeMetaObjectHandler.java b/blade-core-mybatis/src/main/java/org/springblade/core/mp/BladeMetaObjectHandler.java index 43cc93a..48df097 100644 --- a/blade-core-mybatis/src/main/java/org/springblade/core/mp/BladeMetaObjectHandler.java +++ b/blade-core-mybatis/src/main/java/org/springblade/core/mp/BladeMetaObjectHandler.java @@ -21,6 +21,8 @@ import org.apache.ibatis.reflection.MetaObject; /** * mybatisplus自定义填充 + * + * @author smallchill */ @Slf4j public class BladeMetaObjectHandler implements MetaObjectHandler { diff --git a/blade-core-mybatis/src/main/java/org/springblade/core/mp/base/BaseEntity.java b/blade-core-mybatis/src/main/java/org/springblade/core/mp/base/BaseEntity.java index 0fc282c..06c3a63 100644 --- a/blade-core-mybatis/src/main/java/org/springblade/core/mp/base/BaseEntity.java +++ b/blade-core-mybatis/src/main/java/org/springblade/core/mp/base/BaseEntity.java @@ -27,6 +27,11 @@ import org.springframework.format.annotation.DateTimeFormat; import java.io.Serializable; import java.time.LocalDateTime; +/** + * 基础实体类 + * + * @author smallchill + */ @Data public class BaseEntity implements Serializable { /** @@ -36,33 +41,33 @@ public class BaseEntity implements Serializable { @ApiModelProperty(value = "主键id") private Integer id; - /** - * 创建人 - */ + /** + * 创建人 + */ @ApiModelProperty(value = "创建人") - private Integer createUser; + private Integer createUser; - /** - * 创建时间 - */ - @DateTimeFormat(pattern = DatePattern.NORM_DATETIME_PATTERN) - @JsonFormat(pattern = DatePattern.NORM_DATETIME_PATTERN) + /** + * 创建时间 + */ + @DateTimeFormat(pattern = DatePattern.NORM_DATETIME_PATTERN) + @JsonFormat(pattern = DatePattern.NORM_DATETIME_PATTERN) @ApiModelProperty(value = "创建时间") - private LocalDateTime createTime; + private LocalDateTime createTime; - /** - * 更新人 - */ + /** + * 更新人 + */ @ApiModelProperty(value = "更新人") - private Integer updateUser; + private Integer updateUser; - /** - * 更新时间 - */ - @DateTimeFormat(pattern = DatePattern.NORM_DATETIME_PATTERN) - @JsonFormat(pattern = DatePattern.NORM_DATETIME_PATTERN) + /** + * 更新时间 + */ + @DateTimeFormat(pattern = DatePattern.NORM_DATETIME_PATTERN) + @JsonFormat(pattern = DatePattern.NORM_DATETIME_PATTERN) @ApiModelProperty(value = "更新时间") - private LocalDateTime updateTime; + private LocalDateTime updateTime; /** * 状态[1:正常] @@ -70,9 +75,9 @@ public class BaseEntity implements Serializable { @ApiModelProperty(value = "业务状态") private Integer status; - /** - * 状态[0:未删除,1:删除] - */ + /** + * 状态[0:未删除,1:删除] + */ @ApiModelProperty(value = "是否已删除") - private Integer isDeleted; + private Integer isDeleted; } diff --git a/blade-core-mybatis/src/main/java/org/springblade/core/mp/base/BaseService.java b/blade-core-mybatis/src/main/java/org/springblade/core/mp/base/BaseService.java index 5210240..66fa6d2 100644 --- a/blade-core-mybatis/src/main/java/org/springblade/core/mp/base/BaseService.java +++ b/blade-core-mybatis/src/main/java/org/springblade/core/mp/base/BaseService.java @@ -20,13 +20,20 @@ import com.baomidou.mybatisplus.extension.service.IService; import javax.validation.constraints.NotEmpty; import java.util.List; +/** + * 基础业务接口 + * + * @param + * @author smallchill + */ public interface BaseService extends IService { - /** - * 逻辑删除 - * @param ids id集合(逗号分隔) - * @return - */ + /** + * 逻辑删除 + * + * @param ids id集合(逗号分隔) + * @return + */ boolean deleteLogic(@NotEmpty List ids); } diff --git a/blade-core-mybatis/src/main/java/org/springblade/core/mp/base/BaseServiceImpl.java b/blade-core-mybatis/src/main/java/org/springblade/core/mp/base/BaseServiceImpl.java index 0e4ed6c..8811c34 100644 --- a/blade-core-mybatis/src/main/java/org/springblade/core/mp/base/BaseServiceImpl.java +++ b/blade-core-mybatis/src/main/java/org/springblade/core/mp/base/BaseServiceImpl.java @@ -35,6 +35,7 @@ import java.util.List; * * @param mapper * @param model + * @author smallchill */ @Validated public class BaseServiceImpl, T extends BaseEntity> extends ServiceImpl implements BaseService { diff --git a/blade-core-mybatis/src/main/java/org/springblade/core/mp/support/BaseEntityWrapper.java b/blade-core-mybatis/src/main/java/org/springblade/core/mp/support/BaseEntityWrapper.java index 69e74a0..ecee08e 100644 --- a/blade-core-mybatis/src/main/java/org/springblade/core/mp/support/BaseEntityWrapper.java +++ b/blade-core-mybatis/src/main/java/org/springblade/core/mp/support/BaseEntityWrapper.java @@ -23,6 +23,8 @@ import java.util.stream.Collectors; /** * 视图包装基类 + * + * @author smallchill */ public abstract class BaseEntityWrapper { diff --git a/blade-core-mybatis/src/main/java/org/springblade/core/mp/support/Condition.java b/blade-core-mybatis/src/main/java/org/springblade/core/mp/support/Condition.java index 5bb184e..7dec60a 100644 --- a/blade-core-mybatis/src/main/java/org/springblade/core/mp/support/Condition.java +++ b/blade-core-mybatis/src/main/java/org/springblade/core/mp/support/Condition.java @@ -25,6 +25,8 @@ import java.util.Map; /** * 分页工具 + * + * @author smallchill */ public class Condition { diff --git a/blade-core-mybatis/src/main/java/org/springblade/core/mp/support/Query.java b/blade-core-mybatis/src/main/java/org/springblade/core/mp/support/Query.java index f265e3f..26dae44 100644 --- a/blade-core-mybatis/src/main/java/org/springblade/core/mp/support/Query.java +++ b/blade-core-mybatis/src/main/java/org/springblade/core/mp/support/Query.java @@ -21,33 +21,35 @@ import lombok.Data; /** * 分页工具 + * + * @author smallchill */ @Data @ApiModel(description = "查询条件") public class Query { - /** - * 当前页 - */ - @ApiModelProperty(value = "当前页") - private Integer current; + /** + * 当前页 + */ + @ApiModelProperty(value = "当前页") + private Integer current; - /** - * 每页的数量 - */ - @ApiModelProperty(value = "每页的数量") - private Integer size; + /** + * 每页的数量 + */ + @ApiModelProperty(value = "每页的数量") + private Integer size; - /** - * 排序的字段名 - */ - @ApiModelProperty(value = "升序字段") - private String ascs; + /** + * 排序的字段名 + */ + @ApiModelProperty(value = "升序字段") + private String ascs; - /** - * 排序方式 - */ - @ApiModelProperty(value = "降序字段") - private String descs; + /** + * 排序方式 + */ + @ApiModelProperty(value = "降序字段") + private String descs; } diff --git a/blade-core-secure/src/main/java/org/springblade/core/secure/AuthInfo.java b/blade-core-secure/src/main/java/org/springblade/core/secure/AuthInfo.java index 0df84f8..69d7a51 100644 --- a/blade-core-secure/src/main/java/org/springblade/core/secure/AuthInfo.java +++ b/blade-core-secure/src/main/java/org/springblade/core/secure/AuthInfo.java @@ -21,6 +21,8 @@ import lombok.Data; /** * AuthInfo + * + * @author smallchill */ @Data @ApiModel(description = "认证信息") diff --git a/blade-core-secure/src/main/java/org/springblade/core/secure/BladeUser.java b/blade-core-secure/src/main/java/org/springblade/core/secure/BladeUser.java index 421bea2..8531d2e 100644 --- a/blade-core-secure/src/main/java/org/springblade/core/secure/BladeUser.java +++ b/blade-core-secure/src/main/java/org/springblade/core/secure/BladeUser.java @@ -15,12 +15,15 @@ */ package org.springblade.core.secure; +import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.io.Serializable; /** * 用户实体 + * + * @author smallchill */ @Data public class BladeUser implements Serializable { @@ -30,23 +33,27 @@ public class BladeUser implements Serializable { /** * 主键 */ + @ApiModelProperty(hidden = true) private Integer userId; /** * 昵称 */ + @ApiModelProperty(hidden = true) private String userName; /** * 账号 */ + @ApiModelProperty(hidden = true) private String account; /** * 角色id */ + @ApiModelProperty(hidden = true) private String roleId; /** * 角色名 */ + @ApiModelProperty(hidden = true) private String roleName; - } diff --git a/blade-core-secure/src/main/java/org/springblade/core/secure/annotation/PreAuth.java b/blade-core-secure/src/main/java/org/springblade/core/secure/annotation/PreAuth.java index baa1567..71df410 100644 --- a/blade-core-secure/src/main/java/org/springblade/core/secure/annotation/PreAuth.java +++ b/blade-core-secure/src/main/java/org/springblade/core/secure/annotation/PreAuth.java @@ -20,6 +20,7 @@ import java.lang.annotation.*; /** * 权限注解 用于检查权限 规定访问权限 * + * @author smallchill * @example @PreAuth("#userVO.id<10") * @example @PreAuth("hasRole(#test, #test1)") * @example @PreAuth("hasPermission(#test) and @PreAuth.hasPermission(#test)") diff --git a/blade-core-secure/src/main/java/org/springblade/core/secure/aspect/AuthAspect.java b/blade-core-secure/src/main/java/org/springblade/core/secure/aspect/AuthAspect.java index 4ba4c1d..53b3632 100644 --- a/blade-core-secure/src/main/java/org/springblade/core/secure/aspect/AuthAspect.java +++ b/blade-core-secure/src/main/java/org/springblade/core/secure/aspect/AuthAspect.java @@ -39,6 +39,8 @@ import java.lang.reflect.Method; /** * AOP 鉴权 + * + * @author smallchill */ @Aspect public class AuthAspect implements ApplicationContextAware { @@ -50,13 +52,14 @@ public class AuthAspect implements ApplicationContextAware { /** * 切 方法 和 类上的 @PreAuth 注解 + * * @param point 切点 * @return Object * @throws Throwable 没有权限的异常 */ @Around( "@annotation(org.springblade.core.secure.annotation.PreAuth) || " + - "@within(org.springblade.core.secure.annotation.PreAuth)" + "@within(org.springblade.core.secure.annotation.PreAuth)" ) public Object preAuth(ProceedingJoinPoint point) throws Throwable { if (handleAuth(point)) { @@ -91,7 +94,7 @@ public class AuthAspect implements ApplicationContextAware { * 获取方法上的参数 * * @param method 方法 - * @param args 变量 + * @param args 变量 * @return {SimpleEvaluationContext} */ private StandardEvaluationContext getEvaluationContext(Method method, Object[] args) { diff --git a/blade-core-secure/src/main/java/org/springblade/core/secure/auth/AuthFun.java b/blade-core-secure/src/main/java/org/springblade/core/secure/auth/AuthFun.java index 6a597f4..ad8ed50 100644 --- a/blade-core-secure/src/main/java/org/springblade/core/secure/auth/AuthFun.java +++ b/blade-core-secure/src/main/java/org/springblade/core/secure/auth/AuthFun.java @@ -23,6 +23,8 @@ import org.springblade.core.tool.utils.StringUtil; /** * 权限判断 + * + * @author smallchill */ public class AuthFun { diff --git a/blade-core-secure/src/main/java/org/springblade/core/secure/config/RegistryConfiguration.java b/blade-core-secure/src/main/java/org/springblade/core/secure/config/RegistryConfiguration.java index 1b98956..fbf3a1a 100644 --- a/blade-core-secure/src/main/java/org/springblade/core/secure/config/RegistryConfiguration.java +++ b/blade-core-secure/src/main/java/org/springblade/core/secure/config/RegistryConfiguration.java @@ -24,6 +24,8 @@ import org.springframework.context.annotation.Configuration; /** * secure模块api放行默认配置 + * + * @author smallchill */ @Configuration @AutoConfigureBefore(SecureConfiguration.class) diff --git a/blade-core-secure/src/main/java/org/springblade/core/secure/config/SecureConfiguration.java b/blade-core-secure/src/main/java/org/springblade/core/secure/config/SecureConfiguration.java index 3bc59e6..ae8dac9 100644 --- a/blade-core-secure/src/main/java/org/springblade/core/secure/config/SecureConfiguration.java +++ b/blade-core-secure/src/main/java/org/springblade/core/secure/config/SecureConfiguration.java @@ -26,6 +26,11 @@ import org.springframework.core.annotation.Order; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +/** + * 配置类 + * + * @author smallchill + */ @Order @Configuration @AllArgsConstructor diff --git a/blade-core-secure/src/main/java/org/springblade/core/secure/exception/SecureException.java b/blade-core-secure/src/main/java/org/springblade/core/secure/exception/SecureException.java index 898cf86..434fe05 100644 --- a/blade-core-secure/src/main/java/org/springblade/core/secure/exception/SecureException.java +++ b/blade-core-secure/src/main/java/org/springblade/core/secure/exception/SecureException.java @@ -21,6 +21,8 @@ import org.springblade.core.tool.api.ResultCode; /** * Secure异常 + * + * @author smallchill */ public class SecureException extends RuntimeException { private static final long serialVersionUID = 2359767895161832954L; diff --git a/blade-core-secure/src/main/java/org/springblade/core/secure/interceptor/SecureInterceptor.java b/blade-core-secure/src/main/java/org/springblade/core/secure/interceptor/SecureInterceptor.java index 9342e03..ccafa8b 100644 --- a/blade-core-secure/src/main/java/org/springblade/core/secure/interceptor/SecureInterceptor.java +++ b/blade-core-secure/src/main/java/org/springblade/core/secure/interceptor/SecureInterceptor.java @@ -32,6 +32,8 @@ import java.util.Objects; /** * jwt拦截器校验 + * + * @author smallchill */ @Slf4j public class SecureInterceptor extends HandlerInterceptorAdapter { diff --git a/blade-core-secure/src/main/java/org/springblade/core/secure/registry/SecureRegistry.java b/blade-core-secure/src/main/java/org/springblade/core/secure/registry/SecureRegistry.java index b15ce1c..b722cb7 100644 --- a/blade-core-secure/src/main/java/org/springblade/core/secure/registry/SecureRegistry.java +++ b/blade-core-secure/src/main/java/org/springblade/core/secure/registry/SecureRegistry.java @@ -23,6 +23,8 @@ import java.util.List; /** * secure api放行配置 + * + * @author smallchill */ @Data public class SecureRegistry { diff --git a/blade-core-secure/src/main/java/org/springblade/core/secure/utils/SecureUtil.java b/blade-core-secure/src/main/java/org/springblade/core/secure/utils/SecureUtil.java index c2630ac..f64323f 100644 --- a/blade-core-secure/src/main/java/org/springblade/core/secure/utils/SecureUtil.java +++ b/blade-core-secure/src/main/java/org/springblade/core/secure/utils/SecureUtil.java @@ -36,6 +36,8 @@ import java.util.Map; /** * Secure工具类 + * + * @author smallchill */ public class SecureUtil { public static final String BLADE_USER_REQUEST_ATTR = "_BLADE_USER_REQUEST_ATTR_"; @@ -91,9 +93,9 @@ public class SecureUtil { } - /** * 获取用户id + * * @return */ public static Integer getUserId() { @@ -102,6 +104,7 @@ public class SecureUtil { /** * 获取用户id + * * @return */ public static Integer getUserId(HttpServletRequest request) { @@ -110,6 +113,7 @@ public class SecureUtil { /** * 获取用户账号 + * * @return */ public static String getUserAccount() { @@ -118,6 +122,7 @@ public class SecureUtil { /** * 获取用户账号 + * * @return */ public static String getUserAccount(HttpServletRequest request) { diff --git a/blade-core-swagger/src/main/java/org/springblade/core/swagger/SwaggerAutoConfiguration.java b/blade-core-swagger/src/main/java/org/springblade/core/swagger/SwaggerAutoConfiguration.java index dcefce2..bc81bb6 100644 --- a/blade-core-swagger/src/main/java/org/springblade/core/swagger/SwaggerAutoConfiguration.java +++ b/blade-core-swagger/src/main/java/org/springblade/core/swagger/SwaggerAutoConfiguration.java @@ -39,6 +39,8 @@ import java.util.List; /** * swagger配置 + * + * @author smallchill */ @Configuration @EnableSwagger2 @@ -47,90 +49,90 @@ import java.util.List; @EnableConfigurationProperties(SwaggerProperties.class) public class SwaggerAutoConfiguration { - private static final String DEFAULT_EXCLUDE_PATH = "/error"; - private static final String BASE_PATH = "/**"; + private static final String DEFAULT_EXCLUDE_PATH = "/error"; + private static final String BASE_PATH = "/**"; - @Bean - @ConditionalOnMissingBean - public SwaggerProperties swaggerProperties() { - return new SwaggerProperties(); - } + @Bean + @ConditionalOnMissingBean + public SwaggerProperties swaggerProperties() { + return new SwaggerProperties(); + } - @Bean - public Docket api(SwaggerProperties swaggerProperties) { - // base-path处理 - if (swaggerProperties.getBasePath().size() == 0) { - swaggerProperties.getBasePath().add(BASE_PATH); - } - //noinspection unchecked - List> basePath = new ArrayList(); - swaggerProperties.getBasePath().forEach(path -> basePath.add(PathSelectors.ant(path))); + @Bean + public Docket api(SwaggerProperties swaggerProperties) { + // base-path处理 + if (swaggerProperties.getBasePath().size() == 0) { + swaggerProperties.getBasePath().add(BASE_PATH); + } + //noinspection unchecked + List> basePath = new ArrayList(); + swaggerProperties.getBasePath().forEach(path -> basePath.add(PathSelectors.ant(path))); - // exclude-path处理 - if (swaggerProperties.getExcludePath().size() == 0) { - swaggerProperties.getExcludePath().add(DEFAULT_EXCLUDE_PATH); - } - List> excludePath = new ArrayList<>(); - swaggerProperties.getExcludePath().forEach(path -> excludePath.add(PathSelectors.ant(path))); + // exclude-path处理 + if (swaggerProperties.getExcludePath().size() == 0) { + swaggerProperties.getExcludePath().add(DEFAULT_EXCLUDE_PATH); + } + List> excludePath = new ArrayList<>(); + swaggerProperties.getExcludePath().forEach(path -> excludePath.add(PathSelectors.ant(path))); - //noinspection Guava - return new Docket(DocumentationType.SWAGGER_2) - .host(swaggerProperties.getHost()) - .apiInfo(apiInfo(swaggerProperties)).select() - .apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage())) - .paths(Predicates.and(Predicates.not(Predicates.or(excludePath)), Predicates.or(basePath))) - .build() - .securitySchemes(Collections.singletonList(securitySchema())) - .securityContexts(Collections.singletonList(securityContext())) - .pathMapping("/" ); - } + //noinspection Guava + return new Docket(DocumentationType.SWAGGER_2) + .host(swaggerProperties.getHost()) + .apiInfo(apiInfo(swaggerProperties)).select() + .apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage())) + .paths(Predicates.and(Predicates.not(Predicates.or(excludePath)), Predicates.or(basePath))) + .build() + .securitySchemes(Collections.singletonList(securitySchema())) + .securityContexts(Collections.singletonList(securityContext())) + .pathMapping("/"); + } - /** - * 配置默认的全局鉴权策略的开关,通过正则表达式进行匹配;默认匹配所有URL - * - * @return - */ - private SecurityContext securityContext() { - return SecurityContext.builder() - .securityReferences(defaultAuth()) - .forPaths(PathSelectors.regex(swaggerProperties().getAuthorization().getAuthRegex())) - .build(); - } + /** + * 配置默认的全局鉴权策略的开关,通过正则表达式进行匹配;默认匹配所有URL + * + * @return + */ + private SecurityContext securityContext() { + return SecurityContext.builder() + .securityReferences(defaultAuth()) + .forPaths(PathSelectors.regex(swaggerProperties().getAuthorization().getAuthRegex())) + .build(); + } - /** - * 默认的全局鉴权策略 - * - * @return - */ - private List defaultAuth() { - ArrayList authorizationScopeList = new ArrayList<>(); - swaggerProperties().getAuthorization().getAuthorizationScopeList().forEach(authorizationScope -> authorizationScopeList.add(new AuthorizationScope(authorizationScope.getScope(), authorizationScope.getDescription()))); - AuthorizationScope[] authorizationScopes = new AuthorizationScope[authorizationScopeList.size()]; - return Collections.singletonList(SecurityReference.builder() - .reference(swaggerProperties().getAuthorization().getName()) - .scopes(authorizationScopeList.toArray(authorizationScopes)) - .build()); - } + /** + * 默认的全局鉴权策略 + * + * @return + */ + private List defaultAuth() { + ArrayList authorizationScopeList = new ArrayList<>(); + swaggerProperties().getAuthorization().getAuthorizationScopeList().forEach(authorizationScope -> authorizationScopeList.add(new AuthorizationScope(authorizationScope.getScope(), authorizationScope.getDescription()))); + AuthorizationScope[] authorizationScopes = new AuthorizationScope[authorizationScopeList.size()]; + return Collections.singletonList(SecurityReference.builder() + .reference(swaggerProperties().getAuthorization().getName()) + .scopes(authorizationScopeList.toArray(authorizationScopes)) + .build()); + } - private OAuth securitySchema() { - ArrayList authorizationScopeList = new ArrayList<>(); - swaggerProperties().getAuthorization().getAuthorizationScopeList().forEach(authorizationScope -> authorizationScopeList.add(new AuthorizationScope(authorizationScope.getScope(), authorizationScope.getDescription()))); - ArrayList grantTypes = new ArrayList<>(); - swaggerProperties().getAuthorization().getTokenUrlList().forEach(tokenUrl -> grantTypes.add(new ResourceOwnerPasswordCredentialsGrant(tokenUrl))); - return new OAuth(swaggerProperties().getAuthorization().getName(), authorizationScopeList, grantTypes); - } + private OAuth securitySchema() { + ArrayList authorizationScopeList = new ArrayList<>(); + swaggerProperties().getAuthorization().getAuthorizationScopeList().forEach(authorizationScope -> authorizationScopeList.add(new AuthorizationScope(authorizationScope.getScope(), authorizationScope.getDescription()))); + ArrayList grantTypes = new ArrayList<>(); + swaggerProperties().getAuthorization().getTokenUrlList().forEach(tokenUrl -> grantTypes.add(new ResourceOwnerPasswordCredentialsGrant(tokenUrl))); + return new OAuth(swaggerProperties().getAuthorization().getName(), authorizationScopeList, grantTypes); + } - private ApiInfo apiInfo(SwaggerProperties swaggerProperties) { - return new ApiInfoBuilder() - .title(swaggerProperties.getTitle()) - .description(swaggerProperties.getDescription()) - .license(swaggerProperties.getLicense()) - .licenseUrl(swaggerProperties.getLicenseUrl()) - .termsOfServiceUrl(swaggerProperties.getTermsOfServiceUrl()) - .contact(new Contact(swaggerProperties.getContact().getName(), swaggerProperties.getContact().getUrl(), swaggerProperties.getContact().getEmail())) - .version(swaggerProperties.getVersion()) - .build(); - } + private ApiInfo apiInfo(SwaggerProperties swaggerProperties) { + return new ApiInfoBuilder() + .title(swaggerProperties.getTitle()) + .description(swaggerProperties.getDescription()) + .license(swaggerProperties.getLicense()) + .licenseUrl(swaggerProperties.getLicenseUrl()) + .termsOfServiceUrl(swaggerProperties.getTermsOfServiceUrl()) + .contact(new Contact(swaggerProperties.getContact().getName(), swaggerProperties.getContact().getUrl(), swaggerProperties.getContact().getEmail())) + .version(swaggerProperties.getVersion()) + .build(); + } } diff --git a/blade-core-swagger/src/main/java/org/springblade/core/swagger/SwaggerProperties.java b/blade-core-swagger/src/main/java/org/springblade/core/swagger/SwaggerProperties.java index 3b546b0..3ad7926 100644 --- a/blade-core-swagger/src/main/java/org/springblade/core/swagger/SwaggerProperties.java +++ b/blade-core-swagger/src/main/java/org/springblade/core/swagger/SwaggerProperties.java @@ -25,6 +25,8 @@ import java.util.List; /** * SwaggerProperties + * + * @author smallchill */ @Data @RefreshScope diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/api/IResultCode.java b/blade-core-tool/src/main/java/org/springblade/core/tool/api/IResultCode.java index 4317929..430e888 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/api/IResultCode.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/api/IResultCode.java @@ -19,11 +19,23 @@ import java.io.Serializable; /** * 业务代码接口 + * + * @author smallchill */ public interface IResultCode extends Serializable { - String getMessage(); + /** + * 消息 + * + * @return + */ + String getMessage(); - int getCode(); + /** + * 状态码 + * + * @return + */ + int getCode(); } diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/api/R.java b/blade-core-tool/src/main/java/org/springblade/core/tool/api/R.java index b19d01a..f1690a4 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/api/R.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/api/R.java @@ -28,6 +28,8 @@ import java.util.Optional; /** * 统一API响应结果封装 + * + * @author smallchill */ @Getter @Setter @@ -36,32 +38,32 @@ import java.util.Optional; @NoArgsConstructor(access = AccessLevel.PRIVATE) public class R implements Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - @ApiModelProperty(value = "状态码", required = true) - private int code; + @ApiModelProperty(value = "状态码", required = true) + private int code; @ApiModelProperty(value = "是否成功", required = true) private boolean success; - @ApiModelProperty(value = "承载数据") - private T data; - @ApiModelProperty(value = "返回消息", required = true) - private String msg; + @ApiModelProperty(value = "承载数据") + private T data; + @ApiModelProperty(value = "返回消息", required = true) + private String msg; - private R(IResultCode resultCode) { - this(resultCode, null, resultCode.getMessage()); - } + private R(IResultCode resultCode) { + this(resultCode, null, resultCode.getMessage()); + } - private R(IResultCode resultCode, String msg) { - this(resultCode, null, msg); - } + private R(IResultCode resultCode, String msg) { + this(resultCode, null, msg); + } - private R(IResultCode resultCode, T data) { - this(resultCode, data, resultCode.getMessage()); - } + private R(IResultCode resultCode, T data) { + this(resultCode, data, resultCode.getMessage()); + } - private R(IResultCode resultCode, T data, String msg) { - this(resultCode.getCode(), data, msg); - } + private R(IResultCode resultCode, T data, String msg) { + this(resultCode.getCode(), data, msg); + } private R(int code, T data, String msg) { this.code = code; @@ -92,97 +94,108 @@ public class R implements Serializable { return !R.isSuccess(result); } - /** - * 返回R - * @param data 数据 - */ - public static R data(T data) { - return data(data, BladeConstant.DEFAULT_SUCCESS_MESSAGE); - } + /** + * 返回R + * + * @param data 数据 + */ + public static R data(T data) { + return data(data, BladeConstant.DEFAULT_SUCCESS_MESSAGE); + } - /** - * 返回R - * @param data 数据 - * @param msg 消息 - */ - public static R data(T data, String msg) { - return data(HttpServletResponse.SC_OK, data, msg); - } + /** + * 返回R + * + * @param data 数据 + * @param msg 消息 + */ + public static R data(T data, String msg) { + return data(HttpServletResponse.SC_OK, data, msg); + } - /** - * 返回R - * @param code 状态码 - * @param data 数据 - * @param msg 消息 - */ - public static R data(int code, T data, String msg) { - return new R<>(code, data, data == null ? BladeConstant.DEFAULT_NULL_MESSAGE : msg); - } + /** + * 返回R + * + * @param code 状态码 + * @param data 数据 + * @param msg 消息 + */ + public static R data(int code, T data, String msg) { + return new R<>(code, data, data == null ? BladeConstant.DEFAULT_NULL_MESSAGE : msg); + } - /** - * 返回R - * @param msg 消息 - */ - public static R success(String msg) { - return new R<>(ResultCode.SUCCESS, msg); - } + /** + * 返回R + * + * @param msg 消息 + */ + public static R success(String msg) { + return new R<>(ResultCode.SUCCESS, msg); + } - /** - * 返回R - * @param resultCode 业务代码 - */ - public static R success(IResultCode resultCode) { - return new R<>(resultCode); - } + /** + * 返回R + * + * @param resultCode 业务代码 + */ + public static R success(IResultCode resultCode) { + return new R<>(resultCode); + } - /** - * 返回R - * @param resultCode 业务代码 - */ - public static R success(IResultCode resultCode, String msg) { - return new R<>(resultCode, msg); - } + /** + * 返回R + * + * @param resultCode 业务代码 + */ + public static R success(IResultCode resultCode, String msg) { + return new R<>(resultCode, msg); + } - /** - * 返回R - * @param msg 消息 - */ - public static R failure(String msg) { - return new R<>(ResultCode.FAILURE, msg); - } + /** + * 返回R + * + * @param msg 消息 + */ + public static R failure(String msg) { + return new R<>(ResultCode.FAILURE, msg); + } - /** - * 返回R - * @param code 状态码 - * @param msg 消息 - */ - public static R failure(int code, String msg) { - return new R<>(code, null, msg); - } + /** + * 返回R + * + * @param code 状态码 + * @param msg 消息 + */ + public static R failure(int code, String msg) { + return new R<>(code, null, msg); + } - /** - * 返回R - * @param resultCode 业务代码 - */ - public static R failure(IResultCode resultCode) { - return new R<>(resultCode); - } + /** + * 返回R + * + * @param resultCode 业务代码 + */ + public static R failure(IResultCode resultCode) { + return new R<>(resultCode); + } - /** - * 返回R - * @param resultCode 业务代码 - */ - public static R failure(IResultCode resultCode, String msg) { - return new R<>(resultCode, msg); - } + /** + * 返回R + * + * @param resultCode 业务代码 + */ + public static R failure(IResultCode resultCode, String msg) { + return new R<>(resultCode, msg); + } - /** - * 返回R - * @param flag 成功状态 - */ - public static R status(boolean flag) { - return flag ? success(BladeConstant.DEFAULT_SUCCESS_MESSAGE) : failure(BladeConstant.DEFAULT_FAILURE_MESSAGE); - } + /** + * 返回R + * + * @param flag 成功状态 + */ + public static R status(boolean flag) { + return flag ? success(BladeConstant.DEFAULT_SUCCESS_MESSAGE) : failure(BladeConstant.DEFAULT_FAILURE_MESSAGE); + } } diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/api/ResultCode.java b/blade-core-tool/src/main/java/org/springblade/core/tool/api/ResultCode.java index 4841052..72fb9e5 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/api/ResultCode.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/api/ResultCode.java @@ -22,84 +22,86 @@ import javax.servlet.http.HttpServletResponse; /** * 业务代码枚举 + * + * @author smallchill */ @Getter @AllArgsConstructor public enum ResultCode implements IResultCode { - /** - * 操作成功 - */ - SUCCESS(HttpServletResponse.SC_OK, "操作成功"), + /** + * 操作成功 + */ + SUCCESS(HttpServletResponse.SC_OK, "操作成功"), - /** - * 业务异常 - */ - FAILURE(HttpServletResponse.SC_BAD_REQUEST, "业务异常"), + /** + * 业务异常 + */ + FAILURE(HttpServletResponse.SC_BAD_REQUEST, "业务异常"), - /** - * 请求未授权 - */ - UN_AUTHORIZED(HttpServletResponse.SC_UNAUTHORIZED, "请求未授权"), + /** + * 请求未授权 + */ + UN_AUTHORIZED(HttpServletResponse.SC_UNAUTHORIZED, "请求未授权"), - /** - * 404 没找到请求 - */ - NOT_FOUND(HttpServletResponse.SC_NOT_FOUND, "404 没找到请求"), + /** + * 404 没找到请求 + */ + NOT_FOUND(HttpServletResponse.SC_NOT_FOUND, "404 没找到请求"), - /** - * 消息不能读取 - */ - MSG_NOT_READABLE(HttpServletResponse.SC_BAD_REQUEST, "消息不能读取"), + /** + * 消息不能读取 + */ + MSG_NOT_READABLE(HttpServletResponse.SC_BAD_REQUEST, "消息不能读取"), - /** - * 不支持当前请求方法 - */ - METHOD_NOT_SUPPORTED(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "不支持当前请求方法"), + /** + * 不支持当前请求方法 + */ + METHOD_NOT_SUPPORTED(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "不支持当前请求方法"), - /** - * 不支持当前媒体类型 - */ - MEDIA_TYPE_NOT_SUPPORTED(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "不支持当前媒体类型"), + /** + * 不支持当前媒体类型 + */ + MEDIA_TYPE_NOT_SUPPORTED(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "不支持当前媒体类型"), - /** - * 请求被拒绝 - */ - REQ_REJECT(HttpServletResponse.SC_FORBIDDEN, "请求被拒绝"), + /** + * 请求被拒绝 + */ + REQ_REJECT(HttpServletResponse.SC_FORBIDDEN, "请求被拒绝"), - /** - * 服务器异常 - */ - INTERNAL_SERVER_ERROR(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "服务器异常"), + /** + * 服务器异常 + */ + INTERNAL_SERVER_ERROR(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "服务器异常"), - /** - * 缺少必要的请求参数 - */ - PARAM_MISS(HttpServletResponse.SC_BAD_REQUEST, "缺少必要的请求参数"), + /** + * 缺少必要的请求参数 + */ + PARAM_MISS(HttpServletResponse.SC_BAD_REQUEST, "缺少必要的请求参数"), - /** - * 请求参数类型错误 - */ - PARAM_TYPE_ERROR(HttpServletResponse.SC_BAD_REQUEST, "请求参数类型错误"), + /** + * 请求参数类型错误 + */ + PARAM_TYPE_ERROR(HttpServletResponse.SC_BAD_REQUEST, "请求参数类型错误"), - /** - * 请求参数绑定错误 - */ - PARAM_BIND_ERROR(HttpServletResponse.SC_BAD_REQUEST, "请求参数绑定错误"), + /** + * 请求参数绑定错误 + */ + PARAM_BIND_ERROR(HttpServletResponse.SC_BAD_REQUEST, "请求参数绑定错误"), - /** - * 参数校验失败 - */ - PARAM_VALID_ERROR(HttpServletResponse.SC_BAD_REQUEST, "参数校验失败"), - ; + /** + * 参数校验失败 + */ + PARAM_VALID_ERROR(HttpServletResponse.SC_BAD_REQUEST, "参数校验失败"), + ; - /** - * code编码 - */ - final int code; - /** - * 中文信息描述 - */ - final String message; + /** + * code编码 + */ + final int code; + /** + * 中文信息描述 + */ + final String message; } diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/config/JacksonConfiguration.java b/blade-core-tool/src/main/java/org/springblade/core/tool/config/JacksonConfiguration.java index 1fec89b..7a662f0 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/config/JacksonConfiguration.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/config/JacksonConfiguration.java @@ -34,6 +34,11 @@ import java.time.ZoneId; import java.util.Locale; import java.util.TimeZone; +/** + * Jackson配置类 + * + * @author smallchill + */ @Configuration @ConditionalOnClass(ObjectMapper.class) @AutoConfigureBefore(JacksonAutoConfiguration.class) diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/config/MessageConfiguration.java b/blade-core-tool/src/main/java/org/springblade/core/tool/config/MessageConfiguration.java index 9a397c6..e75fa27 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/config/MessageConfiguration.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/config/MessageConfiguration.java @@ -33,6 +33,11 @@ import javax.servlet.DispatcherType; import java.nio.charset.StandardCharsets; import java.util.List; +/** + * 消息配置类 + * + * @author smallchill + */ @Configuration @AllArgsConstructor @Order(Ordered.HIGHEST_PRECEDENCE) diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/config/ToolConfiguration.java b/blade-core-tool/src/main/java/org/springblade/core/tool/config/ToolConfiguration.java index da6103c..1e09e7e 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/config/ToolConfiguration.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/config/ToolConfiguration.java @@ -23,17 +23,21 @@ import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - +/** + * 工具配置类 + * + * @author smallchill + */ @Configuration @Order(Ordered.HIGHEST_PRECEDENCE) public class ToolConfiguration implements WebMvcConfigurer { - /** - * Spring上下文缓存 - */ - @Bean - public SpringUtil springUtils() { - return new SpringUtil(); - } + /** + * Spring上下文缓存 + */ + @Bean + public SpringUtil springUtils() { + return new SpringUtil(); + } } diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/constant/BladeConstant.java b/blade-core-tool/src/main/java/org/springblade/core/tool/constant/BladeConstant.java index 5da95b3..92df5f9 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/constant/BladeConstant.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/constant/BladeConstant.java @@ -17,23 +17,25 @@ package org.springblade.core.tool.constant; /** * 系统常量 + * + * @author smallchill */ public interface BladeConstant { - /** - * 编码 - */ - String UTF_8 = "UTF-8"; + /** + * 编码 + */ + String UTF_8 = "UTF-8"; - /** - * JSON 资源 - */ - String CONTENT_TYPE = "application/json; charset=utf-8"; + /** + * JSON 资源 + */ + String CONTENT_TYPE = "application/json; charset=utf-8"; - /** - * 角色前缀 - */ - String SECURITY_ROLE_PREFIX = "ROLE_"; + /** + * 角色前缀 + */ + String SECURITY_ROLE_PREFIX = "ROLE_"; /** * 主键字段名 @@ -49,11 +51,11 @@ public interface BladeConstant { * 是否删除字段名 */ String IS_DELETED_FIELD = "is_deleted"; - /** - * 删除状态[0:正常,1:删除] - */ - int DB_NOT_DELETED = 0; - int DB_IS_DELETED = 1; + /** + * 删除状态[0:正常,1:删除] + */ + int DB_NOT_DELETED = 0; + int DB_IS_DELETED = 1; /** * 用户锁定状态 @@ -61,26 +63,26 @@ public interface BladeConstant { int DB_ADMIN_NON_LOCKED = 0; int DB_ADMIN_LOCKED = 1; - /** - * 日志默认状态 - */ - String LOG_NORMAL_TYPE = "1"; + /** + * 日志默认状态 + */ + String LOG_NORMAL_TYPE = "1"; - /** - * 默认为空消息 - */ - String DEFAULT_NULL_MESSAGE = "暂无承载数据"; - /** - * 默认成功消息 - */ - String DEFAULT_SUCCESS_MESSAGE = "操作成功"; - /** - * 默认失败消息 - */ - String DEFAULT_FAILURE_MESSAGE = "操作失败"; - /** - * 默认未授权消息 - */ - String DEFAULT_UNAUTHORIZED_MESSAGE = "签名认证失败"; + /** + * 默认为空消息 + */ + String DEFAULT_NULL_MESSAGE = "暂无承载数据"; + /** + * 默认成功消息 + */ + String DEFAULT_SUCCESS_MESSAGE = "操作成功"; + /** + * 默认失败消息 + */ + String DEFAULT_FAILURE_MESSAGE = "操作失败"; + /** + * 默认未授权消息 + */ + String DEFAULT_UNAUTHORIZED_MESSAGE = "签名认证失败"; } diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/constant/RoleConstant.java b/blade-core-tool/src/main/java/org/springblade/core/tool/constant/RoleConstant.java index a80620f..f176cad 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/constant/RoleConstant.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/constant/RoleConstant.java @@ -17,19 +17,21 @@ package org.springblade.core.tool.constant; /** * 系统默认角色 + * + * @author smallchill */ public class RoleConstant { - public static final String ADMIN = "admin"; + public static final String ADMIN = "admin"; - public static final String HAS_ROLE_ADMIN = "hasRole('" + ADMIN + "')"; + public static final String HAS_ROLE_ADMIN = "hasRole('" + ADMIN + "')"; - public static final String USER = "user"; + public static final String USER = "user"; - public static final String HAS_ROLE_USER = "hasRole('" + USER + "')"; + public static final String HAS_ROLE_USER = "hasRole('" + USER + "')"; - public static final String TEST = "test"; + public static final String TEST = "test"; - public static final String HAS_ROLE_TEST = "hasRole('" + TEST + "')"; + public static final String HAS_ROLE_TEST = "hasRole('" + TEST + "')"; } diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/constant/SystemConstant.java b/blade-core-tool/src/main/java/org/springblade/core/tool/constant/SystemConstant.java index f01118f..1918b38 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/constant/SystemConstant.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/constant/SystemConstant.java @@ -20,6 +20,8 @@ import lombok.Data; /** * Blade系统配置类 + * + * @author smallchill */ @Data public class SystemConstant { @@ -34,10 +36,10 @@ public class SystemConstant { */ private boolean remoteMode = false; - /** - * 外网地址 - */ - private String domain = "http://localhost:8888"; + /** + * 外网地址 + */ + private String domain = "http://localhost:8888"; /** * 上传下载路径(物理路径) @@ -53,17 +55,17 @@ public class SystemConstant { * 下载路径 */ private String downloadPath = "/download"; - + /** * 图片压缩 */ private boolean compress = false; - + /** * 图片压缩比例 */ private Double compressScale = 2.00; - + /** * 图片缩放选择:true放大;false缩小 */ @@ -89,12 +91,12 @@ public class SystemConstant { return me; } - public String getUploadRealPath() { - return (remoteMode ? remotePath : realPath) + uploadPath; - } + public String getUploadRealPath() { + return (remoteMode ? remotePath : realPath) + uploadPath; + } - public String getUploadCtxPath() { - return contextPath + uploadPath; - } + public String getUploadCtxPath() { + return contextPath + uploadPath; + } } diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/jackson/JsonUtil.java b/blade-core-tool/src/main/java/org/springblade/core/tool/jackson/JsonUtil.java index 9d39c20..f4ac752 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/jackson/JsonUtil.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/jackson/JsonUtil.java @@ -39,58 +39,58 @@ import java.util.*; @Slf4j public class JsonUtil { - /** - * 将对象序列化成json字符串 - * - * @param value javaBean - * @return jsonString json字符串 - */ - public static String toJson(T value) { - try { - return getInstance().writeValueAsString(value); - } catch (Exception e) { - log.error(e.getMessage(), e); - } - return null; - } + /** + * 将对象序列化成json字符串 + * + * @param value javaBean + * @return jsonString json字符串 + */ + public static String toJson(T value) { + try { + return getInstance().writeValueAsString(value); + } catch (Exception e) { + log.error(e.getMessage(), e); + } + return null; + } - /** - * 将对象序列化成 json byte 数组 - * - * @param object javaBean - * @return jsonString json字符串 - */ - public static byte[] toJsonAsBytes(Object object) { - try { - return getInstance().writeValueAsBytes(object); - } catch (JsonProcessingException e) { - throw Exceptions.unchecked(e); - } - } - - /** - * 将json反序列化成对象 - * - * @param content content - * @param valueType class - * @param T 泛型标记 - * @return Bean - */ - public static T parse(String content, Class valueType) { - try { - return getInstance().readValue(content, valueType); - } catch (Exception e) { - log.error(e.getMessage(), e); - } - return null; - } + /** + * 将对象序列化成 json byte 数组 + * + * @param object javaBean + * @return jsonString json字符串 + */ + public static byte[] toJsonAsBytes(Object object) { + try { + return getInstance().writeValueAsBytes(object); + } catch (JsonProcessingException e) { + throw Exceptions.unchecked(e); + } + } /** * 将json反序列化成对象 * - * @param content content + * @param content content + * @param valueType class + * @param T 泛型标记 + * @return Bean + */ + public static T parse(String content, Class valueType) { + try { + return getInstance().readValue(content, valueType); + } catch (Exception e) { + log.error(e.getMessage(), e); + } + return null; + } + + /** + * 将json反序列化成对象 + * + * @param content content * @param typeReference 泛型类型 - * @param T 泛型标记 + * @param T 泛型标记 * @return Bean */ public static T parse(String content, TypeReference typeReference) { @@ -101,29 +101,29 @@ public class JsonUtil { } } - /** - * 将json byte 数组反序列化成对象 - * - * @param bytes json bytes - * @param valueType class - * @param T 泛型标记 - * @return Bean - */ - public static T parse(byte[] bytes, Class valueType) { - try { - return getInstance().readValue(bytes, valueType); - } catch (IOException e) { - throw Exceptions.unchecked(e); - } - } + /** + * 将json byte 数组反序列化成对象 + * + * @param bytes json bytes + * @param valueType class + * @param T 泛型标记 + * @return Bean + */ + public static T parse(byte[] bytes, Class valueType) { + try { + return getInstance().readValue(bytes, valueType); + } catch (IOException e) { + throw Exceptions.unchecked(e); + } + } /** * 将json反序列化成对象 * - * @param bytes bytes + * @param bytes bytes * @param typeReference 泛型类型 - * @param T 泛型标记 + * @param T 泛型标记 * @return Bean */ public static T parse(byte[] bytes, TypeReference typeReference) { @@ -137,9 +137,9 @@ public class JsonUtil { /** * 将json反序列化成对象 * - * @param in InputStream - * @param valueType class - * @param T 泛型标记 + * @param in InputStream + * @param valueType class + * @param T 泛型标记 * @return Bean */ public static T parse(InputStream in, Class valueType) { @@ -153,9 +153,9 @@ public class JsonUtil { /** * 将json反序列化成对象 * - * @param in InputStream + * @param in InputStream * @param typeReference 泛型类型 - * @param T 泛型标记 + * @param T 泛型标记 * @return Bean */ public static T parse(InputStream in, TypeReference typeReference) { @@ -166,74 +166,75 @@ public class JsonUtil { } } - /** - * 将json反序列化成List对象 - * @param content content - * @param valueTypeRef class - * @param T 泛型标记 - * @return - */ - public static List parseArray(String content, Class valueTypeRef) { - try { + /** + * 将json反序列化成List对象 + * + * @param content content + * @param valueTypeRef class + * @param T 泛型标记 + * @return + */ + public static List parseArray(String content, Class valueTypeRef) { + try { - if (!StringUtil.startsWithIgnoreCase(content, "[")) { - content = "[" + content + "]"; - } + if (!StringUtil.startsWithIgnoreCase(content, "[")) { + content = "[" + content + "]"; + } - List> list = getInstance().readValue(content, new TypeReference>() { - }); - List result = new ArrayList<>(); - for (Map map : list) { - result.add(toPojo(map, valueTypeRef)); - } - return result; - } catch (IOException e) { - log.error(e.getMessage(), e); - } - return null; - } + List> list = getInstance().readValue(content, new TypeReference>() { + }); + List result = new ArrayList<>(); + for (Map map : list) { + result.add(toPojo(map, valueTypeRef)); + } + return result; + } catch (IOException e) { + log.error(e.getMessage(), e); + } + return null; + } - public static Map toMap(String content) { - try { - return getInstance().readValue(content, Map.class); - } catch (IOException e) { - log.error(e.getMessage(), e); - } - return null; - } + public static Map toMap(String content) { + try { + return getInstance().readValue(content, Map.class); + } catch (IOException e) { + log.error(e.getMessage(), e); + } + return null; + } - public static Map toMap(String content, Class valueTypeRef) { - try { - Map> map = getInstance().readValue(content, new TypeReference>() { - }); - Map result = new HashMap<>(); - for (Map.Entry> entry : map.entrySet()) { - result.put(entry.getKey(), toPojo(entry.getValue(), valueTypeRef)); - } - return result; - } catch (IOException e) { - log.error(e.getMessage(), e); - } - return null; - } + public static Map toMap(String content, Class valueTypeRef) { + try { + Map> map = getInstance().readValue(content, new TypeReference>() { + }); + Map result = new HashMap<>(); + for (Map.Entry> entry : map.entrySet()) { + result.put(entry.getKey(), toPojo(entry.getValue(), valueTypeRef)); + } + return result; + } catch (IOException e) { + log.error(e.getMessage(), e); + } + return null; + } - public static T toPojo(Map fromValue, Class toValueType) { - return getInstance().convertValue(fromValue, toValueType); - } + public static T toPojo(Map fromValue, Class toValueType) { + return getInstance().convertValue(fromValue, toValueType); + } - /** - * 将json字符串转成 JsonNode - * - * @param jsonString jsonString - * @return jsonString json字符串 - */ - public static JsonNode readTree(String jsonString) { - try { - return getInstance().readTree(jsonString); - } catch (IOException e) { - throw Exceptions.unchecked(e); - } - } + /** + * 将json字符串转成 JsonNode + * + * @param jsonString jsonString + * @return jsonString json字符串 + */ + public static JsonNode readTree(String jsonString) { + try { + return getInstance().readTree(jsonString); + } catch (IOException e) { + throw Exceptions.unchecked(e); + } + } /** * 将json字符串转成 JsonNode @@ -277,47 +278,47 @@ public class JsonUtil { } } - public static ObjectMapper getInstance() { - return JacksonHolder.INSTANCE; - } + public static ObjectMapper getInstance() { + return JacksonHolder.INSTANCE; + } - private static class JacksonHolder { - private static ObjectMapper INSTANCE = new JacksonObjectMapper(); - } + private static class JacksonHolder { + private static ObjectMapper INSTANCE = new JacksonObjectMapper(); + } - public static class JacksonObjectMapper extends ObjectMapper { - private static final long serialVersionUID = 4288193147502386170L; + public static class JacksonObjectMapper extends ObjectMapper { + private static final long serialVersionUID = 4288193147502386170L; - private static final Locale CHINA = Locale.CHINA; + private static final Locale CHINA = Locale.CHINA; - public JacksonObjectMapper() { - super(); - //设置地点为中国 - super.setLocale(CHINA); - //去掉默认的时间戳格式 - super.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); + public JacksonObjectMapper() { + super(); + //设置地点为中国 + super.setLocale(CHINA); + //去掉默认的时间戳格式 + super.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); //设置为中国上海时区 super.setTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault())); //序列化时,日期的统一格式 super.setDateFormat(new SimpleDateFormat(DatePattern.NORM_DATETIME_PATTERN, Locale.CHINA)); - //序列化处理 - super.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); - super.configure(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, true); - super.findAndRegisterModules(); - //失败处理 - super.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); - super.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - //单引号处理 - super.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); - //反序列化时,属性不存在的兼容处理s - super.getDeserializationConfig().withoutFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); - //序列化处理 - super.setSerializerFactory(this.getSerializerFactory().withSerializerModifier(new BladeBeanSerializerModifier())); - super.getSerializerProvider().setNullValueSerializer(BladeBeanSerializerModifier.NullJsonSerializers.STRING_JSON_SERIALIZER); - //日期格式化 + //序列化处理 + super.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); + super.configure(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, true); + super.findAndRegisterModules(); + //失败处理 + super.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + super.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + //单引号处理 + super.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); + //反序列化时,属性不存在的兼容处理s + super.getDeserializationConfig().withoutFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + //序列化处理 + super.setSerializerFactory(this.getSerializerFactory().withSerializerModifier(new BladeBeanSerializerModifier())); + super.getSerializerProvider().setNullValueSerializer(BladeBeanSerializerModifier.NullJsonSerializers.STRING_JSON_SERIALIZER); + //日期格式化 super.registerModule(new BladeJavaTimeModule()); super.findAndRegisterModules(); - } + } @Override public ObjectMapper copy() { diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/node/BaseNode.java b/blade-core-tool/src/main/java/org/springblade/core/tool/node/BaseNode.java index 9566373..393b246 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/node/BaseNode.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/node/BaseNode.java @@ -24,7 +24,7 @@ import java.util.List; /** * 节点基类 * - * @author zhuangqian + * @author smallchill */ @Data public class BaseNode implements INode { @@ -32,7 +32,7 @@ public class BaseNode implements INode { /** * 主键ID */ - protected Integer id; + protected Integer id; /** * 父节点ID @@ -43,6 +43,6 @@ public class BaseNode implements INode { * 子孙节点 */ @JsonInclude(JsonInclude.Include.NON_EMPTY) - protected List children = new ArrayList<>(); + protected List children = new ArrayList<>(); } diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/node/ForestNode.java b/blade-core-tool/src/main/java/org/springblade/core/tool/node/ForestNode.java index e3d4d78..df764ff 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/node/ForestNode.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/node/ForestNode.java @@ -21,17 +21,22 @@ import lombok.EqualsAndHashCode; /** * 森林节点类 + * + * @author smallchill */ @Data @EqualsAndHashCode(callSuper = false) public class ForestNode extends BaseNode { - private Object content;//节点内容 + /** + * 节点内容 + */ + private Object content; - public ForestNode(Integer id, Integer parentId, Object content) { - this.id = id; - this.parentId = parentId; - this.content = content; - } + public ForestNode(Integer id, Integer parentId, Object content) { + this.id = id; + this.parentId = parentId; + this.content = content; + } } diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/node/ForestNodeManager.java b/blade-core-tool/src/main/java/org/springblade/core/tool/node/ForestNodeManager.java index ece5cb5..ce69401 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/node/ForestNodeManager.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/node/ForestNodeManager.java @@ -21,7 +21,7 @@ import java.util.List; /** * 森林管理类 * - * @author zhuangqian + * @author smallchill */ public class ForestNodeManager { diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/node/ForestNodeMerger.java b/blade-core-tool/src/main/java/org/springblade/core/tool/node/ForestNodeMerger.java index 61b71c8..dbe096a 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/node/ForestNodeMerger.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/node/ForestNodeMerger.java @@ -20,7 +20,7 @@ import java.util.List; /** * 森林节点归并类 * - * @author zhuangqian + * @author smallchill */ public class ForestNodeMerger { diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/node/INode.java b/blade-core-tool/src/main/java/org/springblade/core/tool/node/INode.java index f80e025..dd62b3c 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/node/INode.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/node/INode.java @@ -20,7 +20,7 @@ import java.util.List; /** * Created by Blade. * - * @author zhuangqian + * @author smallchill */ public interface INode { diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/node/NodeTest.java b/blade-core-tool/src/main/java/org/springblade/core/tool/node/NodeTest.java index ea2f76f..0ec1d7f 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/node/NodeTest.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/node/NodeTest.java @@ -8,7 +8,7 @@ import java.util.List; /** * Created by Blade. * - * @author zhuangqian + * @author smallchill */ public class NodeTest { diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/node/TreeNode.java b/blade-core-tool/src/main/java/org/springblade/core/tool/node/TreeNode.java index e540c0b..04ad21e 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/node/TreeNode.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/node/TreeNode.java @@ -20,6 +20,8 @@ import lombok.EqualsAndHashCode; /** * 树型节点类 + * + * @author smallchill */ @Data @EqualsAndHashCode(callSuper = false) diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/support/BeanProperty.java b/blade-core-tool/src/main/java/org/springblade/core/tool/support/BeanProperty.java index d8ecaa6..cc1c270 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/support/BeanProperty.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/support/BeanProperty.java @@ -5,6 +5,8 @@ import lombok.Getter; /** * Bean属性 + * + * @author smallchill */ @Getter @AllArgsConstructor diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/support/CMap.java b/blade-core-tool/src/main/java/org/springblade/core/tool/support/CMap.java index 911f567..58869b9 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/support/CMap.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/support/CMap.java @@ -24,172 +24,177 @@ import java.util.HashMap; /** * 链式map + * + * @author smallchill */ public class CMap extends CaseInsensitiveHashMap { - private CMap(){ - + private CMap() { + } - /** - * 创建CMap - * @return CMap - */ - public static CMap init() { - return new CMap(); - } + /** + * 创建CMap + * + * @return CMap + */ + public static CMap init() { + return new CMap(); + } - public static HashMap newHashMap() { - return new HashMap(); - } + public static HashMap newHashMap() { + return new HashMap(); + } - /** - * 设置列 - * @param attr 属性 - * @param value 值 - * @return 本身 - */ - public CMap set(String attr, Object value) { - this.put(attr, value); - return this; - } + /** + * 设置列 + * + * @param attr 属性 + * @param value 值 + * @return 本身 + */ + public CMap set(String attr, Object value) { + this.put(attr, value); + return this; + } - /** - * 设置列,当键或值为null时忽略 - * @param attr 属性 - * @param value 值 - * @return 本身 - */ - public CMap setIgnoreNull(String attr, Object value) { - if(null != attr && null != value) { - set(attr, value); - } - return this; - } + /** + * 设置列,当键或值为null时忽略 + * + * @param attr 属性 + * @param value 值 + * @return 本身 + */ + public CMap setIgnoreNull(String attr, Object value) { + if (null != attr && null != value) { + set(attr, value); + } + return this; + } - public Object getObj(String key) { - return super.get(key); - } + public Object getObj(String key) { + return super.get(key); + } - /** - * 获得特定类型值 - * - * @param 值类型 - * @param attr 字段名 - * @param defaultValue 默认值 - * @return 字段值 - */ - public T get(String attr, T defaultValue) { - final Object result = get(attr); - return (T)(result != null ? result : defaultValue); - } - - /** + /** * 获得特定类型值 * - * @param attr 字段名 - * @return 字段值 - */ - public String getStr(String attr) { - return Func.toStr(get(attr), null); - } + * @param 值类型 + * @param attr 字段名 + * @param defaultValue 默认值 + * @return 字段值 + */ + public T get(String attr, T defaultValue) { + final Object result = get(attr); + return (T) (result != null ? result : defaultValue); + } - /** + /** * 获得特定类型值 * * @param attr 字段名 - * @return 字段值 - */ - public Integer getInt(String attr) { - return Func.toInt(get(attr), -1); - } + * @return 字段值 + */ + public String getStr(String attr) { + return Func.toStr(get(attr), null); + } - /** + /** * 获得特定类型值 * * @param attr 字段名 - * @return 字段值 - */ - public Long getLong(String attr) { - return Func.toLong(get(attr), -1l); - } + * @return 字段值 + */ + public Integer getInt(String attr) { + return Func.toInt(get(attr), -1); + } - /** + /** * 获得特定类型值 * * @param attr 字段名 - * @return 字段值 - */ - public Float getFloat(String attr) { - return Func.toFloat(get(attr), null); - } + * @return 字段值 + */ + public Long getLong(String attr) { + return Func.toLong(get(attr), -1l); + } - public Double getDouble(String attr) { - return Func.toDouble(get(attr), null); - } - - - /** + /** * 获得特定类型值 * * @param attr 字段名 - * @return 字段值 - */ - public Boolean getBool(String attr) { - return Func.toBoolean(get(attr), null); - } + * @return 字段值 + */ + public Float getFloat(String attr) { + return Func.toFloat(get(attr), null); + } - /** + public Double getDouble(String attr) { + return Func.toDouble(get(attr), null); + } + + + /** * 获得特定类型值 * * @param attr 字段名 - * @return 字段值 - */ - public byte[] getBytes(String attr) { - return get(attr, null); - } + * @return 字段值 + */ + public Boolean getBool(String attr) { + return Func.toBoolean(get(attr), null); + } - /** + /** * 获得特定类型值 * * @param attr 字段名 - * @return 字段值 - */ - public Date getDate(String attr) { - return get(attr, null); - } + * @return 字段值 + */ + public byte[] getBytes(String attr) { + return get(attr, null); + } - /** + /** * 获得特定类型值 * * @param attr 字段名 - * @return 字段值 - */ - public Time getTime(String attr) { - return get(attr, null); - } + * @return 字段值 + */ + public Date getDate(String attr) { + return get(attr, null); + } - /** + /** * 获得特定类型值 * * @param attr 字段名 - * @return 字段值 - */ - public Timestamp getTimestamp(String attr) { - return get(attr, null); - } + * @return 字段值 + */ + public Time getTime(String attr) { + return get(attr, null); + } - /** + /** * 获得特定类型值 * * @param attr 字段名 - * @return 字段值 - */ - public Number getNumber(String attr) { - return get(attr, null); - } - + * @return 字段值 + */ + public Timestamp getTimestamp(String attr) { + return get(attr, null); + } + + /** + * 获得特定类型值 + * + * @param attr 字段名 + * @return 字段值 + */ + public Number getNumber(String attr) { + return get(attr, null); + } + @Override public CMap clone() { return (CMap) super.clone(); diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/support/CaseInsensitiveHashMap.java b/blade-core-tool/src/main/java/org/springblade/core/tool/support/CaseInsensitiveHashMap.java index e62b81d..020065d 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/support/CaseInsensitiveHashMap.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/support/CaseInsensitiveHashMap.java @@ -17,52 +17,58 @@ package org.springblade.core.tool.support; import java.util.*; +/** + * 大小写忽略Map拓展 + * + * @param + * @param + * @author smallchill + */ +public class CaseInsensitiveHashMap extends LinkedHashMap { -public class CaseInsensitiveHashMap extends LinkedHashMap { + private static final long serialVersionUID = 9178606903603606031L; - private static final long serialVersionUID = 9178606903603606031L; + private final Map lowerCaseMap = new HashMap(); - private final Map lowerCaseMap = new HashMap(); + @Override + public boolean containsKey(Object key) { + Object realKey = lowerCaseMap.get(key.toString().toLowerCase(Locale.ENGLISH)); + return super.containsKey(realKey); + } - @Override - public boolean containsKey(Object key) { - Object realKey = lowerCaseMap.get(key.toString().toLowerCase(Locale.ENGLISH)); - return super.containsKey(realKey); - } + @Override + public Object get(Object key) { + Object realKey = lowerCaseMap.get(key.toString().toLowerCase(Locale.ENGLISH)); + return super.get(realKey); + } - @Override - public Object get(Object key) { - Object realKey = lowerCaseMap.get(key.toString().toLowerCase(Locale.ENGLISH)); - return super.get(realKey); - } + @Override + public Set keySet() { + return lowerCaseMap.keySet(); + } - @Override - public Set keySet() { - return lowerCaseMap.keySet(); - } + @Override + public Object put(String key, Object value) { + Object oldKey = lowerCaseMap.put(key.toLowerCase(Locale.ENGLISH), key); + Object oldValue = super.remove(oldKey); + super.put(key, value); + return oldValue; + } - @Override - public Object put(String key, Object value) { - Object oldKey = lowerCaseMap.put(key.toLowerCase(Locale.ENGLISH), key); - Object oldValue = super.remove(oldKey); - super.put(key, value); - return oldValue; - } + @Override + public void putAll(Map m) { + for (Map.Entry entry : m.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + this.put(key, value); + } + } - @Override - public void putAll(Map m) { - for (Map.Entry entry : m.entrySet()) { - String key = entry.getKey(); - Object value = entry.getValue(); - this.put(key, value); - } - } - - @Override - public Object remove(Object key) { - Object realKey = lowerCaseMap.remove(key.toString().toLowerCase(Locale.ENGLISH)); - return super.remove(realKey); - } + @Override + public Object remove(Object key) { + Object realKey = lowerCaseMap.remove(key.toString().toLowerCase(Locale.ENGLISH)); + return super.remove(realKey); + } } diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/support/IMultiOutputStream.java b/blade-core-tool/src/main/java/org/springblade/core/tool/support/IMultiOutputStream.java index 1afb28a..b67d509 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/support/IMultiOutputStream.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/support/IMultiOutputStream.java @@ -19,6 +19,8 @@ import java.io.OutputStream; /** * A factory for creating MultiOutputStream objects. + * + * @author smallchill */ public interface IMultiOutputStream { @@ -28,6 +30,6 @@ public interface IMultiOutputStream { * @param params the params * @return the output stream */ - OutputStream buildOutputStream(Integer... params) ; - + OutputStream buildOutputStream(Integer... params); + } diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/support/ImagePosition.java b/blade-core-tool/src/main/java/org/springblade/core/tool/support/ImagePosition.java index de6dca9..5fbfc41 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/support/ImagePosition.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/support/ImagePosition.java @@ -15,74 +15,99 @@ */ package org.springblade.core.tool.support; +/** + * 图片操作类 + * + * @author smallchill + */ public class ImagePosition { - /** 图片顶部. */ + /** + * 图片顶部. + */ public static final int TOP = 32; - - /** 图片中部. */ + + /** + * 图片中部. + */ public static final int MIDDLE = 16; - - /** 图片底部. */ + + /** + * 图片底部. + */ public static final int BOTTOM = 8; - - /** 图片左侧. */ + + /** + * 图片左侧. + */ public static final int LEFT = 4; - - /** 图片居中. */ + + /** + * 图片居中. + */ public static final int CENTER = 2; - - /** 图片右侧. */ + + /** + * 图片右侧. + */ public static final int RIGHT = 1; - - /** 横向边距,靠左或靠右时和边界的距离. */ + + /** + * 横向边距,靠左或靠右时和边界的距离. + */ private static final int PADDING_HORI = 6; - - /** 纵向边距,靠上或靠底时和边界的距离. */ + + /** + * 纵向边距,靠上或靠底时和边界的距离. + */ private static final int PADDING_VERT = 6; - - /** 图片中盒[左上角]的x坐标. */ - private int boxPosX ; - - /** 图片中盒[左上角]的y坐标. */ - private int boxPosY ; - + + /** + * 图片中盒[左上角]的x坐标. + */ + private int boxPosX; + + /** + * 图片中盒[左上角]的y坐标. + */ + private int boxPosY; + /** * Instantiates a new image position. * - * @param width the width - * @param height the height - * @param boxWidth the box width + * @param width the width + * @param height the height + * @param boxWidth the box width * @param boxHeight the box height - * @param style the style + * @param style the style */ - public ImagePosition(int width , int height , int boxWidth , int boxHeight, int style ) { - switch(style & 7) { + public ImagePosition(int width, int height, int boxWidth, int boxHeight, int style) { + switch (style & 7) { case LEFT: - boxPosX = PADDING_HORI; + boxPosX = PADDING_HORI; break; case RIGHT: - boxPosX = width - boxWidth - PADDING_HORI; + boxPosX = width - boxWidth - PADDING_HORI; break; case CENTER: default: - boxPosX = (width - boxWidth)/2; + boxPosX = (width - boxWidth) / 2; } - switch(style >> 3 << 3) { + switch (style >> 3 << 3) { case TOP: boxPosY = PADDING_VERT; break; case MIDDLE: - boxPosY = (height - boxHeight)/2; + boxPosY = (height - boxHeight) / 2; break; case BOTTOM: default: - boxPosY = height - boxHeight - PADDING_VERT; + boxPosY = height - boxHeight - PADDING_VERT; } } - - + + /** * Gets the x. * @@ -91,7 +116,7 @@ public class ImagePosition { public int getX() { return getX(0); } - + /** * Gets the x. * @@ -101,7 +126,7 @@ public class ImagePosition { public int getX(int x) { return this.boxPosX + x; } - + /** * Gets the y. * @@ -110,7 +135,7 @@ public class ImagePosition { public int getY() { return getY(0); } - + /** * Gets the y. * @@ -120,5 +145,5 @@ public class ImagePosition { public int getY(int y) { return this.boxPosY + y; } - + } diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/support/StrFormatter.java b/blade-core-tool/src/main/java/org/springblade/core/tool/support/StrFormatter.java index 8c2b729..c3a3a7b 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/support/StrFormatter.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/support/StrFormatter.java @@ -3,65 +3,92 @@ package org.springblade.core.tool.support; import org.springblade.core.tool.utils.Func; import org.springblade.core.tool.utils.StringPool; +/** + * 字符串格式化 + * + * @author smallchill + */ public class StrFormatter { - /** - * 格式化字符串
- * 此方法只是简单将占位符 {} 按照顺序替换为参数
- * 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可
- * 例:
- * 通常使用:format("this is {} for {}", "a", "b") =》 this is a for b
- * 转义{}: format("this is \\{} for {}", "a", "b") =》 this is \{} for a
- * 转义\: format("this is \\\\{} for {}", "a", "b") =》 this is \a for b
- * @param strPattern 字符串模板 - * @param argArray 参数列表 - * @return 结果 - */ - public static String format(final String strPattern, final Object... argArray) { - if (Func.isBlank(strPattern) || Func.isEmpty(argArray)) { - return strPattern; - } - final int strPatternLength = strPattern.length(); + /** + * 格式化字符串
+ * 此方法只是简单将占位符 {} 按照顺序替换为参数
+ * 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可
+ * 例:
+ * 通常使用:format("this is {} for {}", "a", "b") =》 this is a for b
+ * 转义{}: format("this is \\{} for {}", "a", "b") =》 this is \{} for a
+ * 转义\: format("this is \\\\{} for {}", "a", "b") =》 this is \a for b
+ * + * @param strPattern 字符串模板 + * @param argArray 参数列表 + * @return 结果 + */ + public static String format(final String strPattern, final Object... argArray) { + if (Func.isBlank(strPattern) || Func.isEmpty(argArray)) { + return strPattern; + } + final int strPatternLength = strPattern.length(); - //初始化定义好的长度以获得更好的性能 - StringBuilder sbuf = new StringBuilder(strPatternLength + 50); + /** + * 初始化定义好的长度以获得更好的性能 + */ + StringBuilder sbuf = new StringBuilder(strPatternLength + 50); - int handledPosition = 0;//记录已经处理到的位置 - int delimIndex;//占位符所在位置 - for (int argIndex = 0; argIndex < argArray.length; argIndex++) { - delimIndex = strPattern.indexOf(StringPool.EMPTY_JSON, handledPosition); - if (delimIndex == -1) {//剩余部分无占位符 - if (handledPosition == 0) { //不带占位符的模板直接返回 - return strPattern; - } else { //字符串模板剩余部分不再包含占位符,加入剩余部分后返回结果 - sbuf.append(strPattern, handledPosition, strPatternLength); - return sbuf.toString(); - } - } else { - if (delimIndex > 0 && strPattern.charAt(delimIndex - 1) == StringPool.BACK_SLASH) {//转义符 - if (delimIndex > 1 && strPattern.charAt(delimIndex - 2) == StringPool.BACK_SLASH) {//双转义符 - //转义符之前还有一个转义符,占位符依旧有效 - sbuf.append(strPattern, handledPosition, delimIndex - 1); - sbuf.append(Func.toStr(argArray[argIndex])); - handledPosition = delimIndex + 2; - } else { - //占位符被转义 - argIndex--; - sbuf.append(strPattern, handledPosition, delimIndex - 1); - sbuf.append(StringPool.LEFT_BRACE); - handledPosition = delimIndex + 1; - } - } else {//正常占位符 - sbuf.append(strPattern, handledPosition, delimIndex); - sbuf.append(Func.toStr(argArray[argIndex])); - handledPosition = delimIndex + 2; - } - } - } - // append the characters following the last {} pair. - //加入最后一个占位符后所有的字符 - sbuf.append(strPattern, handledPosition, strPattern.length()); + /** + * 记录已经处理到的位置 + */ + int handledPosition = 0; - return sbuf.toString(); - } + /** + * 占位符所在位置 + */ + int delimIndex; + for (int argIndex = 0; argIndex < argArray.length; argIndex++) { + delimIndex = strPattern.indexOf(StringPool.EMPTY_JSON, handledPosition); + /** + * 剩余部分无占位符 + */ + if (delimIndex == -1) { + /** + * 不带占位符的模板直接返回 + */ + if (handledPosition == 0) { + return strPattern; + } else { + sbuf.append(strPattern, handledPosition, strPatternLength); + return sbuf.toString(); + } + } else { + /** + * 转义符 + */ + if (delimIndex > 0 && strPattern.charAt(delimIndex - 1) == StringPool.BACK_SLASH) { + /** + * 双转义符 + */ + if (delimIndex > 1 && strPattern.charAt(delimIndex - 2) == StringPool.BACK_SLASH) { + //转义符之前还有一个转义符,占位符依旧有效 + sbuf.append(strPattern, handledPosition, delimIndex - 1); + sbuf.append(Func.toStr(argArray[argIndex])); + handledPosition = delimIndex + 2; + } else { + //占位符被转义 + argIndex--; + sbuf.append(strPattern, handledPosition, delimIndex - 1); + sbuf.append(StringPool.LEFT_BRACE); + handledPosition = delimIndex + 1; + } + } else {//正常占位符 + sbuf.append(strPattern, handledPosition, delimIndex); + sbuf.append(Func.toStr(argArray[argIndex])); + handledPosition = delimIndex + 2; + } + } + } + // append the characters following the last {} pair. + //加入最后一个占位符后所有的字符 + sbuf.append(strPattern, handledPosition, strPattern.length()); + + return sbuf.toString(); + } } diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/support/StrSpliter.java b/blade-core-tool/src/main/java/org/springblade/core/tool/support/StrSpliter.java index 9c9880a..3057230 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/support/StrSpliter.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/support/StrSpliter.java @@ -11,489 +11,494 @@ import java.util.regex.Pattern; /** * 字符串切分器 - * @author Looly * + * @author Looly */ public class StrSpliter { - //---------------------------------------------------------------------------------------------- Split by char - /** - * 切分字符串路径,仅支持Unix分界符:/ - * - * @param str 被切分的字符串 - * @return 切分后的集合 - * @since 3.0.8 - */ - public static List splitPath(String str){ - return splitPath(str, 0); - } + //---------------------------------------------------------------------------------------------- Split by char - /** - * 切分字符串路径,仅支持Unix分界符:/ - * - * @param str 被切分的字符串 - * @return 切分后的集合 - * @since 3.0.8 - */ - public static String[] splitPathToArray(String str){ - return toArray(splitPath(str)); - } + /** + * 切分字符串路径,仅支持Unix分界符:/ + * + * @param str 被切分的字符串 + * @return 切分后的集合 + * @since 3.0.8 + */ + public static List splitPath(String str) { + return splitPath(str, 0); + } - /** - * 切分字符串路径,仅支持Unix分界符:/ - * - * @param str 被切分的字符串 - * @param limit 限制分片数 - * @return 切分后的集合 - * @since 3.0.8 - */ - public static List splitPath(String str, int limit){ - return split(str, StringPool.SLASH, limit, true, true); - } + /** + * 切分字符串路径,仅支持Unix分界符:/ + * + * @param str 被切分的字符串 + * @return 切分后的集合 + * @since 3.0.8 + */ + public static String[] splitPathToArray(String str) { + return toArray(splitPath(str)); + } - /** - * 切分字符串路径,仅支持Unix分界符:/ - * - * @param str 被切分的字符串 - * @param limit 限制分片数 - * @return 切分后的集合 - * @since 3.0.8 - */ - public static String[] splitPathToArray(String str, int limit){ - return toArray(splitPath(str, limit)); - } + /** + * 切分字符串路径,仅支持Unix分界符:/ + * + * @param str 被切分的字符串 + * @param limit 限制分片数 + * @return 切分后的集合 + * @since 3.0.8 + */ + public static List splitPath(String str, int limit) { + return split(str, StringPool.SLASH, limit, true, true); + } - /** - * 切分字符串 - * - * @param str 被切分的字符串 - * @param separator 分隔符字符 - * @param ignoreEmpty 是否忽略空串 - * @return 切分后的集合 - * @since 3.2.1 - */ - public static List splitTrim(String str, char separator, boolean ignoreEmpty){ - return split(str, separator, 0, true, ignoreEmpty); - } + /** + * 切分字符串路径,仅支持Unix分界符:/ + * + * @param str 被切分的字符串 + * @param limit 限制分片数 + * @return 切分后的集合 + * @since 3.0.8 + */ + public static String[] splitPathToArray(String str, int limit) { + return toArray(splitPath(str, limit)); + } - /** - * 切分字符串 - * - * @param str 被切分的字符串 - * @param separator 分隔符字符 - * @param isTrim 是否去除切分字符串后每个元素两边的空格 - * @param ignoreEmpty 是否忽略空串 - * @return 切分后的集合 - * @since 3.0.8 - */ - public static List split(String str, char separator, boolean isTrim, boolean ignoreEmpty){ - return split(str, separator, 0, isTrim, ignoreEmpty); - } + /** + * 切分字符串 + * + * @param str 被切分的字符串 + * @param separator 分隔符字符 + * @param ignoreEmpty 是否忽略空串 + * @return 切分后的集合 + * @since 3.2.1 + */ + public static List splitTrim(String str, char separator, boolean ignoreEmpty) { + return split(str, separator, 0, true, ignoreEmpty); + } - /** - * 切分字符串,大小写敏感,去除每个元素两边空白符 - * - * @param str 被切分的字符串 - * @param separator 分隔符字符 - * @param limit 限制分片数,-1不限制 - * @param ignoreEmpty 是否忽略空串 - * @return 切分后的集合 - * @since 3.0.8 - */ - public static List splitTrim(String str, char separator, int limit, boolean ignoreEmpty){ - return split(str, separator, limit, true, ignoreEmpty, false); - } + /** + * 切分字符串 + * + * @param str 被切分的字符串 + * @param separator 分隔符字符 + * @param isTrim 是否去除切分字符串后每个元素两边的空格 + * @param ignoreEmpty 是否忽略空串 + * @return 切分后的集合 + * @since 3.0.8 + */ + public static List split(String str, char separator, boolean isTrim, boolean ignoreEmpty) { + return split(str, separator, 0, isTrim, ignoreEmpty); + } - /** - * 切分字符串,大小写敏感 - * - * @param str 被切分的字符串 - * @param separator 分隔符字符 - * @param limit 限制分片数,-1不限制 - * @param isTrim 是否去除切分字符串后每个元素两边的空格 - * @param ignoreEmpty 是否忽略空串 - * @return 切分后的集合 - * @since 3.0.8 - */ - public static List split(String str, char separator, int limit, boolean isTrim, boolean ignoreEmpty){ - return split(str, separator, limit, isTrim, ignoreEmpty, false); - } + /** + * 切分字符串,大小写敏感,去除每个元素两边空白符 + * + * @param str 被切分的字符串 + * @param separator 分隔符字符 + * @param limit 限制分片数,-1不限制 + * @param ignoreEmpty 是否忽略空串 + * @return 切分后的集合 + * @since 3.0.8 + */ + public static List splitTrim(String str, char separator, int limit, boolean ignoreEmpty) { + return split(str, separator, limit, true, ignoreEmpty, false); + } - /** - * 切分字符串,忽略大小写 - * - * @param str 被切分的字符串 - * @param separator 分隔符字符 - * @param limit 限制分片数,-1不限制 - * @param isTrim 是否去除切分字符串后每个元素两边的空格 - * @param ignoreEmpty 是否忽略空串 - * @return 切分后的集合 - * @since 3.2.1 - */ - public static List splitIgnoreCase(String str, char separator, int limit, boolean isTrim, boolean ignoreEmpty){ - return split(str, separator, limit, isTrim, ignoreEmpty, true); - } + /** + * 切分字符串,大小写敏感 + * + * @param str 被切分的字符串 + * @param separator 分隔符字符 + * @param limit 限制分片数,-1不限制 + * @param isTrim 是否去除切分字符串后每个元素两边的空格 + * @param ignoreEmpty 是否忽略空串 + * @return 切分后的集合 + * @since 3.0.8 + */ + public static List split(String str, char separator, int limit, boolean isTrim, boolean ignoreEmpty) { + return split(str, separator, limit, isTrim, ignoreEmpty, false); + } - /** - * 切分字符串 - * - * @param str 被切分的字符串 - * @param separator 分隔符字符 - * @param limit 限制分片数,-1不限制 - * @param isTrim 是否去除切分字符串后每个元素两边的空格 - * @param ignoreEmpty 是否忽略空串 - * @param ignoreCase 是否忽略大小写 - * @return 切分后的集合 - * @since 3.2.1 - */ - public static List split(String str, char separator, int limit, boolean isTrim, boolean ignoreEmpty, boolean ignoreCase){ - if(StringUtil.isEmpty(str)){ - return new ArrayList(0); - } - if(limit == 1){ - return addToList(new ArrayList(1), str, isTrim, ignoreEmpty); - } + /** + * 切分字符串,忽略大小写 + * + * @param str 被切分的字符串 + * @param separator 分隔符字符 + * @param limit 限制分片数,-1不限制 + * @param isTrim 是否去除切分字符串后每个元素两边的空格 + * @param ignoreEmpty 是否忽略空串 + * @return 切分后的集合 + * @since 3.2.1 + */ + public static List splitIgnoreCase(String str, char separator, int limit, boolean isTrim, boolean ignoreEmpty) { + return split(str, separator, limit, isTrim, ignoreEmpty, true); + } - final ArrayList list = new ArrayList<>(limit > 0 ? limit : 16); - int len = str.length(); - int start = 0;//切分后每个部分的起始 - for(int i = 0; i < len; i++){ - if(Func.equals(separator, str.charAt(i))){ - addToList(list, str.substring(start, i), isTrim, ignoreEmpty); - start = i+1;//i+1同时将start与i保持一致 + /** + * 切分字符串 + * + * @param str 被切分的字符串 + * @param separator 分隔符字符 + * @param limit 限制分片数,-1不限制 + * @param isTrim 是否去除切分字符串后每个元素两边的空格 + * @param ignoreEmpty 是否忽略空串 + * @param ignoreCase 是否忽略大小写 + * @return 切分后的集合 + * @since 3.2.1 + */ + public static List split(String str, char separator, int limit, boolean isTrim, boolean ignoreEmpty, boolean ignoreCase) { + if (StringUtil.isEmpty(str)) { + return new ArrayList(0); + } + if (limit == 1) { + return addToList(new ArrayList(1), str, isTrim, ignoreEmpty); + } - //检查是否超出范围(最大允许limit-1个,剩下一个留给末尾字符串) - if(limit > 0 && list.size() > limit-2){ - break; - } - } - } - return addToList(list, str.substring(start, len), isTrim, ignoreEmpty);//收尾 - } + final ArrayList list = new ArrayList<>(limit > 0 ? limit : 16); + int len = str.length(); + int start = 0;//切分后每个部分的起始 + for (int i = 0; i < len; i++) { + if (Func.equals(separator, str.charAt(i))) { + addToList(list, str.substring(start, i), isTrim, ignoreEmpty); + start = i + 1;//i+1同时将start与i保持一致 - /** - * 切分字符串为字符串数组 - * - * @param str 被切分的字符串 - * @param separator 分隔符字符 - * @param limit 限制分片数 - * @param isTrim 是否去除切分字符串后每个元素两边的空格 - * @param ignoreEmpty 是否忽略空串 - * @return 切分后的集合 - * @since 3.0.8 - */ - public static String[] splitToArray(String str, char separator, int limit, boolean isTrim, boolean ignoreEmpty){ - return toArray(split(str, separator, limit, isTrim, ignoreEmpty)); - } + //检查是否超出范围(最大允许limit-1个,剩下一个留给末尾字符串) + if (limit > 0 && list.size() > limit - 2) { + break; + } + } + } + return addToList(list, str.substring(start, len), isTrim, ignoreEmpty);//收尾 + } - //---------------------------------------------------------------------------------------------- Split by String + /** + * 切分字符串为字符串数组 + * + * @param str 被切分的字符串 + * @param separator 分隔符字符 + * @param limit 限制分片数 + * @param isTrim 是否去除切分字符串后每个元素两边的空格 + * @param ignoreEmpty 是否忽略空串 + * @return 切分后的集合 + * @since 3.0.8 + */ + public static String[] splitToArray(String str, char separator, int limit, boolean isTrim, boolean ignoreEmpty) { + return toArray(split(str, separator, limit, isTrim, ignoreEmpty)); + } - /** - * 切分字符串,不忽略大小写 - * - * @param str 被切分的字符串 - * @param separator 分隔符字符串 - * @param isTrim 是否去除切分字符串后每个元素两边的空格 - * @param ignoreEmpty 是否忽略空串 - * @return 切分后的集合 - * @since 3.0.8 - */ - public static List split(String str, String separator, boolean isTrim, boolean ignoreEmpty){ - return split(str, separator, -1, isTrim, ignoreEmpty, false); - } + //---------------------------------------------------------------------------------------------- Split by String - /** - * 切分字符串,去除每个元素两边空格,忽略大小写 - * - * @param str 被切分的字符串 - * @param separator 分隔符字符串 - * @param ignoreEmpty 是否忽略空串 - * @return 切分后的集合 - * @since 3.2.1 - */ - public static List splitTrim(String str, String separator, boolean ignoreEmpty){ - return split(str, separator, true, ignoreEmpty); - } + /** + * 切分字符串,不忽略大小写 + * + * @param str 被切分的字符串 + * @param separator 分隔符字符串 + * @param isTrim 是否去除切分字符串后每个元素两边的空格 + * @param ignoreEmpty 是否忽略空串 + * @return 切分后的集合 + * @since 3.0.8 + */ + public static List split(String str, String separator, boolean isTrim, boolean ignoreEmpty) { + return split(str, separator, -1, isTrim, ignoreEmpty, false); + } - /** - * 切分字符串,不忽略大小写 - * - * @param str 被切分的字符串 - * @param separator 分隔符字符串 - * @param limit 限制分片数 - * @param isTrim 是否去除切分字符串后每个元素两边的空格 - * @param ignoreEmpty 是否忽略空串 - * @return 切分后的集合 - * @since 3.0.8 - */ - public static List split(String str, String separator, int limit, boolean isTrim, boolean ignoreEmpty){ - return split(str, separator, limit, isTrim, ignoreEmpty, false); - } + /** + * 切分字符串,去除每个元素两边空格,忽略大小写 + * + * @param str 被切分的字符串 + * @param separator 分隔符字符串 + * @param ignoreEmpty 是否忽略空串 + * @return 切分后的集合 + * @since 3.2.1 + */ + public static List splitTrim(String str, String separator, boolean ignoreEmpty) { + return split(str, separator, true, ignoreEmpty); + } - /** - * 切分字符串,去除每个元素两边空格,忽略大小写 - * - * @param str 被切分的字符串 - * @param separator 分隔符字符串 - * @param limit 限制分片数 - * @param ignoreEmpty 是否忽略空串 - * @return 切分后的集合 - * @since 3.2.1 - */ - public static List splitTrim(String str, String separator, int limit, boolean ignoreEmpty){ - return split(str, separator, limit, true, ignoreEmpty); - } + /** + * 切分字符串,不忽略大小写 + * + * @param str 被切分的字符串 + * @param separator 分隔符字符串 + * @param limit 限制分片数 + * @param isTrim 是否去除切分字符串后每个元素两边的空格 + * @param ignoreEmpty 是否忽略空串 + * @return 切分后的集合 + * @since 3.0.8 + */ + public static List split(String str, String separator, int limit, boolean isTrim, boolean ignoreEmpty) { + return split(str, separator, limit, isTrim, ignoreEmpty, false); + } - /** - * 切分字符串,忽略大小写 - * - * @param str 被切分的字符串 - * @param separator 分隔符字符串 - * @param limit 限制分片数 - * @param isTrim 是否去除切分字符串后每个元素两边的空格 - * @param ignoreEmpty 是否忽略空串 - * @return 切分后的集合 - * @since 3.2.1 - */ - public static List splitIgnoreCase(String str, String separator, int limit, boolean isTrim, boolean ignoreEmpty){ - return split(str, separator, limit, isTrim, ignoreEmpty, true); - } + /** + * 切分字符串,去除每个元素两边空格,忽略大小写 + * + * @param str 被切分的字符串 + * @param separator 分隔符字符串 + * @param limit 限制分片数 + * @param ignoreEmpty 是否忽略空串 + * @return 切分后的集合 + * @since 3.2.1 + */ + public static List splitTrim(String str, String separator, int limit, boolean ignoreEmpty) { + return split(str, separator, limit, true, ignoreEmpty); + } - /** - * 切分字符串,去除每个元素两边空格,忽略大小写 - * - * @param str 被切分的字符串 - * @param separator 分隔符字符串 - * @param limit 限制分片数 - * @param ignoreEmpty 是否忽略空串 - * @return 切分后的集合 - * @since 3.2.1 - */ - public static List splitTrimIgnoreCase(String str, String separator, int limit, boolean ignoreEmpty){ - return split(str, separator, limit, true, ignoreEmpty, true); - } + /** + * 切分字符串,忽略大小写 + * + * @param str 被切分的字符串 + * @param separator 分隔符字符串 + * @param limit 限制分片数 + * @param isTrim 是否去除切分字符串后每个元素两边的空格 + * @param ignoreEmpty 是否忽略空串 + * @return 切分后的集合 + * @since 3.2.1 + */ + public static List splitIgnoreCase(String str, String separator, int limit, boolean isTrim, boolean ignoreEmpty) { + return split(str, separator, limit, isTrim, ignoreEmpty, true); + } - /** - * 切分字符串 - * - * @param str 被切分的字符串 - * @param separator 分隔符字符串 - * @param limit 限制分片数 - * @param isTrim 是否去除切分字符串后每个元素两边的空格 - * @param ignoreEmpty 是否忽略空串 - * @param ignoreCase 是否忽略大小写 - * @return 切分后的集合 - * @since 3.2.1 - */ - public static List split(String str, String separator, int limit, boolean isTrim, boolean ignoreEmpty, boolean ignoreCase){ - if(StringUtil.isEmpty(str)){ - return new ArrayList(0); - } - if(limit == 1){ - return addToList(new ArrayList(1), str, isTrim, ignoreEmpty); - } + /** + * 切分字符串,去除每个元素两边空格,忽略大小写 + * + * @param str 被切分的字符串 + * @param separator 分隔符字符串 + * @param limit 限制分片数 + * @param ignoreEmpty 是否忽略空串 + * @return 切分后的集合 + * @since 3.2.1 + */ + public static List splitTrimIgnoreCase(String str, String separator, int limit, boolean ignoreEmpty) { + return split(str, separator, limit, true, ignoreEmpty, true); + } - if(StringUtil.isEmpty(separator)){//分隔符为空时按照空白符切分 - return split(str, limit); - }else if(separator.length() == 1){//分隔符只有一个字符长度时按照单分隔符切分 - return split(str, separator.charAt(0), limit, isTrim, ignoreEmpty, ignoreCase); - } + /** + * 切分字符串 + * + * @param str 被切分的字符串 + * @param separator 分隔符字符串 + * @param limit 限制分片数 + * @param isTrim 是否去除切分字符串后每个元素两边的空格 + * @param ignoreEmpty 是否忽略空串 + * @param ignoreCase 是否忽略大小写 + * @return 切分后的集合 + * @since 3.2.1 + */ + public static List split(String str, String separator, int limit, boolean isTrim, boolean ignoreEmpty, boolean ignoreCase) { + if (StringUtil.isEmpty(str)) { + return new ArrayList(0); + } + if (limit == 1) { + return addToList(new ArrayList(1), str, isTrim, ignoreEmpty); + } - final ArrayList list = new ArrayList<>(); - int len = str.length(); - int separatorLen = separator.length(); - int start = 0; - int i = 0; - while(i < len){ - i = StringUtil.indexOf(str, separator, start, ignoreCase); - if(i > -1){ - addToList(list, str.substring(start, i), isTrim, ignoreEmpty); - start = i + separatorLen; + if (StringUtil.isEmpty(separator)) {//分隔符为空时按照空白符切分 + return split(str, limit); + } else if (separator.length() == 1) {//分隔符只有一个字符长度时按照单分隔符切分 + return split(str, separator.charAt(0), limit, isTrim, ignoreEmpty, ignoreCase); + } - //检查是否超出范围(最大允许limit-1个,剩下一个留给末尾字符串) - if(limit > 0 && list.size() > limit-2){ - break; - } - }else{ - break; - } - } - return addToList(list, str.substring(start, len), isTrim, ignoreEmpty); - } + final ArrayList list = new ArrayList<>(); + int len = str.length(); + int separatorLen = separator.length(); + int start = 0; + int i = 0; + while (i < len) { + i = StringUtil.indexOf(str, separator, start, ignoreCase); + if (i > -1) { + addToList(list, str.substring(start, i), isTrim, ignoreEmpty); + start = i + separatorLen; - /** - * 切分字符串为字符串数组 - * - * @param str 被切分的字符串 - * @param separator 分隔符字符 - * @param limit 限制分片数 - * @param isTrim 是否去除切分字符串后每个元素两边的空格 - * @param ignoreEmpty 是否忽略空串 - * @return 切分后的集合 - * @since 3.0.8 - */ - public static String[] splitToArray(String str, String separator, int limit, boolean isTrim, boolean ignoreEmpty){ - return toArray(split(str, separator, limit, isTrim, ignoreEmpty)); - } + //检查是否超出范围(最大允许limit-1个,剩下一个留给末尾字符串) + if (limit > 0 && list.size() > limit - 2) { + break; + } + } else { + break; + } + } + return addToList(list, str.substring(start, len), isTrim, ignoreEmpty); + } - //---------------------------------------------------------------------------------------------- Split by Whitespace + /** + * 切分字符串为字符串数组 + * + * @param str 被切分的字符串 + * @param separator 分隔符字符 + * @param limit 限制分片数 + * @param isTrim 是否去除切分字符串后每个元素两边的空格 + * @param ignoreEmpty 是否忽略空串 + * @return 切分后的集合 + * @since 3.0.8 + */ + public static String[] splitToArray(String str, String separator, int limit, boolean isTrim, boolean ignoreEmpty) { + return toArray(split(str, separator, limit, isTrim, ignoreEmpty)); + } - /** - * 使用空白符切分字符串
- * 切分后的字符串两边不包含空白符,空串或空白符串并不做为元素之一 - * - * @param str 被切分的字符串 - * @param limit 限制分片数 - * @return 切分后的集合 - * @since 3.0.8 - */ - public static List split(String str, int limit){ - if(StringUtil.isEmpty(str)){ - return new ArrayList(0); - } - if(limit == 1){ - return addToList(new ArrayList(1), str, true, true); - } + //---------------------------------------------------------------------------------------------- Split by Whitespace - final ArrayList list = new ArrayList<>(); - int len = str.length(); - int start = 0;//切分后每个部分的起始 - for(int i = 0; i < len; i++){ - if(Func.isEmpty(str.charAt(i))){ - addToList(list, str.substring(start, i), true, true); - start = i+1;//i+1同时将start与i保持一致 + /** + * 使用空白符切分字符串
+ * 切分后的字符串两边不包含空白符,空串或空白符串并不做为元素之一 + * + * @param str 被切分的字符串 + * @param limit 限制分片数 + * @return 切分后的集合 + * @since 3.0.8 + */ + public static List split(String str, int limit) { + if (StringUtil.isEmpty(str)) { + return new ArrayList(0); + } + if (limit == 1) { + return addToList(new ArrayList(1), str, true, true); + } - //检查是否超出范围(最大允许limit-1个,剩下一个留给末尾字符串) - if(limit > 0 && list.size() > limit-2){ - break; - } - } - } - return addToList(list, str.substring(start, len), true, true);//收尾 - } + final ArrayList list = new ArrayList<>(); + int len = str.length(); + int start = 0;//切分后每个部分的起始 + for (int i = 0; i < len; i++) { + if (Func.isEmpty(str.charAt(i))) { + addToList(list, str.substring(start, i), true, true); + start = i + 1;//i+1同时将start与i保持一致 - /** - * 切分字符串为字符串数组 - * - * @param str 被切分的字符串 - * @param limit 限制分片数 - * @return 切分后的集合 - * @since 3.0.8 - */ - public static String[] splitToArray(String str, int limit){ - return toArray(split(str, limit)); - } + //检查是否超出范围(最大允许limit-1个,剩下一个留给末尾字符串) + if (limit > 0 && list.size() > limit - 2) { + break; + } + } + } + return addToList(list, str.substring(start, len), true, true);//收尾 + } - //---------------------------------------------------------------------------------------------- Split by regex + /** + * 切分字符串为字符串数组 + * + * @param str 被切分的字符串 + * @param limit 限制分片数 + * @return 切分后的集合 + * @since 3.0.8 + */ + public static String[] splitToArray(String str, int limit) { + return toArray(split(str, limit)); + } - /** - * 通过正则切分字符串 - * @param str 字符串 - * @param separatorPattern 分隔符正则{@link Pattern} - * @param limit 限制分片数 - * @param isTrim 是否去除切分字符串后每个元素两边的空格 - * @param ignoreEmpty 是否忽略空串 - * @return 切分后的集合 - * @since 3.0.8 - */ - public static List split(String str, Pattern separatorPattern, int limit, boolean isTrim, boolean ignoreEmpty){ - if(StringUtil.isEmpty(str)){ - return new ArrayList(0); - } - if(limit == 1){ - return addToList(new ArrayList(1), str, isTrim, ignoreEmpty); - } + //---------------------------------------------------------------------------------------------- Split by regex - if(null == separatorPattern){//分隔符为空时按照空白符切分 - return split(str, limit); - } + /** + * 通过正则切分字符串 + * + * @param str 字符串 + * @param separatorPattern 分隔符正则{@link Pattern} + * @param limit 限制分片数 + * @param isTrim 是否去除切分字符串后每个元素两边的空格 + * @param ignoreEmpty 是否忽略空串 + * @return 切分后的集合 + * @since 3.0.8 + */ + public static List split(String str, Pattern separatorPattern, int limit, boolean isTrim, boolean ignoreEmpty) { + if (StringUtil.isEmpty(str)) { + return new ArrayList(0); + } + if (limit == 1) { + return addToList(new ArrayList(1), str, isTrim, ignoreEmpty); + } - final Matcher matcher = separatorPattern.matcher(str); - final ArrayList list = new ArrayList<>(); - int len = str.length(); - int start = 0; - while(matcher.find()){ - addToList(list, str.substring(start, matcher.start()), isTrim, ignoreEmpty); - start = matcher.end(); + if (null == separatorPattern) {//分隔符为空时按照空白符切分 + return split(str, limit); + } - //检查是否超出范围(最大允许limit-1个,剩下一个留给末尾字符串) - if(limit > 0 && list.size() > limit-2){ - break; - } - } - return addToList(list, str.substring(start, len), isTrim, ignoreEmpty); - } + final Matcher matcher = separatorPattern.matcher(str); + final ArrayList list = new ArrayList<>(); + int len = str.length(); + int start = 0; + while (matcher.find()) { + addToList(list, str.substring(start, matcher.start()), isTrim, ignoreEmpty); + start = matcher.end(); - /** - * 通过正则切分字符串为字符串数组 - * - * @param str 被切分的字符串 - * @param separatorPattern 分隔符正则{@link Pattern} - * @param limit 限制分片数 - * @param isTrim 是否去除切分字符串后每个元素两边的空格 - * @param ignoreEmpty 是否忽略空串 - * @return 切分后的集合 - * @since 3.0.8 - */ - public static String[] splitToArray(String str, Pattern separatorPattern, int limit, boolean isTrim, boolean ignoreEmpty){ - return toArray(split(str, separatorPattern, limit, isTrim, ignoreEmpty)); - } + //检查是否超出范围(最大允许limit-1个,剩下一个留给末尾字符串) + if (limit > 0 && list.size() > limit - 2) { + break; + } + } + return addToList(list, str.substring(start, len), isTrim, ignoreEmpty); + } - //---------------------------------------------------------------------------------------------- Split by length + /** + * 通过正则切分字符串为字符串数组 + * + * @param str 被切分的字符串 + * @param separatorPattern 分隔符正则{@link Pattern} + * @param limit 限制分片数 + * @param isTrim 是否去除切分字符串后每个元素两边的空格 + * @param ignoreEmpty 是否忽略空串 + * @return 切分后的集合 + * @since 3.0.8 + */ + public static String[] splitToArray(String str, Pattern separatorPattern, int limit, boolean isTrim, boolean ignoreEmpty) { + return toArray(split(str, separatorPattern, limit, isTrim, ignoreEmpty)); + } - /** - * 根据给定长度,将给定字符串截取为多个部分 - * - * @param str 字符串 - * @param len 每一个小节的长度 - * @return 截取后的字符串数组 - */ - public static String[] splitByLength(String str, int len) { - int partCount = str.length() / len; - int lastPartCount = str.length() % len; - int fixPart = 0; - if (lastPartCount != 0) { - fixPart = 1; - } + //---------------------------------------------------------------------------------------------- Split by length - final String[] strs = new String[partCount + fixPart]; - for (int i = 0; i < partCount + fixPart; i++) { - if (i == partCount + fixPart - 1 && lastPartCount != 0) { - strs[i] = str.substring(i * len, i * len + lastPartCount); - } else { - strs[i] = str.substring(i * len, i * len + len); - } - } - return strs; - } + /** + * 根据给定长度,将给定字符串截取为多个部分 + * + * @param str 字符串 + * @param len 每一个小节的长度 + * @return 截取后的字符串数组 + */ + public static String[] splitByLength(String str, int len) { + int partCount = str.length() / len; + int lastPartCount = str.length() % len; + int fixPart = 0; + if (lastPartCount != 0) { + fixPart = 1; + } - //---------------------------------------------------------------------------------------------------------- Private method start - /** - * 将字符串加入List中 - * @param list 列表 - * @param part 被加入的部分 - * @param isTrim 是否去除两端空白符 - * @param ignoreEmpty 是否略过空字符串(空字符串不做为一个元素) - * @return 列表 - */ - private static List addToList(List list, String part, boolean isTrim, boolean ignoreEmpty){ - part = part.toString(); - if(isTrim){ - part = part.trim(); - } - if(false == ignoreEmpty || false == part.isEmpty()){ - list.add(part); - } - return list; - } + final String[] strs = new String[partCount + fixPart]; + for (int i = 0; i < partCount + fixPart; i++) { + if (i == partCount + fixPart - 1 && lastPartCount != 0) { + strs[i] = str.substring(i * len, i * len + lastPartCount); + } else { + strs[i] = str.substring(i * len, i * len + len); + } + } + return strs; + } - /** - * List转Array - * @param list List - * @return Array - */ - private static String[] toArray(List list){ - return list.toArray(new String[list.size()]); - } - //---------------------------------------------------------------------------------------------------------- Private method end + //---------------------------------------------------------------------------------------------------------- Private method start + + /** + * 将字符串加入List中 + * + * @param list 列表 + * @param part 被加入的部分 + * @param isTrim 是否去除两端空白符 + * @param ignoreEmpty 是否略过空字符串(空字符串不做为一个元素) + * @return 列表 + */ + private static List addToList(List list, String part, boolean isTrim, boolean ignoreEmpty) { + part = part.toString(); + if (isTrim) { + part = part.trim(); + } + if (false == ignoreEmpty || false == part.isEmpty()) { + list.add(part); + } + return list; + } + + /** + * List转Array + * + * @param list List + * @return Array + */ + private static String[] toArray(List list) { + return list.toArray(new String[list.size()]); + } + //---------------------------------------------------------------------------------------------------------- Private method end } diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/support/Try.java b/blade-core-tool/src/main/java/org/springblade/core/tool/support/Try.java index 0900248..215a0a5 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/support/Try.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/support/Try.java @@ -8,6 +8,8 @@ import java.util.function.Function; /** * 当 Lambda 遇上受检异常 * https://segmentfault.com/a/1190000007832130 + * + * @author smallchill */ public class Try { diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/support/xss/HTMLFilter.java b/blade-core-tool/src/main/java/org/springblade/core/tool/support/xss/HTMLFilter.java index 9d99b42..fa0959b 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/support/xss/HTMLFilter.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/support/xss/HTMLFilter.java @@ -41,514 +41,514 @@ import java.util.regex.Pattern; */ public final class HTMLFilter { - /** - * regex flag union representing /si modifiers in php - **/ - private static final int REGEX_FLAGS_SI = Pattern.CASE_INSENSITIVE | Pattern.DOTALL; - private static final Pattern P_COMMENTS = Pattern.compile("", Pattern.DOTALL); - private static final Pattern P_COMMENT = Pattern.compile("^!--(.*)--$", REGEX_FLAGS_SI); - private static final Pattern P_TAGS = Pattern.compile("<(.*?)>", Pattern.DOTALL); - private static final Pattern P_END_TAG = Pattern.compile("^/([a-z0-9]+)", REGEX_FLAGS_SI); - private static final Pattern P_START_TAG = Pattern.compile("^([a-z0-9]+)(.*?)(/?)$", REGEX_FLAGS_SI); - private static final Pattern P_QUOTED_ATTRIBUTES = Pattern.compile("([a-z0-9]+)=([\"'])(.*?)\\2", REGEX_FLAGS_SI); - private static final Pattern P_UNQUOTED_ATTRIBUTES = Pattern.compile("([a-z0-9]+)(=)([^\"\\s']+)", REGEX_FLAGS_SI); - private static final Pattern P_PROTOCOL = Pattern.compile("^([^:]+):", REGEX_FLAGS_SI); - private static final Pattern P_ENTITY = Pattern.compile("&#(\\d+);?"); - private static final Pattern P_ENTITY_UNICODE = Pattern.compile("&#x([0-9a-f]+);?"); - private static final Pattern P_ENCODE = Pattern.compile("%([0-9a-f]{2});?"); - private static final Pattern P_VALID_ENTITIES = Pattern.compile("&([^&;]*)(?=(;|&|$))"); - private static final Pattern P_VALID_QUOTES = Pattern.compile("(>|^)([^<]+?)(<|$)", Pattern.DOTALL); - private static final Pattern P_END_ARROW = Pattern.compile("^>"); - private static final Pattern P_BODY_TO_END = Pattern.compile("<([^>]*?)(?=<|$)"); - private static final Pattern P_XML_CONTENT = Pattern.compile("(^|>)([^<]*?)(?=>)"); - private static final Pattern P_STRAY_LEFT_ARROW = Pattern.compile("<([^>]*?)(?=<|$)"); - private static final Pattern P_STRAY_RIGHT_ARROW = Pattern.compile("(^|>)([^<]*?)(?=>)"); - private static final Pattern P_AMP = Pattern.compile("&"); - private static final Pattern P_QUOTE = Pattern.compile("<"); - private static final Pattern P_LEFT_ARROW = Pattern.compile("<"); - private static final Pattern P_RIGHT_ARROW = Pattern.compile(">"); - private static final Pattern P_BOTH_ARROWS = Pattern.compile("<>"); + /** + * regex flag union representing /si modifiers in php + **/ + private static final int REGEX_FLAGS_SI = Pattern.CASE_INSENSITIVE | Pattern.DOTALL; + private static final Pattern P_COMMENTS = Pattern.compile("", Pattern.DOTALL); + private static final Pattern P_COMMENT = Pattern.compile("^!--(.*)--$", REGEX_FLAGS_SI); + private static final Pattern P_TAGS = Pattern.compile("<(.*?)>", Pattern.DOTALL); + private static final Pattern P_END_TAG = Pattern.compile("^/([a-z0-9]+)", REGEX_FLAGS_SI); + private static final Pattern P_START_TAG = Pattern.compile("^([a-z0-9]+)(.*?)(/?)$", REGEX_FLAGS_SI); + private static final Pattern P_QUOTED_ATTRIBUTES = Pattern.compile("([a-z0-9]+)=([\"'])(.*?)\\2", REGEX_FLAGS_SI); + private static final Pattern P_UNQUOTED_ATTRIBUTES = Pattern.compile("([a-z0-9]+)(=)([^\"\\s']+)", REGEX_FLAGS_SI); + private static final Pattern P_PROTOCOL = Pattern.compile("^([^:]+):", REGEX_FLAGS_SI); + private static final Pattern P_ENTITY = Pattern.compile("&#(\\d+);?"); + private static final Pattern P_ENTITY_UNICODE = Pattern.compile("&#x([0-9a-f]+);?"); + private static final Pattern P_ENCODE = Pattern.compile("%([0-9a-f]{2});?"); + private static final Pattern P_VALID_ENTITIES = Pattern.compile("&([^&;]*)(?=(;|&|$))"); + private static final Pattern P_VALID_QUOTES = Pattern.compile("(>|^)([^<]+?)(<|$)", Pattern.DOTALL); + private static final Pattern P_END_ARROW = Pattern.compile("^>"); + private static final Pattern P_BODY_TO_END = Pattern.compile("<([^>]*?)(?=<|$)"); + private static final Pattern P_XML_CONTENT = Pattern.compile("(^|>)([^<]*?)(?=>)"); + private static final Pattern P_STRAY_LEFT_ARROW = Pattern.compile("<([^>]*?)(?=<|$)"); + private static final Pattern P_STRAY_RIGHT_ARROW = Pattern.compile("(^|>)([^<]*?)(?=>)"); + private static final Pattern P_AMP = Pattern.compile("&"); + private static final Pattern P_QUOTE = Pattern.compile("<"); + private static final Pattern P_LEFT_ARROW = Pattern.compile("<"); + private static final Pattern P_RIGHT_ARROW = Pattern.compile(">"); + private static final Pattern P_BOTH_ARROWS = Pattern.compile("<>"); - // @xxx could grow large... maybe use sesat's ReferenceMap - private static final ConcurrentMap P_REMOVE_PAIR_BLANKS = new ConcurrentHashMap(); - private static final ConcurrentMap P_REMOVE_SELF_BLANKS = new ConcurrentHashMap(); + // @xxx could grow large... maybe use sesat's ReferenceMap + private static final ConcurrentMap P_REMOVE_PAIR_BLANKS = new ConcurrentHashMap(); + private static final ConcurrentMap P_REMOVE_SELF_BLANKS = new ConcurrentHashMap(); - /** - * set of allowed html elements, along with allowed attributes for each element - **/ - private final Map> vAllowed; - /** - * counts of open tags for each (allowable) html element - **/ - private final Map vTagCounts = new HashMap(); + /** + * set of allowed html elements, along with allowed attributes for each element + **/ + private final Map> vAllowed; + /** + * counts of open tags for each (allowable) html element + **/ + private final Map vTagCounts = new HashMap(); - /** - * html elements which must always be self-closing (e.g. "") - **/ - private final String[] vSelfClosingTags; - /** - * html elements which must always have separate opening and closing tags (e.g. "") - **/ - private final String[] vNeedClosingTags; - /** - * set of disallowed html elements - **/ - private final String[] vDisallowed; - /** - * attributes which should be checked for valid protocols - **/ - private final String[] vProtocolAtts; - /** - * allowed protocols - **/ - private final String[] vAllowedProtocols; - /** - * tags which should be removed if they contain no content (e.g. "" or "") - **/ - private final String[] vRemoveBlanks; - /** - * entities allowed within html markup - **/ - private final String[] vAllowedEntities; - /** - * flag determining whether comments are allowed in input String. - */ - private final boolean stripComment; - private final boolean encodeQuotes; - private boolean vDebug = false; - /** - * flag determining whether to try to make tags when presented with "unbalanced" - * angle brackets (e.g. "" becomes " text "). If set to false, - * unbalanced angle brackets will be html escaped. - */ - private final boolean alwaysMakeTags; + /** + * html elements which must always be self-closing (e.g. "") + **/ + private final String[] vSelfClosingTags; + /** + * html elements which must always have separate opening and closing tags (e.g. "") + **/ + private final String[] vNeedClosingTags; + /** + * set of disallowed html elements + **/ + private final String[] vDisallowed; + /** + * attributes which should be checked for valid protocols + **/ + private final String[] vProtocolAtts; + /** + * allowed protocols + **/ + private final String[] vAllowedProtocols; + /** + * tags which should be removed if they contain no content (e.g. "" or "") + **/ + private final String[] vRemoveBlanks; + /** + * entities allowed within html markup + **/ + private final String[] vAllowedEntities; + /** + * flag determining whether comments are allowed in input String. + */ + private final boolean stripComment; + private final boolean encodeQuotes; + private boolean vDebug = false; + /** + * flag determining whether to try to make tags when presented with "unbalanced" + * angle brackets (e.g. "" becomes " text "). If set to false, + * unbalanced angle brackets will be html escaped. + */ + private final boolean alwaysMakeTags; - /** - * Default constructor. - */ - public HTMLFilter() { - vAllowed = new HashMap<>(); + /** + * Default constructor. + */ + public HTMLFilter() { + vAllowed = new HashMap<>(); - final ArrayList a_atts = new ArrayList(); - a_atts.add("href"); - a_atts.add("target"); - vAllowed.put("a", a_atts); + final ArrayList a_atts = new ArrayList(); + a_atts.add("href"); + a_atts.add("target"); + vAllowed.put("a", a_atts); - final ArrayList img_atts = new ArrayList(); - img_atts.add("src"); - img_atts.add("width"); - img_atts.add("height"); - img_atts.add("alt"); - vAllowed.put("img", img_atts); + final ArrayList img_atts = new ArrayList(); + img_atts.add("src"); + img_atts.add("width"); + img_atts.add("height"); + img_atts.add("alt"); + vAllowed.put("img", img_atts); - final ArrayList no_atts = new ArrayList(); - vAllowed.put("b", no_atts); - vAllowed.put("strong", no_atts); - vAllowed.put("i", no_atts); - vAllowed.put("em", no_atts); + final ArrayList no_atts = new ArrayList(); + vAllowed.put("b", no_atts); + vAllowed.put("strong", no_atts); + vAllowed.put("i", no_atts); + vAllowed.put("em", no_atts); - vSelfClosingTags = new String[]{"img"}; - vNeedClosingTags = new String[]{"a", "b", "strong", "i", "em"}; - vDisallowed = new String[]{}; - vAllowedProtocols = new String[]{"http", "mailto", "https"}; // no ftp. - vProtocolAtts = new String[]{"src", "href"}; - vRemoveBlanks = new String[]{"a", "b", "strong", "i", "em"}; - vAllowedEntities = new String[]{"amp", "gt", "lt", "quot"}; - stripComment = true; - encodeQuotes = true; - alwaysMakeTags = true; - } + vSelfClosingTags = new String[]{"img"}; + vNeedClosingTags = new String[]{"a", "b", "strong", "i", "em"}; + vDisallowed = new String[]{}; + vAllowedProtocols = new String[]{"http", "mailto", "https"}; // no ftp. + vProtocolAtts = new String[]{"src", "href"}; + vRemoveBlanks = new String[]{"a", "b", "strong", "i", "em"}; + vAllowedEntities = new String[]{"amp", "gt", "lt", "quot"}; + stripComment = true; + encodeQuotes = true; + alwaysMakeTags = true; + } - /** - * Set debug flag to true. Otherwise use default settings. See the default constructor. - * - * @param debug turn debug on with a true argument - */ - public HTMLFilter(final boolean debug) { - this(); - vDebug = debug; + /** + * Set debug flag to true. Otherwise use default settings. See the default constructor. + * + * @param debug turn debug on with a true argument + */ + public HTMLFilter(final boolean debug) { + this(); + vDebug = debug; - } + } - /** - * Map-parameter configurable constructor. - * - * @param conf map containing configuration. keys match field names. - */ - public HTMLFilter(final Map conf) { + /** + * Map-parameter configurable constructor. + * + * @param conf map containing configuration. keys match field names. + */ + public HTMLFilter(final Map conf) { - assert conf.containsKey("vAllowed") : "configuration requires vAllowed"; - assert conf.containsKey("vSelfClosingTags") : "configuration requires vSelfClosingTags"; - assert conf.containsKey("vNeedClosingTags") : "configuration requires vNeedClosingTags"; - assert conf.containsKey("vDisallowed") : "configuration requires vDisallowed"; - assert conf.containsKey("vAllowedProtocols") : "configuration requires vAllowedProtocols"; - assert conf.containsKey("vProtocolAtts") : "configuration requires vProtocolAtts"; - assert conf.containsKey("vRemoveBlanks") : "configuration requires vRemoveBlanks"; - assert conf.containsKey("vAllowedEntities") : "configuration requires vAllowedEntities"; + assert conf.containsKey("vAllowed") : "configuration requires vAllowed"; + assert conf.containsKey("vSelfClosingTags") : "configuration requires vSelfClosingTags"; + assert conf.containsKey("vNeedClosingTags") : "configuration requires vNeedClosingTags"; + assert conf.containsKey("vDisallowed") : "configuration requires vDisallowed"; + assert conf.containsKey("vAllowedProtocols") : "configuration requires vAllowedProtocols"; + assert conf.containsKey("vProtocolAtts") : "configuration requires vProtocolAtts"; + assert conf.containsKey("vRemoveBlanks") : "configuration requires vRemoveBlanks"; + assert conf.containsKey("vAllowedEntities") : "configuration requires vAllowedEntities"; - vAllowed = Collections.unmodifiableMap((HashMap>) conf.get("vAllowed")); - vSelfClosingTags = (String[]) conf.get("vSelfClosingTags"); - vNeedClosingTags = (String[]) conf.get("vNeedClosingTags"); - vDisallowed = (String[]) conf.get("vDisallowed"); - vAllowedProtocols = (String[]) conf.get("vAllowedProtocols"); - vProtocolAtts = (String[]) conf.get("vProtocolAtts"); - vRemoveBlanks = (String[]) conf.get("vRemoveBlanks"); - vAllowedEntities = (String[]) conf.get("vAllowedEntities"); - stripComment = conf.containsKey("stripComment") ? (Boolean) conf.get("stripComment") : true; - encodeQuotes = conf.containsKey("encodeQuotes") ? (Boolean) conf.get("encodeQuotes") : true; - alwaysMakeTags = conf.containsKey("alwaysMakeTags") ? (Boolean) conf.get("alwaysMakeTags") : true; - } + vAllowed = Collections.unmodifiableMap((HashMap>) conf.get("vAllowed")); + vSelfClosingTags = (String[]) conf.get("vSelfClosingTags"); + vNeedClosingTags = (String[]) conf.get("vNeedClosingTags"); + vDisallowed = (String[]) conf.get("vDisallowed"); + vAllowedProtocols = (String[]) conf.get("vAllowedProtocols"); + vProtocolAtts = (String[]) conf.get("vProtocolAtts"); + vRemoveBlanks = (String[]) conf.get("vRemoveBlanks"); + vAllowedEntities = (String[]) conf.get("vAllowedEntities"); + stripComment = conf.containsKey("stripComment") ? (Boolean) conf.get("stripComment") : true; + encodeQuotes = conf.containsKey("encodeQuotes") ? (Boolean) conf.get("encodeQuotes") : true; + alwaysMakeTags = conf.containsKey("alwaysMakeTags") ? (Boolean) conf.get("alwaysMakeTags") : true; + } - private void reset() { - vTagCounts.clear(); - } + private void reset() { + vTagCounts.clear(); + } - private void debug(final String msg) { - if (vDebug) { - Logger.getAnonymousLogger().info(msg); - } - } + private void debug(final String msg) { + if (vDebug) { + Logger.getAnonymousLogger().info(msg); + } + } - //--------------------------------------------------------------- - // my versions of some PHP library functions - public static String chr(final int decimal) { - return String.valueOf((char) decimal); - } + //--------------------------------------------------------------- + // my versions of some PHP library functions + public static String chr(final int decimal) { + return String.valueOf((char) decimal); + } - public static String htmlSpecialChars(final String s) { - String result = s; - result = regexReplace(P_AMP, "&", result); - result = regexReplace(P_QUOTE, """, result); - result = regexReplace(P_LEFT_ARROW, "<", result); - result = regexReplace(P_RIGHT_ARROW, ">", result); - return result; - } + public static String htmlSpecialChars(final String s) { + String result = s; + result = regexReplace(P_AMP, "&", result); + result = regexReplace(P_QUOTE, """, result); + result = regexReplace(P_LEFT_ARROW, "<", result); + result = regexReplace(P_RIGHT_ARROW, ">", result); + return result; + } - //--------------------------------------------------------------- + //--------------------------------------------------------------- - /** - * given a user submitted input String, filter out any invalid or restricted - * html. - * - * @param input text (i.e. submitted by a user) than may contain html - * @return "clean" version of input, with only valid, whitelisted html elements allowed - */ - public String filter(final String input) { - reset(); - String s = input; + /** + * given a user submitted input String, filter out any invalid or restricted + * html. + * + * @param input text (i.e. submitted by a user) than may contain html + * @return "clean" version of input, with only valid, whitelisted html elements allowed + */ + public String filter(final String input) { + reset(); + String s = input; - debug("************************************************"); - debug(" INPUT: " + input); + debug("************************************************"); + debug(" INPUT: " + input); - s = escapeComments(s); - debug(" escapeComments: " + s); + s = escapeComments(s); + debug(" escapeComments: " + s); - s = balanceHTML(s); - debug(" balanceHTML: " + s); + s = balanceHTML(s); + debug(" balanceHTML: " + s); - s = checkTags(s); - debug(" checkTags: " + s); + s = checkTags(s); + debug(" checkTags: " + s); - s = processRemoveBlanks(s); - debug("processRemoveBlanks: " + s); + s = processRemoveBlanks(s); + debug("processRemoveBlanks: " + s); - s = validateEntities(s); - debug(" validateEntites: " + s); + s = validateEntities(s); + debug(" validateEntites: " + s); - debug("************************************************\n\n"); - return s; - } + debug("************************************************\n\n"); + return s; + } - public boolean isAlwaysMakeTags() { - return alwaysMakeTags; - } + public boolean isAlwaysMakeTags() { + return alwaysMakeTags; + } - public boolean isStripComments() { - return stripComment; - } + public boolean isStripComments() { + return stripComment; + } - private String escapeComments(final String s) { - final Matcher m = P_COMMENTS.matcher(s); - final StringBuffer buf = new StringBuffer(); - if (m.find()) { - final String match = m.group(1); //(.*?) - m.appendReplacement(buf, Matcher.quoteReplacement("")); - } - m.appendTail(buf); + private String escapeComments(final String s) { + final Matcher m = P_COMMENTS.matcher(s); + final StringBuffer buf = new StringBuffer(); + if (m.find()) { + final String match = m.group(1); //(.*?) + m.appendReplacement(buf, Matcher.quoteReplacement("")); + } + m.appendTail(buf); - return buf.toString(); - } + return buf.toString(); + } - private String balanceHTML(String s) { - if (alwaysMakeTags) { - // - // try and form html - // - s = regexReplace(P_END_ARROW, "", s); - s = regexReplace(P_BODY_TO_END, "<$1>", s); - s = regexReplace(P_XML_CONTENT, "$1<$2", s); + private String balanceHTML(String s) { + if (alwaysMakeTags) { + // + // try and form html + // + s = regexReplace(P_END_ARROW, "", s); + s = regexReplace(P_BODY_TO_END, "<$1>", s); + s = regexReplace(P_XML_CONTENT, "$1<$2", s); - } else { - // - // escape stray brackets - // - s = regexReplace(P_STRAY_LEFT_ARROW, "<$1", s); - s = regexReplace(P_STRAY_RIGHT_ARROW, "$1$2><", s); + } else { + // + // escape stray brackets + // + s = regexReplace(P_STRAY_LEFT_ARROW, "<$1", s); + s = regexReplace(P_STRAY_RIGHT_ARROW, "$1$2><", s); - // - // the last regexp causes '<>' entities to appear - // (we need to do a lookahead assertion so that the last bracket can - // be used in the next pass of the regexp) - // - s = regexReplace(P_BOTH_ARROWS, "", s); - } + // + // the last regexp causes '<>' entities to appear + // (we need to do a lookahead assertion so that the last bracket can + // be used in the next pass of the regexp) + // + s = regexReplace(P_BOTH_ARROWS, "", s); + } - return s; - } + return s; + } - private String checkTags(String s) { - Matcher m = P_TAGS.matcher(s); + private String checkTags(String s) { + Matcher m = P_TAGS.matcher(s); - final StringBuffer buf = new StringBuffer(); - while (m.find()) { - String replaceStr = m.group(1); - replaceStr = processTag(replaceStr); - m.appendReplacement(buf, Matcher.quoteReplacement(replaceStr)); - } - m.appendTail(buf); + final StringBuffer buf = new StringBuffer(); + while (m.find()) { + String replaceStr = m.group(1); + replaceStr = processTag(replaceStr); + m.appendReplacement(buf, Matcher.quoteReplacement(replaceStr)); + } + m.appendTail(buf); - s = buf.toString(); + s = buf.toString(); - // these get tallied in processTag - // (remember to reset before subsequent calls to filter method) - for (String key : vTagCounts.keySet()) { - for (int ii = 0; ii < vTagCounts.get(key); ii++) { - s += ""; - } - } + // these get tallied in processTag + // (remember to reset before subsequent calls to filter method) + for (String key : vTagCounts.keySet()) { + for (int ii = 0; ii < vTagCounts.get(key); ii++) { + s += ""; + } + } - return s; - } + return s; + } - private String processRemoveBlanks(final String s) { - String result = s; - for (String tag : vRemoveBlanks) { - if (!P_REMOVE_PAIR_BLANKS.containsKey(tag)) { - P_REMOVE_PAIR_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?>")); - } - result = regexReplace(P_REMOVE_PAIR_BLANKS.get(tag), "", result); - if (!P_REMOVE_SELF_BLANKS.containsKey(tag)) { - P_REMOVE_SELF_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?/>")); - } - result = regexReplace(P_REMOVE_SELF_BLANKS.get(tag), "", result); - } + private String processRemoveBlanks(final String s) { + String result = s; + for (String tag : vRemoveBlanks) { + if (!P_REMOVE_PAIR_BLANKS.containsKey(tag)) { + P_REMOVE_PAIR_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?>")); + } + result = regexReplace(P_REMOVE_PAIR_BLANKS.get(tag), "", result); + if (!P_REMOVE_SELF_BLANKS.containsKey(tag)) { + P_REMOVE_SELF_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?/>")); + } + result = regexReplace(P_REMOVE_SELF_BLANKS.get(tag), "", result); + } - return result; - } + return result; + } - private static String regexReplace(final Pattern regex_pattern, final String replacement, final String s) { - Matcher m = regex_pattern.matcher(s); - return m.replaceAll(replacement); - } + private static String regexReplace(final Pattern regex_pattern, final String replacement, final String s) { + Matcher m = regex_pattern.matcher(s); + return m.replaceAll(replacement); + } - private String processTag(final String s) { - // ending tags - Matcher m = P_END_TAG.matcher(s); - if (m.find()) { - final String name = m.group(1).toLowerCase(); - if (allowed(name)) { - if (!inArray(name, vSelfClosingTags)) { - if (vTagCounts.containsKey(name)) { - vTagCounts.put(name, vTagCounts.get(name) - 1); - return ""; - } - } - } - } + private String processTag(final String s) { + // ending tags + Matcher m = P_END_TAG.matcher(s); + if (m.find()) { + final String name = m.group(1).toLowerCase(); + if (allowed(name)) { + if (!inArray(name, vSelfClosingTags)) { + if (vTagCounts.containsKey(name)) { + vTagCounts.put(name, vTagCounts.get(name) - 1); + return ""; + } + } + } + } - // starting tags - m = P_START_TAG.matcher(s); - if (m.find()) { - final String name = m.group(1).toLowerCase(); - final String body = m.group(2); - String ending = m.group(3); + // starting tags + m = P_START_TAG.matcher(s); + if (m.find()) { + final String name = m.group(1).toLowerCase(); + final String body = m.group(2); + String ending = m.group(3); - //debug( "in a starting tag, name='" + name + "'; body='" + body + "'; ending='" + ending + "'" ); - if (allowed(name)) { - String params = ""; + //debug( "in a starting tag, name='" + name + "'; body='" + body + "'; ending='" + ending + "'" ); + if (allowed(name)) { + String params = ""; - final Matcher m2 = P_QUOTED_ATTRIBUTES.matcher(body); - final Matcher m3 = P_UNQUOTED_ATTRIBUTES.matcher(body); - final List paramNames = new ArrayList(); - final List paramValues = new ArrayList(); - while (m2.find()) { - paramNames.add(m2.group(1)); //([a-z0-9]+) - paramValues.add(m2.group(3)); //(.*?) - } - while (m3.find()) { - paramNames.add(m3.group(1)); //([a-z0-9]+) - paramValues.add(m3.group(3)); //([^\"\\s']+) - } + final Matcher m2 = P_QUOTED_ATTRIBUTES.matcher(body); + final Matcher m3 = P_UNQUOTED_ATTRIBUTES.matcher(body); + final List paramNames = new ArrayList(); + final List paramValues = new ArrayList(); + while (m2.find()) { + paramNames.add(m2.group(1)); //([a-z0-9]+) + paramValues.add(m2.group(3)); //(.*?) + } + while (m3.find()) { + paramNames.add(m3.group(1)); //([a-z0-9]+) + paramValues.add(m3.group(3)); //([^\"\\s']+) + } - String paramName, paramValue; - for (int ii = 0; ii < paramNames.size(); ii++) { - paramName = paramNames.get(ii).toLowerCase(); - paramValue = paramValues.get(ii); + String paramName, paramValue; + for (int ii = 0; ii < paramNames.size(); ii++) { + paramName = paramNames.get(ii).toLowerCase(); + paramValue = paramValues.get(ii); // debug( "paramName='" + paramName + "'" ); // debug( "paramValue='" + paramValue + "'" ); // debug( "allowed? " + vAllowed.get( name ).contains( paramName ) ); - if (allowedAttribute(name, paramName)) { - if (inArray(paramName, vProtocolAtts)) { - paramValue = processParamProtocol(paramValue); - } - params += " " + paramName + "=\"" + paramValue + "\""; - } - } + if (allowedAttribute(name, paramName)) { + if (inArray(paramName, vProtocolAtts)) { + paramValue = processParamProtocol(paramValue); + } + params += " " + paramName + "=\"" + paramValue + "\""; + } + } - if (inArray(name, vSelfClosingTags)) { - ending = " /"; - } + if (inArray(name, vSelfClosingTags)) { + ending = " /"; + } - if (inArray(name, vNeedClosingTags)) { - ending = ""; - } + if (inArray(name, vNeedClosingTags)) { + ending = ""; + } - if (ending == null || ending.length() < 1) { - if (vTagCounts.containsKey(name)) { - vTagCounts.put(name, vTagCounts.get(name) + 1); - } else { - vTagCounts.put(name, 1); - } - } else { - ending = " /"; - } - return "<" + name + params + ending + ">"; - } else { - return ""; - } - } + if (ending == null || ending.length() < 1) { + if (vTagCounts.containsKey(name)) { + vTagCounts.put(name, vTagCounts.get(name) + 1); + } else { + vTagCounts.put(name, 1); + } + } else { + ending = " /"; + } + return "<" + name + params + ending + ">"; + } else { + return ""; + } + } - // comments - m = P_COMMENT.matcher(s); - if (!stripComment && m.find()) { - return "<" + m.group() + ">"; - } + // comments + m = P_COMMENT.matcher(s); + if (!stripComment && m.find()) { + return "<" + m.group() + ">"; + } - return ""; - } + return ""; + } - private String processParamProtocol(String s) { - s = decodeEntities(s); - final Matcher m = P_PROTOCOL.matcher(s); - if (m.find()) { - final String protocol = m.group(1); - if (!inArray(protocol, vAllowedProtocols)) { - // bad protocol, turn into local anchor link instead - s = "#" + s.substring(protocol.length() + 1, s.length()); - if (s.startsWith("#//")) { - s = "#" + s.substring(3, s.length()); - } - } - } + private String processParamProtocol(String s) { + s = decodeEntities(s); + final Matcher m = P_PROTOCOL.matcher(s); + if (m.find()) { + final String protocol = m.group(1); + if (!inArray(protocol, vAllowedProtocols)) { + // bad protocol, turn into local anchor link instead + s = "#" + s.substring(protocol.length() + 1, s.length()); + if (s.startsWith("#//")) { + s = "#" + s.substring(3, s.length()); + } + } + } - return s; - } + return s; + } - private String decodeEntities(String s) { - StringBuffer buf = new StringBuffer(); + private String decodeEntities(String s) { + StringBuffer buf = new StringBuffer(); - Matcher m = P_ENTITY.matcher(s); - while (m.find()) { - final String match = m.group(1); - final int decimal = Integer.decode(match).intValue(); - m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal))); - } - m.appendTail(buf); - s = buf.toString(); + Matcher m = P_ENTITY.matcher(s); + while (m.find()) { + final String match = m.group(1); + final int decimal = Integer.decode(match).intValue(); + m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal))); + } + m.appendTail(buf); + s = buf.toString(); - buf = new StringBuffer(); - m = P_ENTITY_UNICODE.matcher(s); - while (m.find()) { - final String match = m.group(1); - final int decimal = Integer.valueOf(match, 16).intValue(); - m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal))); - } - m.appendTail(buf); - s = buf.toString(); + buf = new StringBuffer(); + m = P_ENTITY_UNICODE.matcher(s); + while (m.find()) { + final String match = m.group(1); + final int decimal = Integer.valueOf(match, 16).intValue(); + m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal))); + } + m.appendTail(buf); + s = buf.toString(); - buf = new StringBuffer(); - m = P_ENCODE.matcher(s); - while (m.find()) { - final String match = m.group(1); - final int decimal = Integer.valueOf(match, 16).intValue(); - m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal))); - } - m.appendTail(buf); - s = buf.toString(); + buf = new StringBuffer(); + m = P_ENCODE.matcher(s); + while (m.find()) { + final String match = m.group(1); + final int decimal = Integer.valueOf(match, 16).intValue(); + m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal))); + } + m.appendTail(buf); + s = buf.toString(); - s = validateEntities(s); - return s; - } + s = validateEntities(s); + return s; + } - private String validateEntities(final String s) { - StringBuffer buf = new StringBuffer(); + private String validateEntities(final String s) { + StringBuffer buf = new StringBuffer(); - // validate entities throughout the string - Matcher m = P_VALID_ENTITIES.matcher(s); - while (m.find()) { - final String one = m.group(1); //([^&;]*) - final String two = m.group(2); //(?=(;|&|$)) - m.appendReplacement(buf, Matcher.quoteReplacement(checkEntity(one, two))); - } - m.appendTail(buf); + // validate entities throughout the string + Matcher m = P_VALID_ENTITIES.matcher(s); + while (m.find()) { + final String one = m.group(1); //([^&;]*) + final String two = m.group(2); //(?=(;|&|$)) + m.appendReplacement(buf, Matcher.quoteReplacement(checkEntity(one, two))); + } + m.appendTail(buf); - return encodeQuotes(buf.toString()); - } + return encodeQuotes(buf.toString()); + } - private String encodeQuotes(final String s) { - if (encodeQuotes) { - StringBuffer buf = new StringBuffer(); - Matcher m = P_VALID_QUOTES.matcher(s); - while (m.find()) { - final String one = m.group(1); //(>|^) - final String two = m.group(2); //([^<]+?) - final String three = m.group(3); //(<|$) - m.appendReplacement(buf, Matcher.quoteReplacement(one + regexReplace(P_QUOTE, """, two) + three)); - } - m.appendTail(buf); - return buf.toString(); - } else { - return s; - } - } + private String encodeQuotes(final String s) { + if (encodeQuotes) { + StringBuffer buf = new StringBuffer(); + Matcher m = P_VALID_QUOTES.matcher(s); + while (m.find()) { + final String one = m.group(1); //(>|^) + final String two = m.group(2); //([^<]+?) + final String three = m.group(3); //(<|$) + m.appendReplacement(buf, Matcher.quoteReplacement(one + regexReplace(P_QUOTE, """, two) + three)); + } + m.appendTail(buf); + return buf.toString(); + } else { + return s; + } + } - private String checkEntity(final String preamble, final String term) { + private String checkEntity(final String preamble, final String term) { - return ";".equals(term) && isValidEntity(preamble) - ? '&' + preamble - : "&" + preamble; - } + return ";".equals(term) && isValidEntity(preamble) + ? '&' + preamble + : "&" + preamble; + } - private boolean isValidEntity(final String entity) { - return inArray(entity, vAllowedEntities); - } + private boolean isValidEntity(final String entity) { + return inArray(entity, vAllowedEntities); + } - private static boolean inArray(final String s, final String[] array) { - for (String item : array) { - if (item != null && item.equals(s)) { - return true; - } - } - return false; - } + private static boolean inArray(final String s, final String[] array) { + for (String item : array) { + if (item != null && item.equals(s)) { + return true; + } + } + return false; + } - private boolean allowed(final String name) { - return (vAllowed.isEmpty() || vAllowed.containsKey(name)) && !inArray(name, vDisallowed); - } + private boolean allowed(final String name) { + return (vAllowed.isEmpty() || vAllowed.containsKey(name)) && !inArray(name, vDisallowed); + } - private boolean allowedAttribute(final String name, final String paramName) { - return allowed(name) && (vAllowed.isEmpty() || vAllowed.get(name).contains(paramName)); - } -} \ No newline at end of file + private boolean allowedAttribute(final String name, final String paramName) { + return allowed(name) && (vAllowed.isEmpty() || vAllowed.get(name).contains(paramName)); + } +} diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/support/xss/SqlFilter.java b/blade-core-tool/src/main/java/org/springblade/core/tool/support/xss/SqlFilter.java new file mode 100644 index 0000000..d18cbcb --- /dev/null +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/support/xss/SqlFilter.java @@ -0,0 +1,58 @@ +/** + * Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com). + *

+ * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE; + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springblade.core.tool.support.xss; + + +import org.springblade.core.tool.utils.StringUtil; + +/** + * SQL过滤 + * + * @author smallchill + */ +public class SqlFilter { + + /** + * SQL注入过滤 + * + * @param str 待验证的字符串 + */ + public static String sqlInject(String str) { + if (StringUtil.isBlank(str)) { + return null; + } + //去掉'|"|;|\字符 + str = str.replace("'", ""); + str = str.replace("\"", ""); + str = str.replace(";", ""); + str = str.replace("\\", ""); + + //转换成小写 + str = str.toLowerCase(); + + //非法字符 + String[] keywords = {"master", "truncate", "insert", "select", "delete", "update", "declare", "alert", "drop"}; + + //判断是否包含非法字符 + for (String keyword : keywords) { + if (str.indexOf(keyword) != -1) { + throw new RuntimeException("包含非法字符"); + } + } + + return str; + } +} diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/support/xss/XssFilter.java b/blade-core-tool/src/main/java/org/springblade/core/tool/support/xss/XssFilter.java index bb86a80..90d3dd9 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/support/xss/XssFilter.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/support/xss/XssFilter.java @@ -21,29 +21,32 @@ import java.io.IOException; /** * XSS过滤 + * + * @author smallchill */ public class XssFilter implements Filter { - @Override - public void init(FilterConfig config) throws ServletException { + @Override + public void init(FilterConfig config) throws ServletException { - } + } - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - ServletRequest requestWrapper = null; - if(request instanceof HttpServletRequest) { - requestWrapper = new XssHttpServletRequestWrapper((HttpServletRequest) request); - } - if(requestWrapper == null) { - chain.doFilter(request, response); - } else { - chain.doFilter(requestWrapper, response); - } - } + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + ServletRequest requestWrapper = null; + if (request instanceof HttpServletRequest) { + requestWrapper = new XssHttpServletRequestWrapper((HttpServletRequest) request); + } + if (requestWrapper == null) { + chain.doFilter(request, response); + } else { + chain.doFilter(requestWrapper, response); + } + } - @Override - public void destroy() { + @Override + public void destroy() { - } + } } diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/support/xss/XssHttpServletRequestWrapper.java b/blade-core-tool/src/main/java/org/springblade/core/tool/support/xss/XssHttpServletRequestWrapper.java index 184305d..8c25155 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/support/xss/XssHttpServletRequestWrapper.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/support/xss/XssHttpServletRequestWrapper.java @@ -34,141 +34,151 @@ import java.util.Map; /** * XSS过滤处理 + * + * @author smallchill */ public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper { - //没被包装过的HttpServletRequest(特殊场景,需要自己过滤) - HttpServletRequest orgRequest; - //html过滤 - private final static HTMLFilter htmlFilter = new HTMLFilter(); - // 缓存报文,支持多次读取流 - private final byte[] body; + /** + * 没被包装过的HttpServletRequest(特殊场景,需要自己过滤) + */ + HttpServletRequest orgRequest; - public XssHttpServletRequestWrapper(HttpServletRequest request) throws IOException { - super(request); - orgRequest = request; - body = WebUtil.getRequestBytes(request); - } + /** + * html过滤 + */ + private final static HTMLFilter htmlFilter = new HTMLFilter(); - @Override - public BufferedReader getReader() throws IOException { - return new BufferedReader(new InputStreamReader(getInputStream())); - } + /** + * 缓存报文,支持多次读取流 + */ + private final byte[] body; - @Override - public ServletInputStream getInputStream() throws IOException { + public XssHttpServletRequestWrapper(HttpServletRequest request) throws IOException { + super(request); + orgRequest = request; + body = WebUtil.getRequestBytes(request); + } - //为空,直接返回 - if (null == super.getHeader(HttpHeaders.CONTENT_TYPE)) { - return super.getInputStream(); - } + @Override + public BufferedReader getReader() throws IOException { + return new BufferedReader(new InputStreamReader(getInputStream())); + } - //非json类型,直接返回 - if (!super.getHeader(HttpHeaders.CONTENT_TYPE).equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE) - && !super.getHeader(HttpHeaders.CONTENT_TYPE).equalsIgnoreCase(MediaType.APPLICATION_JSON_UTF8_VALUE)) { - return super.getInputStream(); - } + @Override + public ServletInputStream getInputStream() throws IOException { - //为空,直接返回 - String requestStr = WebUtil.getRequestStr(orgRequest, body); - if (StringUtil.isBlank(requestStr)) { - return super.getInputStream(); - } + //为空,直接返回 + if (null == super.getHeader(HttpHeaders.CONTENT_TYPE)) { + return super.getInputStream(); + } - requestStr = xssEncode(requestStr); + //非json类型,直接返回 + if (!super.getHeader(HttpHeaders.CONTENT_TYPE).equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE) + && !super.getHeader(HttpHeaders.CONTENT_TYPE).equalsIgnoreCase(MediaType.APPLICATION_JSON_UTF8_VALUE)) { + return super.getInputStream(); + } - final ByteArrayInputStream bis = new ByteArrayInputStream(requestStr.getBytes(Charsets.UTF_8)); + //为空,直接返回 + String requestStr = WebUtil.getRequestStr(orgRequest, body); + if (StringUtil.isBlank(requestStr)) { + return super.getInputStream(); + } - return new ServletInputStream() { + requestStr = xssEncode(requestStr); - @Override - public boolean isFinished() { - return true; - } + final ByteArrayInputStream bis = new ByteArrayInputStream(requestStr.getBytes(Charsets.UTF_8)); - @Override - public boolean isReady() { - return true; - } + return new ServletInputStream() { - @Override - public void setReadListener(ReadListener readListener) { + @Override + public boolean isFinished() { + return true; + } - } + @Override + public boolean isReady() { + return true; + } - @Override - public int read() throws IOException { - return bis.read(); - } - }; + @Override + public void setReadListener(ReadListener readListener) { - } + } - @Override - public String getParameter(String name) { - String value = super.getParameter(xssEncode(name)); - if (StringUtil.isNotBlank(value)) { - value = xssEncode(value); - } - return value; - } + @Override + public int read() throws IOException { + return bis.read(); + } + }; - @Override - public String[] getParameterValues(String name) { - String[] parameters = super.getParameterValues(name); - if (parameters == null || parameters.length == 0) { - return null; - } + } - for (int i = 0; i < parameters.length; i++) { - parameters[i] = xssEncode(parameters[i]); - } - return parameters; - } + @Override + public String getParameter(String name) { + String value = super.getParameter(xssEncode(name)); + if (StringUtil.isNotBlank(value)) { + value = xssEncode(value); + } + return value; + } - @Override - public Map getParameterMap() { - Map map = new LinkedHashMap<>(); - Map parameters = super.getParameterMap(); - for (String key : parameters.keySet()) { - String[] values = parameters.get(key); - for (int i = 0; i < values.length; i++) { - values[i] = xssEncode(values[i]); - } - map.put(key, values); - } - return map; - } + @Override + public String[] getParameterValues(String name) { + String[] parameters = super.getParameterValues(name); + if (parameters == null || parameters.length == 0) { + return null; + } - @Override - public String getHeader(String name) { - String value = super.getHeader(xssEncode(name)); - if (StringUtil.isNotBlank(value)) { - value = xssEncode(value); - } - return value; - } + for (int i = 0; i < parameters.length; i++) { + parameters[i] = xssEncode(parameters[i]); + } + return parameters; + } - private String xssEncode(String input) { - return htmlFilter.filter(input); - } + @Override + public Map getParameterMap() { + Map map = new LinkedHashMap<>(); + Map parameters = super.getParameterMap(); + for (String key : parameters.keySet()) { + String[] values = parameters.get(key); + for (int i = 0; i < values.length; i++) { + values[i] = xssEncode(values[i]); + } + map.put(key, values); + } + return map; + } - /** - * 获取最原始的request - */ - public HttpServletRequest getOrgRequest() { - return orgRequest; - } + @Override + public String getHeader(String name) { + String value = super.getHeader(xssEncode(name)); + if (StringUtil.isNotBlank(value)) { + value = xssEncode(value); + } + return value; + } - /** - * 获取最原始的request - */ - public static HttpServletRequest getOrgRequest(HttpServletRequest request) { - if (request instanceof XssHttpServletRequestWrapper) { - return ((XssHttpServletRequestWrapper) request).getOrgRequest(); - } + private String xssEncode(String input) { + return htmlFilter.filter(input); + } - return request; - } + /** + * 获取最原始的request + */ + public HttpServletRequest getOrgRequest() { + return orgRequest; + } + + /** + * 获取最原始的request + */ + public static HttpServletRequest getOrgRequest(HttpServletRequest request) { + if (request instanceof XssHttpServletRequestWrapper) { + return ((XssHttpServletRequestWrapper) request).getOrgRequest(); + } + + return request; + } } diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/AESUtil.java b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/AESUtil.java index 93168c2..478a4aa 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/AESUtil.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/AESUtil.java @@ -30,7 +30,8 @@ import java.util.Arrays; */ public class AESUtil { - private AESUtil() {} + private AESUtil() { + } public static String genAesKey() { return StringUtil.random(32); diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/Charsets.java b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/Charsets.java index 16603d2..9fd165b 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/Charsets.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/Charsets.java @@ -21,6 +21,8 @@ import java.nio.charset.UnsupportedCharsetException; /** * 字符集工具类 + * + * @author L.cm */ public class Charsets { @@ -34,17 +36,18 @@ public class Charsets { public static final java.nio.charset.Charset GBK = java.nio.charset.Charset.forName(StringPool.GBK); /** * 字符集utf-8 - */ + */ public static final java.nio.charset.Charset UTF_8 = StandardCharsets.UTF_8; - /** - * 转换为Charset对象 - * @param charsetName 字符集,为空则返回默认字符集 - * @return Charsets - * @throws UnsupportedCharsetException 编码不支持 - */ - public static java.nio.charset.Charset charset(String charsetName) throws UnsupportedCharsetException { - return StringUtil.isBlank(charsetName) ? java.nio.charset.Charset.defaultCharset() : java.nio.charset.Charset.forName(charsetName); - } + /** + * 转换为Charset对象 + * + * @param charsetName 字符集,为空则返回默认字符集 + * @return Charsets + * @throws UnsupportedCharsetException 编码不支持 + */ + public static java.nio.charset.Charset charset(String charsetName) throws UnsupportedCharsetException { + return StringUtil.isBlank(charsetName) ? java.nio.charset.Charset.defaultCharset() : java.nio.charset.Charset.forName(charsetName); + } } diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/ClassUtil.java b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/ClassUtil.java index 997af1f..d4d4a50 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/ClassUtil.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/ClassUtil.java @@ -34,71 +34,76 @@ import java.lang.reflect.Method; */ public class ClassUtil extends org.springframework.util.ClassUtils { - private static final ParameterNameDiscoverer PARAMETER_NAME_DISCOVERER = new DefaultParameterNameDiscoverer(); + private static final ParameterNameDiscoverer PARAMETER_NAME_DISCOVERER = new DefaultParameterNameDiscoverer(); - /** - * 获取方法参数信息 - * @param constructor 构造器 - * @param parameterIndex 参数序号 - * @return {MethodParameter} - */ - public static MethodParameter getMethodParameter(Constructor constructor, int parameterIndex) { - MethodParameter methodParameter = new SynthesizingMethodParameter(constructor, parameterIndex); - methodParameter.initParameterNameDiscovery(PARAMETER_NAME_DISCOVERER); - return methodParameter; - } + /** + * 获取方法参数信息 + * + * @param constructor 构造器 + * @param parameterIndex 参数序号 + * @return {MethodParameter} + */ + public static MethodParameter getMethodParameter(Constructor constructor, int parameterIndex) { + MethodParameter methodParameter = new SynthesizingMethodParameter(constructor, parameterIndex); + methodParameter.initParameterNameDiscovery(PARAMETER_NAME_DISCOVERER); + return methodParameter; + } - /** - * 获取方法参数信息 - * @param method 方法 - * @param parameterIndex 参数序号 - * @return {MethodParameter} - */ - public static MethodParameter getMethodParameter(Method method, int parameterIndex) { - MethodParameter methodParameter = new SynthesizingMethodParameter(method, parameterIndex); - methodParameter.initParameterNameDiscovery(PARAMETER_NAME_DISCOVERER); - return methodParameter; - } + /** + * 获取方法参数信息 + * + * @param method 方法 + * @param parameterIndex 参数序号 + * @return {MethodParameter} + */ + public static MethodParameter getMethodParameter(Method method, int parameterIndex) { + MethodParameter methodParameter = new SynthesizingMethodParameter(method, parameterIndex); + methodParameter.initParameterNameDiscovery(PARAMETER_NAME_DISCOVERER); + return methodParameter; + } - /** - * 获取Annotation - * @param method Method - * @param annotationType 注解类 - * @param 泛型标记 - * @return {Annotation} - */ - public static A getAnnotation(Method method, Class annotationType) { - Class targetClass = method.getDeclaringClass(); - // The method may be on an interface, but we need attributes from the target class. - // If the target class is null, the method will be unchanged. - Method specificMethod = ClassUtil.getMostSpecificMethod(method, targetClass); - // If we are dealing with method with generic parameters, find the original method. - specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod); - // 先找方法,再找方法上的类 - A annotation = AnnotatedElementUtils.findMergedAnnotation(specificMethod, annotationType);; - if (null != annotation) { - return annotation; - } - // 获取类上面的Annotation,可能包含组合注解,故采用spring的工具类 - return AnnotatedElementUtils.findMergedAnnotation(specificMethod.getDeclaringClass(), annotationType); - } + /** + * 获取Annotation + * + * @param method Method + * @param annotationType 注解类 + * @param 泛型标记 + * @return {Annotation} + */ + public static A getAnnotation(Method method, Class annotationType) { + Class targetClass = method.getDeclaringClass(); + // The method may be on an interface, but we need attributes from the target class. + // If the target class is null, the method will be unchanged. + Method specificMethod = ClassUtil.getMostSpecificMethod(method, targetClass); + // If we are dealing with method with generic parameters, find the original method. + specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod); + // 先找方法,再找方法上的类 + A annotation = AnnotatedElementUtils.findMergedAnnotation(specificMethod, annotationType); + ; + if (null != annotation) { + return annotation; + } + // 获取类上面的Annotation,可能包含组合注解,故采用spring的工具类 + return AnnotatedElementUtils.findMergedAnnotation(specificMethod.getDeclaringClass(), annotationType); + } - /** - * 获取Annotation - * @param handlerMethod HandlerMethod - * @param annotationType 注解类 - * @param 泛型标记 - * @return {Annotation} - */ - public static A getAnnotation(HandlerMethod handlerMethod, Class annotationType) { - // 先找方法,再找方法上的类 - A annotation = handlerMethod.getMethodAnnotation(annotationType); - if (null != annotation) { - return annotation; - } - // 获取类上面的Annotation,可能包含组合注解,故采用spring的工具类 - Class beanType = handlerMethod.getBeanType(); - return AnnotatedElementUtils.findMergedAnnotation(beanType, annotationType); - } + /** + * 获取Annotation + * + * @param handlerMethod HandlerMethod + * @param annotationType 注解类 + * @param 泛型标记 + * @return {Annotation} + */ + public static A getAnnotation(HandlerMethod handlerMethod, Class annotationType) { + // 先找方法,再找方法上的类 + A annotation = handlerMethod.getMethodAnnotation(annotationType); + if (null != annotation) { + return annotation; + } + // 获取类上面的Annotation,可能包含组合注解,故采用spring的工具类 + Class beanType = handlerMethod.getBeanType(); + return AnnotatedElementUtils.findMergedAnnotation(beanType, annotationType); + } } diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/CollectionUtil.java b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/CollectionUtil.java index 0d1dc22..d1a1db3 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/CollectionUtil.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/CollectionUtil.java @@ -31,32 +31,36 @@ public class CollectionUtil extends org.springframework.util.CollectionUtils { /** * Check whether the given Array contains the given element. - * @param array the Array to check + * + * @param array the Array to check * @param element the element to look for - * @param The generic tag + * @param The generic tag * @return {@code true} if found, {@code false} else */ public static boolean contains(@Nullable T[] array, final T element) { - if (array == null) { return false; } + if (array == null) { + return false; + } return Arrays.stream(array).anyMatch(x -> ObjectUtil.nullSafeEquals(x, element)); } - /** - * 对象是否为数组对象 - * - * @param obj 对象 - * @return 是否为数组对象,如果为{@code null} 返回false - */ - public static boolean isArray(Object obj) { - if (null == obj) { - return false; - } - return obj.getClass().isArray(); - } + /** + * 对象是否为数组对象 + * + * @param obj 对象 + * @return 是否为数组对象,如果为{@code null} 返回false + */ + public static boolean isArray(Object obj) { + if (null == obj) { + return false; + } + return obj.getClass().isArray(); + } /** * Determine whether the given Collection is not empty: * i.e. {@code null} or of zero length. + * * @param coll the Collection to check */ public static boolean isNotEmpty(@Nullable Collection coll) { @@ -66,6 +70,7 @@ public class CollectionUtil extends org.springframework.util.CollectionUtils { /** * Determine whether the given Map is not empty: * i.e. {@code null} or of zero length. + * * @param map the Map to check */ public static boolean isNotEmpty(@Nullable Map map) { diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/DateTimeUtil.java b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/DateTimeUtil.java index 83961df..dff685c 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/DateTimeUtil.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/DateTimeUtil.java @@ -31,7 +31,7 @@ import java.time.temporal.TemporalAccessor; public class DateTimeUtil { public static final DateTimeFormatter DATETIME_FORMAT = DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN); public static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN); - public static final DateTimeFormatter TIME_FORMAT = DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN); + public static final DateTimeFormatter TIME_FORMAT = DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN); /** * 日期时间格式化 @@ -67,7 +67,7 @@ public class DateTimeUtil { * 日期格式化 * * @param temporal 时间 - * @param pattern 表达式 + * @param pattern 表达式 * @return 格式化后的时间 */ public static String format(TemporalAccessor temporal, String pattern) { @@ -89,7 +89,7 @@ public class DateTimeUtil { /** * 将字符串转换为时间 * - * @param dateStr 时间字符串 + * @param dateStr 时间字符串 * @param formatter DateTimeFormatter * @return 时间 */ @@ -99,6 +99,7 @@ public class DateTimeUtil { /** * 时间转 Instant + * * @param dateTime 时间 * @return Instant */ @@ -108,6 +109,7 @@ public class DateTimeUtil { /** * Instant 转 时间 + * * @param instant Instant * @return Instant */ diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/DigestUtil.java b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/DigestUtil.java index 38e7110..6012087 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/DigestUtil.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/DigestUtil.java @@ -39,6 +39,7 @@ public class DigestUtil extends org.springframework.util.DigestUtils { /** * Return a hexadecimal string representation of the MD5 digest of the given bytes. + * * @param bytes the bytes to calculate the digest over * @return a hexadecimal digest string */ @@ -48,19 +49,19 @@ public class DigestUtil extends org.springframework.util.DigestUtils { private static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray(); - public static String sha1(String srcStr){ + public static String sha1(String srcStr) { return hash("SHA-1", srcStr); } - public static String sha256(String srcStr){ + public static String sha256(String srcStr) { return hash("SHA-256", srcStr); } - public static String sha384(String srcStr){ + public static String sha384(String srcStr) { return hash("SHA-384", srcStr); } - public static String sha512(String srcStr){ + public static String sha512(String srcStr) { return hash("SHA-512", srcStr); } @@ -76,7 +77,7 @@ public class DigestUtil extends org.springframework.util.DigestUtils { public static String toHex(byte[] bytes) { StringBuilder ret = new StringBuilder(bytes.length * 2); - for (int i=0; i> 4) & 0x0f]); ret.append(HEX_DIGITS[bytes[i] & 0x0f]); } @@ -98,19 +99,20 @@ public class DigestUtil extends org.springframework.util.DigestUtils { return false; } int diff = a.length ^ b.length; - for(int i=0; i the type of the reference + * @param the type of the reference * @return {@code obj} if not {@code null} * @throws NullPointerException if {@code obj} is {@code null} */ @@ -103,10 +103,10 @@ public class Func { * creating the message supplier are less than the cost of just * creating the string message directly. * - * @param obj the object reference to check for nullity + * @param obj the object reference to check for nullity * @param messageSupplier supplier of the detail message to be - * used in the event that a {@code NullPointerException} is thrown - * @param the type of the reference + * used in the event that a {@code NullPointerException} is thrown + * @param the type of the reference * @return {@code obj} if not {@code null} * @throws NullPointerException if {@code obj} is {@code null} * @since 1.8 @@ -118,14 +118,13 @@ public class Func { /** * Returns {@code true} if the provided reference is {@code null} otherwise * returns {@code false}. - * + *

* This method exists to be used as a * {@link java.util.function.Predicate}, {@code filter($::isNull)} * * @param obj a reference to be checked against {@code null} * @return {@code true} if the provided reference is {@code null} otherwise * {@code false} - * * @see java.util.function.Predicate * @since 1.8 */ @@ -136,14 +135,13 @@ public class Func { /** * Returns {@code true} if the provided reference is non-{@code null} * otherwise returns {@code false}. - * + *

* This method exists to be used as a * {@link java.util.function.Predicate}, {@code filter($::notNull)} * * @param obj a reference to be checked against {@code null} * @return {@code true} if the provided reference is non-{@code null} * otherwise {@code false} - * * @see java.util.function.Predicate * @since 1.8 */ @@ -153,6 +151,7 @@ public class Func { /** * 首字母变小写 + * * @param str 字符串 * @return {String} */ @@ -162,6 +161,7 @@ public class Func { /** * 首字母变大写 + * * @param str 字符串 * @return {String} */ @@ -212,6 +212,7 @@ public class Func { /** * 有 任意 一个 Blank + * * @param css CharSequence * @return boolean */ @@ -221,6 +222,7 @@ public class Func { /** * 是否全非 Blank + * * @param css CharSequence * @return boolean */ @@ -231,6 +233,7 @@ public class Func { /** * Determine whether the given object is an array: * either an Object array or a primitive array. + * * @param obj the object to check * @return 是否数组 */ @@ -241,6 +244,7 @@ public class Func { /** * Determine whether the given object is empty: * i.e. {@code null} or of zero length. + * * @param obj the object to check * @return 数组是否为空 */ @@ -251,6 +255,7 @@ public class Func { /** * Determine whether the given object is not empty: * i.e. {@code null} or of zero length. + * * @param obj the object to check * @return 是否不为空 */ @@ -261,14 +266,17 @@ public class Func { /** * Determine whether the given array is empty: * i.e. {@code null} or of zero length. + * * @param array the array to check * @return 数组是否为空 */ public static boolean isEmpty(@Nullable Object[] array) { return ObjectUtil.isEmpty(array); } + /** * 判断数组不为空 + * * @param array 数组 * @return 数组是否不为空 */ @@ -279,8 +287,7 @@ public class Func { /** * 对象组中是否存在 Empty Object * - * @param os - * 对象组 + * @param os 对象组 * @return */ public static boolean hasEmpty(Object... os) { @@ -312,10 +319,8 @@ public class Func { * 相同的条件有两个,满足其一即可:
* 1. obj1 == null && obj2 == null; 2. obj1.equals(obj2) * - * @param obj1 - * 对象1 - * @param obj2 - * 对象2 + * @param obj1 对象1 + * @param obj2 对象2 * @return 是否相等 */ public static boolean equals(Object obj1, Object obj2) { @@ -327,6 +332,7 @@ public class Func { * both are {@code null} or {@code false} if only one is {@code null}. *

Compares arrays with {@code Arrays.equals}, performing an equality * check based on the array elements rather than the array reference. + * * @param o1 first Object to compare * @param o2 second Object to compare * @return whether the given objects are equal @@ -339,9 +345,10 @@ public class Func { /** * Check whether the given Array contains the given element. - * @param array the Array to check + * + * @param array the Array to check * @param element the element to look for - * @param The generic tag + * @param The generic tag * @return {@code true} if found, {@code false} else */ public static boolean contains(@Nullable T[] array, final T element) { @@ -350,8 +357,9 @@ public class Func { /** * Check whether the given Iterator contains the given element. + * * @param iterator the Iterator to check - * @param element the element to look for + * @param element the element to look for * @return {@code true} if found, {@code false} otherwise */ public static boolean contains(@Nullable Iterator iterator, Object element) { @@ -360,8 +368,9 @@ public class Func { /** * Check whether the given Enumeration contains the given element. + * * @param enumeration the Enumeration to check - * @param element the element to look for + * @param element the element to look for * @return {@code true} if found, {@code false} otherwise */ public static boolean contains(@Nullable Enumeration enumeration, Object element) { @@ -394,6 +403,7 @@ public class Func { /** * 判断一个字符串是否是数字 + * * @param cs the CharSequence to check, may be null * @return {boolean} */ @@ -433,7 +443,7 @@ public class Func { * $.toInt("1", 0) = 1 * * - * @param value the string to convert, may be null + * @param value the string to convert, may be null * @param defaultValue the default value * @return the int represented by the string, or the default if conversion fails */ @@ -473,7 +483,7 @@ public class Func { * $.toLong("1", 0L) = 1L * * - * @param value the string to convert, may be null + * @param value the string to convert, may be null * @param defaultValue the default value * @return the long represented by the string, or the default if conversion fails */ @@ -493,7 +503,7 @@ public class Func { * $.toDouble("1", 0) = 1.0 * * - * @param value the string to convert, may be null + * @param value the string to convert, may be null * @return the int represented by the string, or the default if conversion fails */ public static Double toDouble(Object value) { @@ -512,8 +522,8 @@ public class Func { * $.toDouble("1", 0) = 1.0 * * - * @param value the string to convert, may be null - * @param defaultValue the default value + * @param value the string to convert, may be null + * @param defaultValue the default value * @return the int represented by the string, or the default if conversion fails */ public static Double toDouble(Object value, Double defaultValue) { @@ -532,7 +542,7 @@ public class Func { * $.toFloat("1", 0) = 1.00f * * - * @param value the string to convert, may be null + * @param value the string to convert, may be null * @return the int represented by the string, or the default if conversion fails */ public static Float toFloat(Object value) { @@ -551,8 +561,8 @@ public class Func { * $.toFloat("1", 0) = 1.00f * * - * @param value the string to convert, may be null - * @param defaultValue the default value + * @param value the string to convert, may be null + * @param defaultValue the default value * @return the int represented by the string, or the default if conversion fails */ public static Float toFloat(Object value, Float defaultValue) { @@ -571,7 +581,7 @@ public class Func { * $.toBoolean("", false) = false * * - * @param value the string to convert, may be null + * @param value the string to convert, may be null * @return the int represented by the string, or the default if conversion fails */ public static Boolean toBoolean(Object value) { @@ -590,8 +600,8 @@ public class Func { * $.toBoolean("", false) = false * * - * @param value the string to convert, may be null - * @param defaultValue the default value + * @param value the string to convert, may be null + * @param defaultValue the default value * @return the int represented by the string, or the default if conversion fails */ public static Boolean toBoolean(Object value, Boolean defaultValue) { @@ -627,7 +637,7 @@ public class Func { */ public static Integer[] toIntArray(String split, String str) { if (StringUtil.isEmpty(str)) { - return new Integer[] {}; + return new Integer[]{}; } String[] arr = str.split(split); final Integer[] ints = new Integer[arr.length]; @@ -657,13 +667,14 @@ public class Func { */ public static String[] toStrArray(String split, String str) { if (isBlank(str)) { - return new String[]{}; + return new String[]{}; } return str.split(split); } /** * 将 long 转短字符串 为 62 进制 + * * @param num 数字 * @return 短字符串 */ @@ -796,6 +807,7 @@ public class Func { /** * 自定义加密 先MD5再SHA1 + * * @param data * @return */ @@ -805,6 +817,7 @@ public class Func { /** * 编码 + * * @param value 字符串 * @return {String} */ @@ -814,7 +827,8 @@ public class Func { /** * 编码 - * @param value 字符串 + * + * @param value 字符串 * @param charset 字符集 * @return {String} */ @@ -824,6 +838,7 @@ public class Func { /** * 编码URL安全 + * * @param value 字符串 * @return {String} */ @@ -833,7 +848,8 @@ public class Func { /** * 编码URL安全 - * @param value 字符串 + * + * @param value 字符串 * @param charset 字符集 * @return {String} */ @@ -843,6 +859,7 @@ public class Func { /** * 解码 + * * @param value 字符串 * @return {String} */ @@ -852,7 +869,8 @@ public class Func { /** * 解码 - * @param value 字符串 + * + * @param value 字符串 * @param charset 字符集 * @return {String} */ @@ -862,6 +880,7 @@ public class Func { /** * 解码URL安全 + * * @param value 字符串 * @return {String} */ @@ -871,7 +890,8 @@ public class Func { /** * 解码URL安全 - * @param value 字符串 + * + * @param value 字符串 * @param charset 字符集 * @return {String} */ @@ -978,9 +998,9 @@ public class Func { /** * 将json byte 数组反序列化成对象 * - * @param bytes json bytes - * @param valueType class - * @param T 泛型标记 + * @param bytes json bytes + * @param valueType class + * @param T 泛型标记 * @return Bean */ public static T parse(byte[] bytes, Class valueType) { @@ -1002,9 +1022,9 @@ public class Func { /** * 将json反序列化成对象 * - * @param in InputStream - * @param valueType class - * @param T 泛型标记 + * @param in InputStream + * @param valueType class + * @param T 泛型标记 * @return Bean */ public static T parse(InputStream in, Class valueType) { @@ -1014,9 +1034,9 @@ public class Func { /** * 将json反序列化成对象 * - * @param bytes bytes + * @param bytes bytes * @param typeReference 泛型类型 - * @param T 泛型标记 + * @param T 泛型标记 * @return Bean */ public static T parse(byte[] bytes, TypeReference typeReference) { @@ -1026,9 +1046,9 @@ public class Func { /** * 将json反序列化成对象 * - * @param jsonString jsonString + * @param jsonString jsonString * @param typeReference 泛型类型 - * @param T 泛型标记 + * @param T 泛型标记 * @return Bean */ public static T parse(String jsonString, TypeReference typeReference) { @@ -1038,9 +1058,9 @@ public class Func { /** * 将json反序列化成对象 * - * @param in InputStream + * @param in InputStream * @param typeReference 泛型类型 - * @param T 泛型标记 + * @param T 泛型标记 * @return Bean */ public static T parse(InputStream in, TypeReference typeReference) { @@ -1053,6 +1073,7 @@ public class Func { * RFC 3986. * This is useful to ensure that the given String will be preserved as-is * and will not have any o impact on the structure or meaning of the URI. + * * @param source the String to be encoded * @return the encoded String */ @@ -1066,7 +1087,8 @@ public class Func { * RFC 3986. * This is useful to ensure that the given String will be preserved as-is * and will not have any o impact on the structure or meaning of the URI. - * @param source the String to be encoded + * + * @param source the String to be encoded * @param charset the character encoding to encode to * @return the encoded String */ @@ -1077,6 +1099,7 @@ public class Func { /** * Decode the given encoded URI component. *

See {@link StringUtils#uriDecode(String, Charset)} for the decoding rules. + * * @param source the encoded String * @return the decoded value * @throws IllegalArgumentException when the given source contains invalid encoded sequences @@ -1090,7 +1113,8 @@ public class Func { /** * Decode the given encoded URI component. *

See {@link StringUtils#uriDecode(String, Charset)} for the decoding rules. - * @param source the encoded String + * + * @param source the encoded String * @param charset the character encoding to use * @return the decoded value * @throws IllegalArgumentException when the given source contains invalid encoded sequences @@ -1104,7 +1128,7 @@ public class Func { /** * 日期时间格式化 * - * @param date 时间 + * @param date 时间 * @return 格式化后的时间 */ public static String formatDateTime(Date date) { @@ -1114,7 +1138,7 @@ public class Func { /** * 日期格式化 * - * @param date 时间 + * @param date 时间 * @return 格式化后的时间 */ public static String formatDate(Date date) { @@ -1124,7 +1148,7 @@ public class Func { /** * 时间格式化 * - * @param date 时间 + * @param date 时间 * @return 格式化后的时间 */ public static String formatTime(Date date) { @@ -1157,7 +1181,7 @@ public class Func { * 将字符串转换为时间 * * @param dateStr 时间字符串 - * @param format ConcurrentDateFormat + * @param format ConcurrentDateFormat * @return 时间 */ public static Date parse(String dateStr, ConcurrentDateFormat format) { @@ -1198,7 +1222,7 @@ public class Func { * 日期格式化 * * @param temporal 时间 - * @param pattern 表达式 + * @param pattern 表达式 * @return 格式化后的时间 */ public static String format(TemporalAccessor temporal, String pattern) { @@ -1219,7 +1243,7 @@ public class Func { /** * 将字符串转换为时间 * - * @param dateStr 时间字符串 + * @param dateStr 时间字符串 * @param formatter DateTimeFormatter * @return 时间 */ @@ -1230,8 +1254,8 @@ public class Func { /** * 时间比较 * - * @param startInclusive the start instant, inclusive, not null - * @param endExclusive the end instant, exclusive, not null + * @param startInclusive the start instant, inclusive, not null + * @param endExclusive the end instant, exclusive, not null * @return a {@code Duration}, not null */ public static Duration between(Temporal startInclusive, Temporal endExclusive) { @@ -1240,7 +1264,8 @@ public class Func { /** * 获取方法参数信息 - * @param constructor 构造器 + * + * @param constructor 构造器 * @param parameterIndex 参数序号 * @return {MethodParameter} */ @@ -1250,7 +1275,8 @@ public class Func { /** * 获取方法参数信息 - * @param method 方法 + * + * @param method 方法 * @param parameterIndex 参数序号 * @return {MethodParameter} */ @@ -1260,9 +1286,10 @@ public class Func { /** * 获取Annotation + * * @param annotatedElement AnnotatedElement - * @param annotationType 注解类 - * @param 泛型标记 + * @param annotationType 注解类 + * @param 泛型标记 * @return {Annotation} */ @Nullable @@ -1272,9 +1299,10 @@ public class Func { /** * 获取Annotation - * @param method Method + * + * @param method Method * @param annotationType 注解类 - * @param 泛型标记 + * @param 泛型标记 * @return {Annotation} */ @Nullable @@ -1284,9 +1312,10 @@ public class Func { /** * 获取Annotation - * @param handlerMethod HandlerMethod + * + * @param handlerMethod HandlerMethod * @param annotationType 注解类 - * @param 泛型标记 + * @param 泛型标记 * @return {Annotation} */ @Nullable @@ -1296,8 +1325,9 @@ public class Func { /** * 实例化对象 + * * @param clazz 类 - * @param 泛型标记 + * @param 泛型标记 * @return 对象 */ @SuppressWarnings("unchecked") @@ -1307,8 +1337,9 @@ public class Func { /** * 实例化对象 + * * @param clazzStr 类名 - * @param 泛型标记 + * @param 泛型标记 * @return 对象 */ public static T newInstance(String clazzStr) { @@ -1317,7 +1348,8 @@ public class Func { /** * 获取Bean的属性 - * @param bean bean + * + * @param bean bean * @param propertyName 属性名 * @return 属性值 */ @@ -1327,9 +1359,10 @@ public class Func { /** * 设置Bean属性 - * @param bean bean + * + * @param bean bean * @param propertyName 属性名 - * @param value 属性值 + * @param value 属性值 */ public static void setProperty(Object bean, String propertyName, Object value) { BeanUtil.setProperty(bean, propertyName, value); @@ -1337,11 +1370,11 @@ public class Func { /** * 深复制 - * + *

* 注意:不支持链式Bean * * @param source 源对象 - * @param 泛型标记 + * @param 泛型标记 * @return T */ public static T clone(T source) { @@ -1350,12 +1383,12 @@ public class Func { /** * copy 对象属性到另一个对象,默认不使用Convert - * + *

* 注意:不支持链式Bean,链式用 copyProperties * * @param source 源对象 - * @param clazz 类名 - * @param 泛型标记 + * @param clazz 类名 + * @param 泛型标记 * @return T */ public static T copy(Object source, Class clazz) { @@ -1364,10 +1397,10 @@ public class Func { /** * 拷贝对象 - * + *

* 注意:不支持链式Bean,链式用 copyProperties * - * @param source 源对象 + * @param source 源对象 * @param targetBean 需要赋值的对象 */ public static void copy(Object source, Object targetBean) { @@ -1380,11 +1413,12 @@ public class Func { * from each other, as long as the properties match. Any bean properties that the * source bean exposes but the target bean does not will silently be ignored. *

This is just a convenience method. For more complex transfer needs, + * * @param source the source bean - * @param clazz the target bean class - * @param 泛型标记 - * @throws BeansException if the copying failed + * @param clazz the target bean class + * @param 泛型标记 * @return T + * @throws BeansException if the copying failed */ public static T copyProperties(Object source, Class clazz) throws BeansException { return BeanUtil.copyProperties(source, clazz); @@ -1392,17 +1426,20 @@ public class Func { /** * 将对象装成map形式 + * * @param bean 源对象 * @return {Map} */ public static Map toMap(Object bean) { return BeanUtil.toMap(bean); } + /** * 将map 转为 bean - * @param beanMap map + * + * @param beanMap map * @param valueType 对象类型 - * @param 泛型标记 + * @param 泛型标记 * @return {T} */ public static T toBean(Map beanMap, Class valueType) { diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/IOUtil.java b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/IOUtil.java index 84be0f0..b4047ad 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/IOUtil.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/IOUtil.java @@ -90,7 +90,7 @@ public class IOUtil extends org.springframework.util.StreamUtils { * @param data the String to write, null ignored * @param output the OutputStream to write to * @param encoding the encoding to use, null means platform default - * @throws IOException if an I/O error occurs + * @throws IOException if an I/O error occurs */ public static void write(@Nullable final String data, final OutputStream output, final java.nio.charset.Charset encoding) throws IOException { if (data != null) { diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/ImageUtil.java b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/ImageUtil.java index e5cb753..0066291 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/ImageUtil.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/ImageUtil.java @@ -21,15 +21,18 @@ public final class ImageUtil { */ private static Logger LOGGER = LoggerFactory.getLogger(ImageUtil.class); - /** 默认输出图片类型 */ + /** + * 默认输出图片类型 + */ public static final String DEFAULT_IMG_TYPE = "JPEG"; private ImageUtil() { - + } - + /** * 转换输入流到byte + * * @param src * @return * @throws IOException @@ -39,9 +42,10 @@ public final class ImageUtil { ImageIO.write(src, defaultString(type, DEFAULT_IMG_TYPE), os); return os.toByteArray(); } - + /** * 获取图像内容 + * * @param srcImageFile 文件路径 * @return */ @@ -49,12 +53,14 @@ public final class ImageUtil { try { return ImageIO.read(new File(srcImageFile)); } catch (IOException e) { - LOGGER.error("Error readImage",e); + LOGGER.error("Error readImage", e); } return null; } + /** * 获取图像内容 + * * @param srcImageFile 文件 * @return */ @@ -62,12 +68,14 @@ public final class ImageUtil { try { return ImageIO.read(srcImageFile); } catch (IOException e) { - LOGGER.error("Error readImage",e); + LOGGER.error("Error readImage", e); } return null; } + /** * 获取图像内容 + * * @param srcInputStream 输入流 * @return */ @@ -75,12 +83,14 @@ public final class ImageUtil { try { return ImageIO.read(srcInputStream); } catch (IOException e) { - LOGGER.error("Error readImage",e); + LOGGER.error("Error readImage", e); } return null; } + /** * 获取图像内容 + * * @param url URL地址 * @return */ @@ -88,341 +98,357 @@ public final class ImageUtil { try { return ImageIO.read(url); } catch (IOException e) { - LOGGER.error("Error readImage",e); + LOGGER.error("Error readImage", e); } return null; } - - + + /** - * 缩放图像(按比例缩放) - * @param src 源图像 - * @param output 输出流 - * @param scale 缩放比例 - * @param flag 缩放选择:true 放大; false 缩小; - */ - public final static void zoomScale(BufferedImage src, OutputStream output, String type, double scale, boolean flag) { - try { - // 得到源图宽 - int width = src.getWidth(); - // 得到源图长 - int height = src.getHeight(); - if (flag) { - // 放大 - width = Long.valueOf(Math.round(width * scale)).intValue(); - height = Long.valueOf(Math.round(height * scale)).intValue(); - } else { - // 缩小 - width = Long.valueOf(Math.round(width / scale)).intValue(); - height = Long.valueOf(Math.round(height / scale)).intValue(); - } - Image image = src.getScaledInstance(width, height, Image.SCALE_DEFAULT); - BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); - Graphics g = tag.getGraphics(); - // 绘制缩小后的图 - g.drawImage(image, 0, 0, null); - g.dispose(); - // 输出为文件 - ImageIO.write(tag, defaultString(type, DEFAULT_IMG_TYPE), output); - // 关闭流 - output.close(); - } catch (IOException e) { - LOGGER.error("Error in zoom image", e); - } - } - /** - * 缩放图像(按高度和宽度缩放) - * @param src 源图像 - * @param output 输出流 - * @param height 缩放后的高度 - * @param width 缩放后的宽度 - * @param bb 比例不对时是否需要补白:true为补白; false为不补白; - * @param fillColor 填充色,null时为Color.WHITE - */ - public final static void zoomFixed(BufferedImage src, OutputStream output, String type, int height, int width, boolean bb, Color fillColor) { - try { - double ratio = 0.0; // 缩放比例 - Image itemp = src.getScaledInstance(width, height, BufferedImage.SCALE_SMOOTH); - // 计算比例 - if (src.getHeight() > src.getWidth()) { - ratio = Integer.valueOf(height).doubleValue() / src.getHeight(); - } else { - ratio = Integer.valueOf(width).doubleValue() / src.getWidth(); - } - AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null); - itemp = op.filter(src, null); - - if (bb) { - //补白 - BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); - Graphics2D g = image.createGraphics(); - Color fill = fillColor == null ? Color.white:fillColor ; - g.setColor(fill); - g.fillRect(0, 0, width, height); - if (width == itemp.getWidth(null)) { - g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2, itemp.getWidth(null), itemp.getHeight(null), fill, null); - } else { - g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0, itemp.getWidth(null), itemp.getHeight(null), fill, null); - } - g.dispose(); - itemp = image; - } - // 输出为文件 - ImageIO.write((BufferedImage) itemp, defaultString(type, DEFAULT_IMG_TYPE), output); - // 关闭流 - output.close(); - } catch (IOException e) { - LOGGER.error("Error in zoom image", e); - } - } - - /** - * 图像裁剪(按指定起点坐标和宽高切割) - * @param src 源图像 - * @param output 切片后的图像地址 - * @param x 目标切片起点坐标X - * @param y 目标切片起点坐标Y - * @param width 目标切片宽度 - * @param height 目标切片高度 - */ - public final static void crop(BufferedImage src, OutputStream output, String type, int x, int y, int width, int height) { - try { - // 源图宽度 - int srcWidth = src.getHeight(); - // 源图高度 - int srcHeight = src.getWidth(); - if (srcWidth > 0 && srcHeight > 0) { - Image image = src.getScaledInstance(srcWidth, srcHeight, Image.SCALE_DEFAULT); - // 四个参数分别为图像起点坐标和宽高 - ImageFilter cropFilter = new CropImageFilter(x, y, width, height); - Image img = Toolkit.getDefaultToolkit().createImage( new FilteredImageSource(image.getSource(), cropFilter)); - BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); - Graphics g = tag.getGraphics(); - g.drawImage(img, 0, 0, width, height, null); // 绘制切割后的图 - g.dispose(); - // 输出为文件 - ImageIO.write(tag, defaultString(type, DEFAULT_IMG_TYPE), output); - // 关闭流 - output.close(); - } - } catch (Exception e) { - LOGGER.error("Error in cut image", e); - } - } - - /** - * 图像切割(指定切片的行数和列数) - * @param src 源图像地址 - * @param mos 切片目标文件夹 - * @param prows 目标切片行数。默认2,必须是范围 [1, 20] 之内 - * @param pcols 目标切片列数。默认2,必须是范围 [1, 20] 之内 - */ - public final static void sliceWithNumber(BufferedImage src, IMultiOutputStream mos, String type, int prows, int pcols) { - try { - int rows = prows<=0|| prows>20 ? 2: prows; - int cols = pcols<=0|| pcols>20 ? 2: pcols; - // 源图宽度 - int srcWidth = src.getHeight(); - // 源图高度 - int srcHeight = src.getWidth(); - if (srcWidth > 0 && srcHeight > 0) { - Image img; - ImageFilter cropFilter; - Image image = src.getScaledInstance(srcWidth, srcHeight, Image.SCALE_DEFAULT); - // 每张切片的宽度 - int destWidth = (srcWidth%cols==0)?(srcWidth/cols):(srcWidth/cols + 1); - // 每张切片的高度 - int destHeight = (srcHeight%rows==0)?(srcHeight/rows):(srcHeight/rows+1); - // 循环建立切片 - // 改进的想法:是否可用多线程加快切割速度 - for (int i = 0; i < rows; i++) { - for (int j = 0; j < cols; j++) { - // 四个参数分别为图像起点坐标和宽高 - cropFilter = new CropImageFilter(j * destWidth, i * destHeight, destWidth, destHeight); - img = Toolkit.getDefaultToolkit().createImage( new FilteredImageSource(image.getSource(), cropFilter)); - BufferedImage tag = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB); - Graphics g = tag.getGraphics(); - // 绘制缩小后的图 - g.drawImage(img, 0, 0, null); - g.dispose(); - // 输出为文件 - ImageIO.write(tag, defaultString(type, DEFAULT_IMG_TYPE), mos.buildOutputStream(i,j) ); - } - } - } - } catch (Exception e) { - LOGGER.error("Error in slice image", e); - } - } - /** - * 图像切割(指定切片的宽度和高度) - * @param src 源图像地址 - * @param mos 切片目标文件夹 - * @param pdestWidth 目标切片宽度。默认200 - * @param pdestHeight 目标切片高度。默认150 - */ - public final static void sliceWithSize(BufferedImage src, IMultiOutputStream mos, String type, int pdestWidth, int pdestHeight) { - try { - int destWidth = pdestWidth<= 0 ? 200 : pdestWidth; - int destHeight = pdestHeight <= 0 ? 150 : pdestHeight; - // 源图宽度 - int srcWidth = src.getHeight(); - // 源图高度 - int srcHeight = src.getWidth(); - if (srcWidth > destWidth && srcHeight > destHeight) { - Image img; - ImageFilter cropFilter; - Image image = src.getScaledInstance(srcWidth, srcHeight, Image.SCALE_DEFAULT); - // 切片横向数量 - int cols = (srcWidth % destWidth == 0)?(srcWidth/destWidth):(srcWidth/destWidth + 1); - // 切片纵向数量 - int rows = (srcHeight % destHeight == 0)?(srcHeight/destHeight):(srcHeight/destHeight+1); - // 循环建立切片 - // 改进的想法:是否可用多线程加快切割速度 - for (int i = 0; i < rows; i++) { - for (int j = 0; j < cols; j++) { - // 四个参数分别为图像起点坐标和宽高 - cropFilter = new CropImageFilter(j * destWidth, i * destHeight, destWidth, destHeight); - img = Toolkit.getDefaultToolkit().createImage( new FilteredImageSource(image.getSource(), cropFilter)); - BufferedImage tag = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB); - Graphics g = tag.getGraphics(); - // 绘制缩小后的图 - g.drawImage(img, 0, 0, null); - g.dispose(); - // 输出为文件 - ImageIO.write(tag, defaultString(type, DEFAULT_IMG_TYPE), mos.buildOutputStream(i,j)); - } - } - } - } catch (Exception e) { - LOGGER.error("Error in slice image", e); - } - } - /** - * 图像类型转换:GIF->JPG、GIF->PNG、PNG->JPG、PNG->GIF(X)、BMP->PNG - * @param src 源图像地址 - * @param formatName 包含格式非正式名称的 String:如JPG、JPEG、GIF等 - * @param output 目标图像地址 - */ - public final static void convert(BufferedImage src, OutputStream output, String formatName) { - try { - // 输出为文件 - ImageIO.write(src, formatName, output); - // 关闭流 - output.close(); - } catch (Exception e) { - LOGGER.error("Error in convert image", e); - } - } - /** - * 彩色转为黑白 - * @param src 源图像地址 - * @param output 目标图像地址 - */ - public final static void gray(BufferedImage src, OutputStream output, String type) { - try { - ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY); - ColorConvertOp op = new ColorConvertOp(cs, null); - src = op.filter(src, null); - // 输出为文件 - ImageIO.write(src, defaultString(type, DEFAULT_IMG_TYPE), output); - // 关闭流 - output.close(); - } catch (IOException e) { - LOGGER.error("Error in gray image", e); - } - } - /** - * 给图片添加文字水印 - * @param src 源图像 - * @param output 输出流 - * @param text 水印文字 - * @param font 水印的字体 - * @param color 水印的字体颜色 - * @param position 水印位置 {@link ImagePosition} - * @param x 修正值 - * @param y 修正值 - * @param alpha 透明度:alpha 必须是范围 [0.0, 1.0] 之内(包含边界值)的一个浮点数字 - */ - public final static void textStamp(BufferedImage src, OutputStream output, String type, String text, Font font, Color color - , int position, int x, int y, float alpha) { - try { - int width = src.getWidth(null); - int height = src.getHeight(null); - BufferedImage image = new BufferedImage(width, height, - BufferedImage.TYPE_INT_RGB); - Graphics2D g = image.createGraphics(); - g.drawImage(src, 0, 0, width, height, null); - g.setColor(color); - g.setFont(font); - g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha)); - // 在指定坐标绘制水印文字 - ImagePosition boxPos = new ImagePosition(width, height, calcTextWidth(text) * font.getSize(), font.getSize(), position); - g.drawString(text, boxPos.getX(x), boxPos.getY(y)); - g.dispose(); - // 输出为文件 - ImageIO.write((BufferedImage) image, defaultString(type, DEFAULT_IMG_TYPE), output); - // 关闭流 - output.close(); - } catch (Exception e) { - LOGGER.error("Error in textStamp image", e); - } - } - - /** - * 给图片添加图片水印 - * @param src 源图像 - * @param output 输出流 - * @param stamp 水印图片 - * @param position 水印位置 {@link ImagePosition} - * @param x 修正值 - * @param y 修正值 - * @param alpha 透明度:alpha 必须是范围 [0.0, 1.0] 之内(包含边界值)的一个浮点数字 - */ - public final static void imageStamp(BufferedImage src, OutputStream output, String type, BufferedImage stamp - ,int position, int x, int y, float alpha) { - try { - int width = src.getWidth(); - int height = src.getHeight(); - BufferedImage image = new BufferedImage(width, height, - BufferedImage.TYPE_INT_RGB); - Graphics2D g = image.createGraphics(); - g.drawImage(src, 0, 0, width, height, null); - // 水印文件 - int stampWidth = stamp.getWidth(); - int stampHeight = stamp.getHeight(); - g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha)); - ImagePosition boxPos = new ImagePosition(width, height, stampWidth, stampHeight, position); - g.drawImage(stamp, boxPos.getX(x), boxPos.getY(y), stampWidth, stampHeight, null); - // 水印文件结束 - g.dispose(); - // 输出为文件 - ImageIO.write((BufferedImage) image, defaultString(type, DEFAULT_IMG_TYPE), output); - // 关闭流 - output.close(); - } catch (Exception e) { - LOGGER.error("Error imageStamp",e); - } - } - /** - * 计算text的长度(一个中文算两个字符) - * @param text - * @return - */ - public final static int calcTextWidth(String text) { - int length = 0; - for (int i = 0; i < text.length(); i++) { - if (new String(text.charAt(i) + "").getBytes().length > 1) { - length += 2; - } else { - length += 1; - } - } - return length / 2; - } - - public static String defaultString(String str, String defaultStr) { + * 缩放图像(按比例缩放) + * + * @param src 源图像 + * @param output 输出流 + * @param scale 缩放比例 + * @param flag 缩放选择:true 放大; false 缩小; + */ + public final static void zoomScale(BufferedImage src, OutputStream output, String type, double scale, boolean flag) { + try { + // 得到源图宽 + int width = src.getWidth(); + // 得到源图长 + int height = src.getHeight(); + if (flag) { + // 放大 + width = Long.valueOf(Math.round(width * scale)).intValue(); + height = Long.valueOf(Math.round(height * scale)).intValue(); + } else { + // 缩小 + width = Long.valueOf(Math.round(width / scale)).intValue(); + height = Long.valueOf(Math.round(height / scale)).intValue(); + } + Image image = src.getScaledInstance(width, height, Image.SCALE_DEFAULT); + BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + Graphics g = tag.getGraphics(); + // 绘制缩小后的图 + g.drawImage(image, 0, 0, null); + g.dispose(); + // 输出为文件 + ImageIO.write(tag, defaultString(type, DEFAULT_IMG_TYPE), output); + // 关闭流 + output.close(); + } catch (IOException e) { + LOGGER.error("Error in zoom image", e); + } + } + + /** + * 缩放图像(按高度和宽度缩放) + * + * @param src 源图像 + * @param output 输出流 + * @param height 缩放后的高度 + * @param width 缩放后的宽度 + * @param bb 比例不对时是否需要补白:true为补白; false为不补白; + * @param fillColor 填充色,null时为Color.WHITE + */ + public final static void zoomFixed(BufferedImage src, OutputStream output, String type, int height, int width, boolean bb, Color fillColor) { + try { + double ratio = 0.0; // 缩放比例 + Image itemp = src.getScaledInstance(width, height, BufferedImage.SCALE_SMOOTH); + // 计算比例 + if (src.getHeight() > src.getWidth()) { + ratio = Integer.valueOf(height).doubleValue() / src.getHeight(); + } else { + ratio = Integer.valueOf(width).doubleValue() / src.getWidth(); + } + AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null); + itemp = op.filter(src, null); + + if (bb) { + //补白 + BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + Graphics2D g = image.createGraphics(); + Color fill = fillColor == null ? Color.white : fillColor; + g.setColor(fill); + g.fillRect(0, 0, width, height); + if (width == itemp.getWidth(null)) { + g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2, itemp.getWidth(null), itemp.getHeight(null), fill, null); + } else { + g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0, itemp.getWidth(null), itemp.getHeight(null), fill, null); + } + g.dispose(); + itemp = image; + } + // 输出为文件 + ImageIO.write((BufferedImage) itemp, defaultString(type, DEFAULT_IMG_TYPE), output); + // 关闭流 + output.close(); + } catch (IOException e) { + LOGGER.error("Error in zoom image", e); + } + } + + /** + * 图像裁剪(按指定起点坐标和宽高切割) + * + * @param src 源图像 + * @param output 切片后的图像地址 + * @param x 目标切片起点坐标X + * @param y 目标切片起点坐标Y + * @param width 目标切片宽度 + * @param height 目标切片高度 + */ + public final static void crop(BufferedImage src, OutputStream output, String type, int x, int y, int width, int height) { + try { + // 源图宽度 + int srcWidth = src.getHeight(); + // 源图高度 + int srcHeight = src.getWidth(); + if (srcWidth > 0 && srcHeight > 0) { + Image image = src.getScaledInstance(srcWidth, srcHeight, Image.SCALE_DEFAULT); + // 四个参数分别为图像起点坐标和宽高 + ImageFilter cropFilter = new CropImageFilter(x, y, width, height); + Image img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), cropFilter)); + BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + Graphics g = tag.getGraphics(); + g.drawImage(img, 0, 0, width, height, null); // 绘制切割后的图 + g.dispose(); + // 输出为文件 + ImageIO.write(tag, defaultString(type, DEFAULT_IMG_TYPE), output); + // 关闭流 + output.close(); + } + } catch (Exception e) { + LOGGER.error("Error in cut image", e); + } + } + + /** + * 图像切割(指定切片的行数和列数) + * + * @param src 源图像地址 + * @param mos 切片目标文件夹 + * @param prows 目标切片行数。默认2,必须是范围 [1, 20] 之内 + * @param pcols 目标切片列数。默认2,必须是范围 [1, 20] 之内 + */ + public final static void sliceWithNumber(BufferedImage src, IMultiOutputStream mos, String type, int prows, int pcols) { + try { + int rows = prows <= 0 || prows > 20 ? 2 : prows; + int cols = pcols <= 0 || pcols > 20 ? 2 : pcols; + // 源图宽度 + int srcWidth = src.getHeight(); + // 源图高度 + int srcHeight = src.getWidth(); + if (srcWidth > 0 && srcHeight > 0) { + Image img; + ImageFilter cropFilter; + Image image = src.getScaledInstance(srcWidth, srcHeight, Image.SCALE_DEFAULT); + // 每张切片的宽度 + int destWidth = (srcWidth % cols == 0) ? (srcWidth / cols) : (srcWidth / cols + 1); + // 每张切片的高度 + int destHeight = (srcHeight % rows == 0) ? (srcHeight / rows) : (srcHeight / rows + 1); + // 循环建立切片 + // 改进的想法:是否可用多线程加快切割速度 + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + // 四个参数分别为图像起点坐标和宽高 + cropFilter = new CropImageFilter(j * destWidth, i * destHeight, destWidth, destHeight); + img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), cropFilter)); + BufferedImage tag = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB); + Graphics g = tag.getGraphics(); + // 绘制缩小后的图 + g.drawImage(img, 0, 0, null); + g.dispose(); + // 输出为文件 + ImageIO.write(tag, defaultString(type, DEFAULT_IMG_TYPE), mos.buildOutputStream(i, j)); + } + } + } + } catch (Exception e) { + LOGGER.error("Error in slice image", e); + } + } + + /** + * 图像切割(指定切片的宽度和高度) + * + * @param src 源图像地址 + * @param mos 切片目标文件夹 + * @param pdestWidth 目标切片宽度。默认200 + * @param pdestHeight 目标切片高度。默认150 + */ + public final static void sliceWithSize(BufferedImage src, IMultiOutputStream mos, String type, int pdestWidth, int pdestHeight) { + try { + int destWidth = pdestWidth <= 0 ? 200 : pdestWidth; + int destHeight = pdestHeight <= 0 ? 150 : pdestHeight; + // 源图宽度 + int srcWidth = src.getHeight(); + // 源图高度 + int srcHeight = src.getWidth(); + if (srcWidth > destWidth && srcHeight > destHeight) { + Image img; + ImageFilter cropFilter; + Image image = src.getScaledInstance(srcWidth, srcHeight, Image.SCALE_DEFAULT); + // 切片横向数量 + int cols = (srcWidth % destWidth == 0) ? (srcWidth / destWidth) : (srcWidth / destWidth + 1); + // 切片纵向数量 + int rows = (srcHeight % destHeight == 0) ? (srcHeight / destHeight) : (srcHeight / destHeight + 1); + // 循环建立切片 + // 改进的想法:是否可用多线程加快切割速度 + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + // 四个参数分别为图像起点坐标和宽高 + cropFilter = new CropImageFilter(j * destWidth, i * destHeight, destWidth, destHeight); + img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), cropFilter)); + BufferedImage tag = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB); + Graphics g = tag.getGraphics(); + // 绘制缩小后的图 + g.drawImage(img, 0, 0, null); + g.dispose(); + // 输出为文件 + ImageIO.write(tag, defaultString(type, DEFAULT_IMG_TYPE), mos.buildOutputStream(i, j)); + } + } + } + } catch (Exception e) { + LOGGER.error("Error in slice image", e); + } + } + + /** + * 图像类型转换:GIF->JPG、GIF->PNG、PNG->JPG、PNG->GIF(X)、BMP->PNG + * + * @param src 源图像地址 + * @param formatName 包含格式非正式名称的 String:如JPG、JPEG、GIF等 + * @param output 目标图像地址 + */ + public final static void convert(BufferedImage src, OutputStream output, String formatName) { + try { + // 输出为文件 + ImageIO.write(src, formatName, output); + // 关闭流 + output.close(); + } catch (Exception e) { + LOGGER.error("Error in convert image", e); + } + } + + /** + * 彩色转为黑白 + * + * @param src 源图像地址 + * @param output 目标图像地址 + */ + public final static void gray(BufferedImage src, OutputStream output, String type) { + try { + ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY); + ColorConvertOp op = new ColorConvertOp(cs, null); + src = op.filter(src, null); + // 输出为文件 + ImageIO.write(src, defaultString(type, DEFAULT_IMG_TYPE), output); + // 关闭流 + output.close(); + } catch (IOException e) { + LOGGER.error("Error in gray image", e); + } + } + + /** + * 给图片添加文字水印 + * + * @param src 源图像 + * @param output 输出流 + * @param text 水印文字 + * @param font 水印的字体 + * @param color 水印的字体颜色 + * @param position 水印位置 {@link ImagePosition} + * @param x 修正值 + * @param y 修正值 + * @param alpha 透明度:alpha 必须是范围 [0.0, 1.0] 之内(包含边界值)的一个浮点数字 + */ + public final static void textStamp(BufferedImage src, OutputStream output, String type, String text, Font font, Color color + , int position, int x, int y, float alpha) { + try { + int width = src.getWidth(null); + int height = src.getHeight(null); + BufferedImage image = new BufferedImage(width, height, + BufferedImage.TYPE_INT_RGB); + Graphics2D g = image.createGraphics(); + g.drawImage(src, 0, 0, width, height, null); + g.setColor(color); + g.setFont(font); + g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha)); + // 在指定坐标绘制水印文字 + ImagePosition boxPos = new ImagePosition(width, height, calcTextWidth(text) * font.getSize(), font.getSize(), position); + g.drawString(text, boxPos.getX(x), boxPos.getY(y)); + g.dispose(); + // 输出为文件 + ImageIO.write((BufferedImage) image, defaultString(type, DEFAULT_IMG_TYPE), output); + // 关闭流 + output.close(); + } catch (Exception e) { + LOGGER.error("Error in textStamp image", e); + } + } + + /** + * 给图片添加图片水印 + * + * @param src 源图像 + * @param output 输出流 + * @param stamp 水印图片 + * @param position 水印位置 {@link ImagePosition} + * @param x 修正值 + * @param y 修正值 + * @param alpha 透明度:alpha 必须是范围 [0.0, 1.0] 之内(包含边界值)的一个浮点数字 + */ + public final static void imageStamp(BufferedImage src, OutputStream output, String type, BufferedImage stamp + , int position, int x, int y, float alpha) { + try { + int width = src.getWidth(); + int height = src.getHeight(); + BufferedImage image = new BufferedImage(width, height, + BufferedImage.TYPE_INT_RGB); + Graphics2D g = image.createGraphics(); + g.drawImage(src, 0, 0, width, height, null); + // 水印文件 + int stampWidth = stamp.getWidth(); + int stampHeight = stamp.getHeight(); + g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha)); + ImagePosition boxPos = new ImagePosition(width, height, stampWidth, stampHeight, position); + g.drawImage(stamp, boxPos.getX(x), boxPos.getY(y), stampWidth, stampHeight, null); + // 水印文件结束 + g.dispose(); + // 输出为文件 + ImageIO.write((BufferedImage) image, defaultString(type, DEFAULT_IMG_TYPE), output); + // 关闭流 + output.close(); + } catch (Exception e) { + LOGGER.error("Error imageStamp", e); + } + } + + /** + * 计算text的长度(一个中文算两个字符) + * + * @param text + * @return + */ + public final static int calcTextWidth(String text) { + int length = 0; + for (int i = 0; i < text.length(); i++) { + if (new String(text.charAt(i) + "").getBytes().length > 1) { + length += 2; + } else { + length += 1; + } + } + return length / 2; + } + + public static String defaultString(String str, String defaultStr) { return ((str == null) ? defaultStr : str); } - + } diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/Lazy.java b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/Lazy.java index ce9b15e..0daa419 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/Lazy.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/Lazy.java @@ -34,8 +34,9 @@ public class Lazy implements Supplier, Serializable { /** * Creates new instance of Lazy. + * * @param supplier Supplier - * @param 泛型标记 + * @param 泛型标记 * @return Lazy */ public static Lazy of(final Supplier supplier) { @@ -48,6 +49,7 @@ public class Lazy implements Supplier, Serializable { /** * Returns the value. Value will be computed on first call. + * * @return lazy value */ @Nullable diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/NumberUtil.java b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/NumberUtil.java index 4248fa1..e7bb5d5 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/NumberUtil.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/NumberUtil.java @@ -121,73 +121,74 @@ public class NumberUtil extends org.springframework.util.NumberUtils { } } - /** - *

Convert a String to a Double - * - * @param value - * @return double value - */ - public static Double toDouble(String value) { - return toDouble(value, null); - } + /** + *

Convert a String to a Double + * + * @param value + * @return double value + */ + public static Double toDouble(String value) { + return toDouble(value, null); + } - /** - *

Convert a String to a Double - * - * @param value - * @param defaultValue 默认值 - * @return double value - */ - public static Double toDouble(@Nullable String value, Double defaultValue) { - if (value != null) { - return Double.valueOf(value.trim()); - } - return defaultValue; - } + /** + *

Convert a String to a Double + * + * @param value + * @param defaultValue 默认值 + * @return double value + */ + public static Double toDouble(@Nullable String value, Double defaultValue) { + if (value != null) { + return Double.valueOf(value.trim()); + } + return defaultValue; + } - /** - *

Convert a String to a Double - * - * @param value - * @return double value - */ - public static Float toFloat(String value) { - return toFloat(value, null); - } + /** + *

Convert a String to a Double + * + * @param value + * @return double value + */ + public static Float toFloat(String value) { + return toFloat(value, null); + } - /** - *

Convert a String to a Double - * - * @param value - * @param defaultValue 默认值 - * @return double value - */ - public static Float toFloat(@Nullable String value, Float defaultValue) { - if (value != null) { - return Float.valueOf(value.trim()); - } - return defaultValue; - } + /** + *

Convert a String to a Double + * + * @param value + * @param defaultValue 默认值 + * @return double value + */ + public static Float toFloat(@Nullable String value, Float defaultValue) { + if (value != null) { + return Float.valueOf(value.trim()); + } + return defaultValue; + } /** * All possible chars for representing a number as a String */ private final static char[] DIGITS = { - '0' , '1' , '2' , '3' , '4' , '5' , - '6' , '7' , '8' , '9' , 'a' , 'b' , - 'c' , 'd' , 'e' , 'f' , 'g' , 'h' , - 'i' , 'j' , 'k' , 'l' , 'm' , 'n' , - 'o' , 'p' , 'q' , 'r' , 's' , 't' , - 'u' , 'v' , 'w' , 'x' , 'y' , 'z' , - 'A' , 'B' , 'C' , 'D' , 'E' , 'F' , - 'G' , 'H' , 'I' , 'J' , 'K' , 'L' , - 'M' , 'N' , 'O' , 'P' , 'Q' , 'R' , - 'S' , 'T' , 'U' , 'V' , 'W' , 'X' , - 'Y' , 'Z' + '0', '1', '2', '3', '4', '5', + '6', '7', '8', '9', 'a', 'b', + 'c', 'd', 'e', 'f', 'g', 'h', + 'i', 'j', 'k', 'l', 'm', 'n', + 'o', 'p', 'q', 'r', 's', 't', + 'u', 'v', 'w', 'x', 'y', 'z', + 'A', 'B', 'C', 'D', 'E', 'F', + 'G', 'H', 'I', 'J', 'K', 'L', + 'M', 'N', 'O', 'P', 'Q', 'R', + 'S', 'T', 'U', 'V', 'W', 'X', + 'Y', 'Z' }; /** * 将 long 转短字符串 为 62 进制 + * * @param i 数字 * @return 短字符串 */ @@ -197,10 +198,10 @@ public class NumberUtil extends org.springframework.util.NumberUtils { int charPos = 64; i = -i; while (i <= -radix) { - buf[charPos--] = DIGITS[(int)(-(i % radix))]; + buf[charPos--] = DIGITS[(int) (-(i % radix))]; i = i / radix; } - buf[charPos] = DIGITS[(int)(-i)]; + buf[charPos] = DIGITS[(int) (-i)]; return new String(buf, charPos, (65 - charPos)); } diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/OKHttpUtil.java b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/OKHttpUtil.java index 718899c..4eaef6b 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/OKHttpUtil.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/OKHttpUtil.java @@ -22,170 +22,176 @@ import java.util.Map; /** * Http请求工具类 + * + * @author smallchill */ @Slf4j public class OKHttpUtil { - public static MediaType JSON = MediaType.parse("application/json; charset=utf-8"); - public static MediaType XML = MediaType.parse("application/xml; charset=utf-8"); + public static MediaType JSON = MediaType.parse("application/json; charset=utf-8"); + public static MediaType XML = MediaType.parse("application/xml; charset=utf-8"); - /** - * GET - * - * @param url 请求的url - * @param queries 请求的参数,在浏览器?后面的数据,没有可以传null - * @return - */ - public static String get(String url, Map queries) { - return get(url, null, queries); - } + /** + * GET + * + * @param url 请求的url + * @param queries 请求的参数,在浏览器?后面的数据,没有可以传null + * @return + */ + public static String get(String url, Map queries) { + return get(url, null, queries); + } - /** - * GET - * - * @param url 请求的url - * @param header 请求头 - * @param queries 请求的参数,在浏览器?后面的数据,没有可以传null - * @return - */ - public static String get(String url, Map header, Map queries) { - StringBuffer sb = new StringBuffer(url); - if (queries != null && queries.keySet().size() > 0) { - sb.append("?clientId=blade"); - queries.forEach((k, v) -> sb.append("&").append(k).append("=").append(v)); - } + /** + * GET + * + * @param url 请求的url + * @param header 请求头 + * @param queries 请求的参数,在浏览器?后面的数据,没有可以传null + * @return + */ + public static String get(String url, Map header, Map queries) { + StringBuffer sb = new StringBuffer(url); + if (queries != null && queries.keySet().size() > 0) { + sb.append("?clientId=blade"); + queries.forEach((k, v) -> sb.append("&").append(k).append("=").append(v)); + } - Request.Builder builder = new Request.Builder(); + Request.Builder builder = new Request.Builder(); - //添加请求头 - if (header != null && header.keySet().size() > 0) { - header.forEach(builder::addHeader); - } + if (header != null && header.keySet().size() > 0) { + header.forEach(builder::addHeader); + } - Request request = builder.url(sb.toString()).build(); - return getBody(request); - } + Request request = builder.url(sb.toString()).build(); + return getBody(request); + } - /** - * POST - * - * @param url 请求的url - * @param params post form 提交的参数 - * @return - */ - public static String post(String url, Map params) { - return post(url, null, params); - } + /** + * POST + * + * @param url 请求的url + * @param params post form 提交的参数 + * @return + */ + public static String post(String url, Map params) { + return post(url, null, params); + } - /** - * POST - * - * @param url 请求的url - * @param header 请求头 - * @param params post form 提交的参数 - * @return - */ - public static String post(String url, Map header, Map params) { - FormBody.Builder formBuilder = new FormBody.Builder().add("clientId", "blade"); - //添加参数 - if (params != null && params.keySet().size() > 0) { - params.forEach(formBuilder::add); - } + /** + * POST + * + * @param url 请求的url + * @param header 请求头 + * @param params post form 提交的参数 + * @return + */ + public static String post(String url, Map header, Map params) { + FormBody.Builder formBuilder = new FormBody.Builder().add("clientId", "blade"); + //添加参数 + if (params != null && params.keySet().size() > 0) { + params.forEach(formBuilder::add); + } - Request.Builder builder = new Request.Builder(); - //添加请求头 - if (header != null && header.keySet().size() > 0) { - header.forEach(builder::addHeader); - } + Request.Builder builder = new Request.Builder(); - Request request = builder.url(url).post(formBuilder.build()).build(); - return getBody(request); - } + if (header != null && header.keySet().size() > 0) { + header.forEach(builder::addHeader); + } - /** - * POST请求发送JSON数据 - * @param url - * @param json - * @return - */ - public static String postJson(String url, String json) { - return postJson(url, null, json); - } + Request request = builder.url(url).post(formBuilder.build()).build(); + return getBody(request); + } - /** - * POST请求发送JSON数据 - * @param url - * @param header - * @param json - * @return - */ - public static String postJson(String url, Map header, String json) { - return postContent(url, header, json, JSON); - } + /** + * POST请求发送JSON数据 + * + * @param url + * @param json + * @return + */ + public static String postJson(String url, String json) { + return postJson(url, null, json); + } - /** - * POST请求发送xml数据 - * @param url - * @param xml - * @return - */ - public static String postXml(String url, String xml) { - return postXml(url, null, xml); - } + /** + * POST请求发送JSON数据 + * + * @param url + * @param header + * @param json + * @return + */ + public static String postJson(String url, Map header, String json) { + return postContent(url, header, json, JSON); + } - /** - * POST请求发送xml数据 - * @param url - * @param header - * @param xml - * @return - */ - public static String postXml(String url, Map header, String xml) { - return postContent(url, header, xml, XML); - } + /** + * POST请求发送xml数据 + * + * @param url + * @param xml + * @return + */ + public static String postXml(String url, String xml) { + return postXml(url, null, xml); + } - /** - * 发送POST请求 - * @param url - * @param header - * @param content - * @param mediaType - * @return - */ - public static String postContent(String url, Map header, String content, MediaType mediaType) { - RequestBody requestBody = RequestBody.create(mediaType, content); - Request.Builder builder = new Request.Builder(); - //添加请求头 - if (header != null && header.keySet().size() > 0) { - header.forEach(builder::addHeader); - } - Request request = builder.url(url).post(requestBody).build(); - return getBody(request); - } + /** + * POST请求发送xml数据 + * + * @param url + * @param header + * @param xml + * @return + */ + public static String postXml(String url, Map header, String xml) { + return postContent(url, header, xml, XML); + } - /** - * 获取body - * - * @param request - * @return - */ - private static String getBody(Request request) { - String responseBody = ""; - Response response = null; - try { - OkHttpClient okHttpClient = new OkHttpClient(); - response = okHttpClient.newCall(request).execute(); - if (response.isSuccessful()) { - return response.body().string(); - } - } catch (Exception e) { - log.error("okhttp3 post error >> ex = {}", e.getMessage()); - } finally { - if (response != null) { - response.close(); - } - } - return responseBody; - } + /** + * 发送POST请求 + * + * @param url + * @param header + * @param content + * @param mediaType + * @return + */ + public static String postContent(String url, Map header, String content, MediaType mediaType) { + RequestBody requestBody = RequestBody.create(mediaType, content); + Request.Builder builder = new Request.Builder(); + + if (header != null && header.keySet().size() > 0) { + header.forEach(builder::addHeader); + } + Request request = builder.url(url).post(requestBody).build(); + return getBody(request); + } + + /** + * 获取body + * + * @param request + * @return + */ + private static String getBody(Request request) { + String responseBody = ""; + Response response = null; + try { + OkHttpClient okHttpClient = new OkHttpClient(); + response = okHttpClient.newCall(request).execute(); + if (response.isSuccessful()) { + return response.body().string(); + } + } catch (Exception e) { + log.error("okhttp3 post error >> ex = {}", e.getMessage()); + } finally { + if (response != null) { + response.close(); + } + } + return responseBody; + } } diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/PathUtil.java b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/PathUtil.java index bcd18d2..54730c8 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/PathUtil.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/PathUtil.java @@ -34,6 +34,7 @@ public class PathUtil { /** * 获取jar包运行时的当前目录 + * * @return {String} */ @Nullable @@ -49,7 +50,9 @@ public class PathUtil { @Nullable public static String toFilePath(@Nullable URL url) { - if (url == null) { return null; } + if (url == null) { + return null; + } String protocol = url.getProtocol(); String file = URLUtil.decodeURL(url.getPath(), Charsets.UTF_8); if (FILE_PROTOCOL.equals(protocol)) { diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/ProtostuffUtil.java b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/ProtostuffUtil.java index d4a600c..a2c07ff 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/ProtostuffUtil.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/ProtostuffUtil.java @@ -26,6 +26,8 @@ import java.util.concurrent.ConcurrentHashMap; /** * Protostuff 工具类 + * + * @author L.cm */ public class ProtostuffUtil { diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/RandomType.java b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/RandomType.java index 9a15366..bf56adb 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/RandomType.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/RandomType.java @@ -24,5 +24,5 @@ public enum RandomType { /** * INT STRING ALL */ - INT, STRING, ALL; + INT, STRING, ALL } diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/RegexUtil.java b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/RegexUtil.java index 762ebdd..4d77e06 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/RegexUtil.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/RegexUtil.java @@ -64,12 +64,12 @@ public class RegexUtil { /** * 域名校验 */ - public static final String DOMAIN = "^[0-9a-zA-Z]+[0-9a-zA-Z\\.-]*\\.[a-zA-Z]{2,4}$"; + public static final String DOMAIN = "^[0-9a-zA-Z]+[0-9a-zA-Z\\.-]*\\.[a-zA-Z]{2,4}$"; /** - * * 编译传入正则表达式和字符串去匹配,忽略大小写 - * @param regex 正则 + * + * @param regex 正则 * @param beTestString 字符串 * @return {boolean} */ @@ -80,9 +80,9 @@ public class RegexUtil { } /** - * * 编译传入正则表达式在字符串中寻找,如果匹配到则为true - * @param regex 正则 + * + * @param regex 正则 * @param beTestString 字符串 * @return {boolean} */ @@ -95,7 +95,8 @@ public class RegexUtil { /** * 编译传入正则表达式在字符串中寻找,如果找到返回第一个结果 * 找不到返回null - * @param regex 正则 + * + * @param regex 正则 * @param beFoundString 字符串 * @return {boolean} */ diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/ResourceUtil.java b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/ResourceUtil.java index 937eff9..cfa4fa7 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/ResourceUtil.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/ResourceUtil.java @@ -35,19 +35,20 @@ public class ResourceUtil extends org.springframework.util.ResourceUtils { /** * 获取资源 - * + *

* 支持一下协议: *

- * 1. classpath: - * 2. file: - * 3. ftp: - * 4. http: and https: - * 5. classpath*: - * 6. C:/dir1/ and /Users/lcm + * 1. classpath: + * 2. file: + * 3. ftp: + * 4. http: and https: + * 5. classpath*: + * 6. C:/dir1/ and /Users/lcm *

+ * * @param resourceLocation 资源路径 - * @throws IOException IOException * @return {Resource} + * @throws IOException IOException */ public static Resource getResource(String resourceLocation) throws IOException { Assert.notNull(resourceLocation, "Resource location must not be null"); diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/SpringUtil.java b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/SpringUtil.java index 0d746a3..21c285e 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/SpringUtil.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/SpringUtil.java @@ -23,51 +23,53 @@ import org.springframework.context.ApplicationEvent; /** * spring 工具类 + * + * @author smallchill */ @Slf4j public class SpringUtil implements ApplicationContextAware { - private static ApplicationContext context; + private static ApplicationContext context; - @Override - public void setApplicationContext(ApplicationContext context) throws BeansException { - SpringUtil.context = context; - } + @Override + public void setApplicationContext(ApplicationContext context) throws BeansException { + SpringUtil.context = context; + } - public static T getBean(Class clazz) { - if (clazz == null) { - return null; - } - return context.getBean(clazz); - } - - public static T getBean(String beanId) { - if (beanId == null) { - return null; - } - return (T) context.getBean(beanId); - } - - public static T getBean(String beanName, Class clazz) { - if (null == beanName || "".equals(beanName.trim())) { - return null; - } - if (clazz == null) return null; - return (T) context.getBean(beanName, clazz); - } - - public static ApplicationContext getContext() { - if (context == null) return null; - return context; - } - - public static void publishEvent(ApplicationEvent event) { - if (context == null) return; - try { - context.publishEvent(event); - } catch (Exception ex) { - log.error(ex.getMessage()); + public static T getBean(Class clazz) { + if (clazz == null) { + return null; } - } + return context.getBean(clazz); + } + + public static T getBean(String beanId) { + if (beanId == null) { + return null; + } + return (T) context.getBean(beanId); + } + + public static T getBean(String beanName, Class clazz) { + if (null == beanName || "".equals(beanName.trim())) { + return null; + } + if (clazz == null) return null; + return (T) context.getBean(beanName, clazz); + } + + public static ApplicationContext getContext() { + if (context == null) return null; + return context; + } + + public static void publishEvent(ApplicationEvent event) { + if (context == null) return; + try { + context.publishEvent(event); + } catch (Exception ex) { + log.error(ex.getMessage()); + } + } } diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/StringUtil.java b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/StringUtil.java index 9eeb4e2..19e2773 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/StringUtil.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/StringUtil.java @@ -29,53 +29,57 @@ import java.util.stream.Stream; /** * 继承自Spring util的工具类,减少jar依赖 + * + * @author L.cm */ public class StringUtil extends org.springframework.util.StringUtils { - public static final int INDEX_NOT_FOUND = -1; - /** - * Check whether the given {@code CharSequence} contains actual text. - *

More specifically, this method returns {@code true} if the - * {@code CharSequence} is not {@code null}, its length is greater than - * 0, and it contains at least one non-whitespace character. - *

-     * StringUtil.isBlank(null) = true
-     * StringUtil.isBlank("") = true
-     * StringUtil.isBlank(" ") = true
-     * StringUtil.isBlank("12345") = false
-     * StringUtil.isBlank(" 12345 ") = false
-     * 
- * - * @param cs the {@code CharSequence} to check (may be {@code null}) - * @return {@code true} if the {@code CharSequence} is not {@code null}, - * its length is greater than 0, and it does not contain whitespace only - * @see Character#isWhitespace - */ - public static boolean isBlank(final CharSequence cs) { - return !StringUtil.hasText(cs); - } + public static final int INDEX_NOT_FOUND = -1; - /** - *

Checks if a CharSequence is not empty (""), not null and not whitespace only.

- *
-     * StringUtil.isNotBlank(null)	  = false
-     * StringUtil.isNotBlank("")		= false
-     * StringUtil.isNotBlank(" ")	   = false
-     * StringUtil.isNotBlank("bob")	 = true
-     * StringUtil.isNotBlank("  bob  ") = true
-     * 
- * - * @param cs the CharSequence to check, may be null - * @return {@code true} if the CharSequence is - * not empty and not null and not whitespace - * @see Character#isWhitespace - */ - public static boolean isNotBlank(final CharSequence cs) { - return StringUtil.hasText(cs); - } + /** + * Check whether the given {@code CharSequence} contains actual text. + *

More specifically, this method returns {@code true} if the + * {@code CharSequence} is not {@code null}, its length is greater than + * 0, and it contains at least one non-whitespace character. + *

+	 * StringUtil.isBlank(null) = true
+	 * StringUtil.isBlank("") = true
+	 * StringUtil.isBlank(" ") = true
+	 * StringUtil.isBlank("12345") = false
+	 * StringUtil.isBlank(" 12345 ") = false
+	 * 
+ * + * @param cs the {@code CharSequence} to check (may be {@code null}) + * @return {@code true} if the {@code CharSequence} is not {@code null}, + * its length is greater than 0, and it does not contain whitespace only + * @see Character#isWhitespace + */ + public static boolean isBlank(final CharSequence cs) { + return !StringUtil.hasText(cs); + } + + /** + *

Checks if a CharSequence is not empty (""), not null and not whitespace only.

+ *
+	 * StringUtil.isNotBlank(null)	  = false
+	 * StringUtil.isNotBlank("")		= false
+	 * StringUtil.isNotBlank(" ")	   = false
+	 * StringUtil.isNotBlank("bob")	 = true
+	 * StringUtil.isNotBlank("  bob  ") = true
+	 * 
+ * + * @param cs the CharSequence to check, may be null + * @return {@code true} if the CharSequence is + * not empty and not null and not whitespace + * @see Character#isWhitespace + */ + public static boolean isNotBlank(final CharSequence cs) { + return StringUtil.hasText(cs); + } /** * 有 任意 一个 Blank + * * @param css CharSequence * @return boolean */ @@ -88,6 +92,7 @@ public class StringUtil extends org.springframework.util.StringUtils { /** * 是否全非 Blank + * * @param css CharSequence * @return boolean */ @@ -98,727 +103,728 @@ public class StringUtil extends org.springframework.util.StringUtils { return Stream.of(css).allMatch(StringUtil::isNotBlank); } - /** - * 判断一个字符串是否是数字 - * - * @param cs the CharSequence to check, may be null - * @return {boolean} - */ - public static boolean isNumeric(final CharSequence cs) { - if (isBlank(cs)) { - return false; - } - for (int i = cs.length(); --i >= 0; ) { - int chr = cs.charAt(i); - if (chr < 48 || chr > 57) - return false; - } - return true; - } + /** + * 判断一个字符串是否是数字 + * + * @param cs the CharSequence to check, may be null + * @return {boolean} + */ + public static boolean isNumeric(final CharSequence cs) { + if (isBlank(cs)) { + return false; + } + for (int i = cs.length(); --i >= 0; ) { + int chr = cs.charAt(i); + if (chr < 48 || chr > 57) { + return false; + } + } + return true; + } - /** - * Convert a {@code Collection} into a delimited {@code String} (e.g., CSV). - *

Useful for {@code toString()} implementations. - * - * @param coll the {@code Collection} to convert - * @return the delimited {@code String} - */ - public static String join(Collection coll) { - return StringUtil.collectionToCommaDelimitedString(coll); - } + /** + * Convert a {@code Collection} into a delimited {@code String} (e.g., CSV). + *

Useful for {@code toString()} implementations. + * + * @param coll the {@code Collection} to convert + * @return the delimited {@code String} + */ + public static String join(Collection coll) { + return StringUtil.collectionToCommaDelimitedString(coll); + } - /** - * Convert a {@code Collection} into a delimited {@code String} (e.g. CSV). - *

Useful for {@code toString()} implementations. - * - * @param coll the {@code Collection} to convert - * @param delim the delimiter to use (typically a ",") - * @return the delimited {@code String} - */ - public static String join(Collection coll, String delim) { - return StringUtil.collectionToDelimitedString(coll, delim); - } + /** + * Convert a {@code Collection} into a delimited {@code String} (e.g. CSV). + *

Useful for {@code toString()} implementations. + * + * @param coll the {@code Collection} to convert + * @param delim the delimiter to use (typically a ",") + * @return the delimited {@code String} + */ + public static String join(Collection coll, String delim) { + return StringUtil.collectionToDelimitedString(coll, delim); + } - /** - * Convert a {@code String} array into a comma delimited {@code String} - * (i.e., CSV). - *

Useful for {@code toString()} implementations. - * - * @param arr the array to display - * @return the delimited {@code String} - */ - public static String join(Object[] arr) { - return StringUtil.arrayToCommaDelimitedString(arr); - } + /** + * Convert a {@code String} array into a comma delimited {@code String} + * (i.e., CSV). + *

Useful for {@code toString()} implementations. + * + * @param arr the array to display + * @return the delimited {@code String} + */ + public static String join(Object[] arr) { + return StringUtil.arrayToCommaDelimitedString(arr); + } - /** - * Convert a {@code String} array into a delimited {@code String} (e.g. CSV). - *

Useful for {@code toString()} implementations. - * - * @param arr the array to display - * @param delim the delimiter to use (typically a ",") - * @return the delimited {@code String} - */ - public static String join(Object[] arr, String delim) { - return StringUtil.arrayToDelimitedString(arr, delim); - } + /** + * Convert a {@code String} array into a delimited {@code String} (e.g. CSV). + *

Useful for {@code toString()} implementations. + * + * @param arr the array to display + * @param delim the delimiter to use (typically a ",") + * @return the delimited {@code String} + */ + public static String join(Object[] arr, String delim) { + return StringUtil.arrayToDelimitedString(arr, delim); + } - /** - * 生成uuid - * - * @return UUID - */ - public static String randomUUID() { + /** + * 生成uuid + * + * @return UUID + */ + public static String randomUUID() { ThreadLocalRandom random = ThreadLocalRandom.current(); return new UUID(random.nextLong(), random.nextLong()).toString().replace(StringPool.DASH, StringPool.EMPTY); - } + } - /** - * 转义HTML用于安全过滤 - * - * @param html html - * @return {String} - */ - public static String escapeHtml(String html) { - return HtmlUtils.htmlEscape(html); - } + /** + * 转义HTML用于安全过滤 + * + * @param html html + * @return {String} + */ + public static String escapeHtml(String html) { + return HtmlUtils.htmlEscape(html); + } - /** - * 清理字符串,清理出某些不可见字符 - * - * @param txt 字符串 - * @return {String} - */ - public static String cleanChars(String txt) { - return txt.replaceAll("[  `·•�\\f\\t\\v\\s]", ""); - } + /** + * 清理字符串,清理出某些不可见字符 + * + * @param txt 字符串 + * @return {String} + */ + public static String cleanChars(String txt) { + return txt.replaceAll("[  `·•�\\f\\t\\v\\s]", ""); + } - // 随机字符串 - private static final String _INT = "0123456789"; - private static final String _STR = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; - private static final String _ALL = _INT + _STR; + // 随机字符串 + private static final String _INT = "0123456789"; + private static final String _STR = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + private static final String _ALL = _INT + _STR; - /** - * 随机数生成 - * - * @param count 字符长度 - * @return 随机数 - */ - public static String random(int count) { - return StringUtil.random(count, RandomType.ALL); - } + /** + * 随机数生成 + * + * @param count 字符长度 + * @return 随机数 + */ + public static String random(int count) { + return StringUtil.random(count, RandomType.ALL); + } - /** - * 随机数生成 - * - * @param count 字符长度 - * @param randomType 随机数类别 - * @return 随机数 - */ - public static String random(int count, RandomType randomType) { - if (count == 0) { - return ""; - } - Assert.isTrue(count > 0, "Requested random string length " + count + " is less than 0."); - final ThreadLocalRandom random = ThreadLocalRandom.current(); - char[] buffer = new char[count]; - for (int i = 0; i < count; i++) { - if (RandomType.INT == randomType) { - buffer[i] = _INT.charAt(random.nextInt(_INT.length())); - } else if (RandomType.STRING == randomType) { - buffer[i] = _STR.charAt(random.nextInt(_STR.length())); - } else { - buffer[i] = _ALL.charAt(random.nextInt(_ALL.length())); - } - } - return new String(buffer); - } + /** + * 随机数生成 + * + * @param count 字符长度 + * @param randomType 随机数类别 + * @return 随机数 + */ + public static String random(int count, RandomType randomType) { + if (count == 0) { + return ""; + } + Assert.isTrue(count > 0, "Requested random string length " + count + " is less than 0."); + final ThreadLocalRandom random = ThreadLocalRandom.current(); + char[] buffer = new char[count]; + for (int i = 0; i < count; i++) { + if (RandomType.INT == randomType) { + buffer[i] = _INT.charAt(random.nextInt(_INT.length())); + } else if (RandomType.STRING == randomType) { + buffer[i] = _STR.charAt(random.nextInt(_STR.length())); + } else { + buffer[i] = _ALL.charAt(random.nextInt(_ALL.length())); + } + } + return new String(buffer); + } - /** - * 格式化文本, {} 表示占位符
- * 此方法只是简单将占位符 {} 按照顺序替换为参数
- * 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可
- * 例:
- * 通常使用:format("this is {} for {}", "a", "b") =》 this is a for b
- * 转义{}: format("this is \\{} for {}", "a", "b") =》 this is \{} for a
- * 转义\: format("this is \\\\{} for {}", "a", "b") =》 this is \a for b
- * - * @param template 文本模板,被替换的部分用 {} 表示 - * @param params 参数值 - * @return 格式化后的文本 - */ - public static String format(CharSequence template, Object... params) { - if (null == template) { - return null; - } - if (Func.isEmpty(params) || isBlank(template)) { - return template.toString(); - } - return StrFormatter.format(template.toString(), params); - } + /** + * 格式化文本, {} 表示占位符
+ * 此方法只是简单将占位符 {} 按照顺序替换为参数
+ * 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可
+ * 例:
+ * 通常使用:format("this is {} for {}", "a", "b") =》 this is a for b
+ * 转义{}: format("this is \\{} for {}", "a", "b") =》 this is \{} for a
+ * 转义\: format("this is \\\\{} for {}", "a", "b") =》 this is \a for b
+ * + * @param template 文本模板,被替换的部分用 {} 表示 + * @param params 参数值 + * @return 格式化后的文本 + */ + public static String format(CharSequence template, Object... params) { + if (null == template) { + return null; + } + if (Func.isEmpty(params) || isBlank(template)) { + return template.toString(); + } + return StrFormatter.format(template.toString(), params); + } - /** - * 有序的格式化文本,使用{number}做为占位符
- * 例:
- * 通常使用:format("this is {0} for {1}", "a", "b") =》 this is a for b
- * - * @param pattern 文本格式 - * @param arguments 参数 - * @return 格式化后的文本 - */ - public static String indexedFormat(CharSequence pattern, Object... arguments) { - return MessageFormat.format(pattern.toString(), arguments); - } + /** + * 有序的格式化文本,使用{number}做为占位符
+ * 例:
+ * 通常使用:format("this is {0} for {1}", "a", "b") =》 this is a for b
+ * + * @param pattern 文本格式 + * @param arguments 参数 + * @return 格式化后的文本 + */ + public static String indexedFormat(CharSequence pattern, Object... arguments) { + return MessageFormat.format(pattern.toString(), arguments); + } - /** - * 格式化文本,使用 {varName} 占位
- * map = {a: "aValue", b: "bValue"} format("{a} and {b}", map) ---=》 aValue and bValue - * - * @param template 文本模板,被替换的部分用 {key} 表示 - * @param map 参数值对 - * @return 格式化后的文本 - */ - public static String format(CharSequence template, Map map) { - if (null == template) { - return null; - } - if (null == map || map.isEmpty()) { - return template.toString(); - } + /** + * 格式化文本,使用 {varName} 占位
+ * map = {a: "aValue", b: "bValue"} format("{a} and {b}", map) ---=》 aValue and bValue + * + * @param template 文本模板,被替换的部分用 {key} 表示 + * @param map 参数值对 + * @return 格式化后的文本 + */ + public static String format(CharSequence template, Map map) { + if (null == template) { + return null; + } + if (null == map || map.isEmpty()) { + return template.toString(); + } - String template2 = template.toString(); - for (Map.Entry entry : map.entrySet()) { - template2 = template2.replace("{" + entry.getKey() + "}", Func.toStr(entry.getValue())); - } - return template2; - } + String template2 = template.toString(); + for (Map.Entry entry : map.entrySet()) { + template2 = template2.replace("{" + entry.getKey() + "}", Func.toStr(entry.getValue())); + } + return template2; + } - /** - * 切分字符串,不去除切分后每个元素两边的空白符,不去除空白项 - * - * @param str 被切分的字符串 - * @param separator 分隔符字符 - * @param limit 限制分片数,-1不限制 - * @return 切分后的集合 - */ - public static List split(CharSequence str, char separator, int limit) { - return split(str, separator, limit, false, false); - } + /** + * 切分字符串,不去除切分后每个元素两边的空白符,不去除空白项 + * + * @param str 被切分的字符串 + * @param separator 分隔符字符 + * @param limit 限制分片数,-1不限制 + * @return 切分后的集合 + */ + public static List split(CharSequence str, char separator, int limit) { + return split(str, separator, limit, false, false); + } - /** - * 切分字符串,去除切分后每个元素两边的空白符,去除空白项 - * - * @param str 被切分的字符串 - * @param separator 分隔符字符 - * @return 切分后的集合 - * @since 3.1.2 - */ - public static List splitTrim(CharSequence str, char separator) { - return splitTrim(str, separator, -1); - } + /** + * 切分字符串,去除切分后每个元素两边的空白符,去除空白项 + * + * @param str 被切分的字符串 + * @param separator 分隔符字符 + * @return 切分后的集合 + * @since 3.1.2 + */ + public static List splitTrim(CharSequence str, char separator) { + return splitTrim(str, separator, -1); + } - /** - * 切分字符串,去除切分后每个元素两边的空白符,去除空白项 - * - * @param str 被切分的字符串 - * @param separator 分隔符字符 - * @return 切分后的集合 - * @since 3.2.0 - */ - public static List splitTrim(CharSequence str, CharSequence separator) { - return splitTrim(str, separator, -1); - } + /** + * 切分字符串,去除切分后每个元素两边的空白符,去除空白项 + * + * @param str 被切分的字符串 + * @param separator 分隔符字符 + * @return 切分后的集合 + * @since 3.2.0 + */ + public static List splitTrim(CharSequence str, CharSequence separator) { + return splitTrim(str, separator, -1); + } - /** - * 切分字符串,去除切分后每个元素两边的空白符,去除空白项 - * - * @param str 被切分的字符串 - * @param separator 分隔符字符 - * @param limit 限制分片数,-1不限制 - * @return 切分后的集合 - * @since 3.1.0 - */ - public static List splitTrim(CharSequence str, char separator, int limit) { - return split(str, separator, limit, true, true); - } + /** + * 切分字符串,去除切分后每个元素两边的空白符,去除空白项 + * + * @param str 被切分的字符串 + * @param separator 分隔符字符 + * @param limit 限制分片数,-1不限制 + * @return 切分后的集合 + * @since 3.1.0 + */ + public static List splitTrim(CharSequence str, char separator, int limit) { + return split(str, separator, limit, true, true); + } - /** - * 切分字符串,去除切分后每个元素两边的空白符,去除空白项 - * - * @param str 被切分的字符串 - * @param separator 分隔符字符 - * @param limit 限制分片数,-1不限制 - * @return 切分后的集合 - * @since 3.2.0 - */ - public static List splitTrim(CharSequence str, CharSequence separator, int limit) { - return split(str, separator, limit, true, true); - } + /** + * 切分字符串,去除切分后每个元素两边的空白符,去除空白项 + * + * @param str 被切分的字符串 + * @param separator 分隔符字符 + * @param limit 限制分片数,-1不限制 + * @return 切分后的集合 + * @since 3.2.0 + */ + public static List splitTrim(CharSequence str, CharSequence separator, int limit) { + return split(str, separator, limit, true, true); + } - /** - * 切分字符串,不限制分片数量 - * - * @param str 被切分的字符串 - * @param separator 分隔符字符 - * @param isTrim 是否去除切分字符串后每个元素两边的空格 - * @param ignoreEmpty 是否忽略空串 - * @return 切分后的集合 - * @since 3.0.8 - */ - public static List split(CharSequence str, char separator, boolean isTrim, boolean ignoreEmpty) { - return split(str, separator, 0, isTrim, ignoreEmpty); - } + /** + * 切分字符串,不限制分片数量 + * + * @param str 被切分的字符串 + * @param separator 分隔符字符 + * @param isTrim 是否去除切分字符串后每个元素两边的空格 + * @param ignoreEmpty 是否忽略空串 + * @return 切分后的集合 + * @since 3.0.8 + */ + public static List split(CharSequence str, char separator, boolean isTrim, boolean ignoreEmpty) { + return split(str, separator, 0, isTrim, ignoreEmpty); + } - /** - * 切分字符串 - * - * @param str 被切分的字符串 - * @param separator 分隔符字符 - * @param limit 限制分片数,-1不限制 - * @param isTrim 是否去除切分字符串后每个元素两边的空格 - * @param ignoreEmpty 是否忽略空串 - * @return 切分后的集合 - * @since 3.0.8 - */ - public static List split(CharSequence str, char separator, int limit, boolean isTrim, boolean ignoreEmpty) { - if (null == str) { - return new ArrayList<>(0); - } - return StrSpliter.split(str.toString(), separator, limit, isTrim, ignoreEmpty); - } + /** + * 切分字符串 + * + * @param str 被切分的字符串 + * @param separator 分隔符字符 + * @param limit 限制分片数,-1不限制 + * @param isTrim 是否去除切分字符串后每个元素两边的空格 + * @param ignoreEmpty 是否忽略空串 + * @return 切分后的集合 + * @since 3.0.8 + */ + public static List split(CharSequence str, char separator, int limit, boolean isTrim, boolean ignoreEmpty) { + if (null == str) { + return new ArrayList<>(0); + } + return StrSpliter.split(str.toString(), separator, limit, isTrim, ignoreEmpty); + } - /** - * 切分字符串 - * - * @param str 被切分的字符串 - * @param separator 分隔符字符 - * @param limit 限制分片数,-1不限制 - * @param isTrim 是否去除切分字符串后每个元素两边的空格 - * @param ignoreEmpty 是否忽略空串 - * @return 切分后的集合 - * @since 3.2.0 - */ - public static List split(CharSequence str, CharSequence separator, int limit, boolean isTrim, boolean ignoreEmpty) { - if (null == str) { - return new ArrayList<>(0); - } - final String separatorStr = (null == separator) ? null : separator.toString(); - return StrSpliter.split(str.toString(), separatorStr, limit, isTrim, ignoreEmpty); - } + /** + * 切分字符串 + * + * @param str 被切分的字符串 + * @param separator 分隔符字符 + * @param limit 限制分片数,-1不限制 + * @param isTrim 是否去除切分字符串后每个元素两边的空格 + * @param ignoreEmpty 是否忽略空串 + * @return 切分后的集合 + * @since 3.2.0 + */ + public static List split(CharSequence str, CharSequence separator, int limit, boolean isTrim, boolean ignoreEmpty) { + if (null == str) { + return new ArrayList<>(0); + } + final String separatorStr = (null == separator) ? null : separator.toString(); + return StrSpliter.split(str.toString(), separatorStr, limit, isTrim, ignoreEmpty); + } - /** - * 切分字符串 - * - * @param str 被切分的字符串 - * @param separator 分隔符 - * @return 字符串 - */ - public static String[] split(CharSequence str, CharSequence separator) { - if (str == null) { - return new String[]{}; - } + /** + * 切分字符串 + * + * @param str 被切分的字符串 + * @param separator 分隔符 + * @return 字符串 + */ + public static String[] split(CharSequence str, CharSequence separator) { + if (str == null) { + return new String[]{}; + } - final String separatorStr = (null == separator) ? null : separator.toString(); - return StrSpliter.splitToArray(str.toString(), separatorStr, 0, false, false); - } + final String separatorStr = (null == separator) ? null : separator.toString(); + return StrSpliter.splitToArray(str.toString(), separatorStr, 0, false, false); + } - /** - * 根据给定长度,将给定字符串截取为多个部分 - * - * @param str 字符串 - * @param len 每一个小节的长度 - * @return 截取后的字符串数组 - * @see StrSpliter#splitByLength(String, int) - */ - public static String[] split(CharSequence str, int len) { - if (null == str) { - return new String[]{}; - } - return StrSpliter.splitByLength(str.toString(), len); - } + /** + * 根据给定长度,将给定字符串截取为多个部分 + * + * @param str 字符串 + * @param len 每一个小节的长度 + * @return 截取后的字符串数组 + * @see StrSpliter#splitByLength(String, int) + */ + public static String[] split(CharSequence str, int len) { + if (null == str) { + return new String[]{}; + } + return StrSpliter.splitByLength(str.toString(), len); + } - /** - * 指定字符是否在字符串中出现过 - * - * @param str 字符串 - * @param searchChar 被查找的字符 - * @return 是否包含 - * @since 3.1.2 - */ - public static boolean contains(CharSequence str, char searchChar) { - return indexOf(str, searchChar) > -1; - } + /** + * 指定字符是否在字符串中出现过 + * + * @param str 字符串 + * @param searchChar 被查找的字符 + * @return 是否包含 + * @since 3.1.2 + */ + public static boolean contains(CharSequence str, char searchChar) { + return indexOf(str, searchChar) > -1; + } - /** - * 查找指定字符串是否包含指定字符串列表中的任意一个字符串 - * - * @param str 指定字符串 - * @param testStrs 需要检查的字符串数组 - * @return 是否包含任意一个字符串 - * @since 3.2.0 - */ - public static boolean containsAny(CharSequence str, CharSequence... testStrs) { - return null != getContainsStr(str, testStrs); - } + /** + * 查找指定字符串是否包含指定字符串列表中的任意一个字符串 + * + * @param str 指定字符串 + * @param testStrs 需要检查的字符串数组 + * @return 是否包含任意一个字符串 + * @since 3.2.0 + */ + public static boolean containsAny(CharSequence str, CharSequence... testStrs) { + return null != getContainsStr(str, testStrs); + } - /** - * 查找指定字符串是否包含指定字符串列表中的任意一个字符串,如果包含返回找到的第一个字符串 - * - * @param str 指定字符串 - * @param testStrs 需要检查的字符串数组 - * @return 被包含的第一个字符串 - * @since 3.2.0 - */ - public static String getContainsStr(CharSequence str, CharSequence... testStrs) { - if (isEmpty(str) || Func.isEmpty(testStrs)) { - return null; - } - for (CharSequence checkStr : testStrs) { - if (str.toString().contains(checkStr)) { - return checkStr.toString(); - } - } - return null; - } + /** + * 查找指定字符串是否包含指定字符串列表中的任意一个字符串,如果包含返回找到的第一个字符串 + * + * @param str 指定字符串 + * @param testStrs 需要检查的字符串数组 + * @return 被包含的第一个字符串 + * @since 3.2.0 + */ + public static String getContainsStr(CharSequence str, CharSequence... testStrs) { + if (isEmpty(str) || Func.isEmpty(testStrs)) { + return null; + } + for (CharSequence checkStr : testStrs) { + if (str.toString().contains(checkStr)) { + return checkStr.toString(); + } + } + return null; + } - /** - * 是否包含特定字符,忽略大小写,如果给定两个参数都为null,返回true - * - * @param str 被检测字符串 - * @param testStr 被测试是否包含的字符串 - * @return 是否包含 - */ - public static boolean containsIgnoreCase(CharSequence str, CharSequence testStr) { - if (null == str) { - // 如果被监测字符串和 - return null == testStr; - } - return str.toString().toLowerCase().contains(testStr.toString().toLowerCase()); - } + /** + * 是否包含特定字符,忽略大小写,如果给定两个参数都为null,返回true + * + * @param str 被检测字符串 + * @param testStr 被测试是否包含的字符串 + * @return 是否包含 + */ + public static boolean containsIgnoreCase(CharSequence str, CharSequence testStr) { + if (null == str) { + // 如果被监测字符串和 + return null == testStr; + } + return str.toString().toLowerCase().contains(testStr.toString().toLowerCase()); + } - /** - * 查找指定字符串是否包含指定字符串列表中的任意一个字符串
- * 忽略大小写 - * - * @param str 指定字符串 - * @param testStrs 需要检查的字符串数组 - * @return 是否包含任意一个字符串 - * @since 3.2.0 - */ - public static boolean containsAnyIgnoreCase(CharSequence str, CharSequence... testStrs) { - return null != getContainsStrIgnoreCase(str, testStrs); - } + /** + * 查找指定字符串是否包含指定字符串列表中的任意一个字符串
+ * 忽略大小写 + * + * @param str 指定字符串 + * @param testStrs 需要检查的字符串数组 + * @return 是否包含任意一个字符串 + * @since 3.2.0 + */ + public static boolean containsAnyIgnoreCase(CharSequence str, CharSequence... testStrs) { + return null != getContainsStrIgnoreCase(str, testStrs); + } - /** - * 查找指定字符串是否包含指定字符串列表中的任意一个字符串,如果包含返回找到的第一个字符串
- * 忽略大小写 - * - * @param str 指定字符串 - * @param testStrs 需要检查的字符串数组 - * @return 被包含的第一个字符串 - * @since 3.2.0 - */ - public static String getContainsStrIgnoreCase(CharSequence str, CharSequence... testStrs) { - if (isEmpty(str) || Func.isEmpty(testStrs)) { - return null; - } - for (CharSequence testStr : testStrs) { - if (containsIgnoreCase(str, testStr)) { - return testStr.toString(); - } - } - return null; - } + /** + * 查找指定字符串是否包含指定字符串列表中的任意一个字符串,如果包含返回找到的第一个字符串
+ * 忽略大小写 + * + * @param str 指定字符串 + * @param testStrs 需要检查的字符串数组 + * @return 被包含的第一个字符串 + * @since 3.2.0 + */ + public static String getContainsStrIgnoreCase(CharSequence str, CharSequence... testStrs) { + if (isEmpty(str) || Func.isEmpty(testStrs)) { + return null; + } + for (CharSequence testStr : testStrs) { + if (containsIgnoreCase(str, testStr)) { + return testStr.toString(); + } + } + return null; + } - /** - * 改进JDK subString
- * index从0开始计算,最后一个字符为-1
- * 如果from和to位置一样,返回 ""
- * 如果from或to为负数,则按照length从后向前数位置,如果绝对值大于字符串长度,则from归到0,to归到length
- * 如果经过修正的index中from大于to,则互换from和to example:
- * abcdefgh 2 3 =》 c
- * abcdefgh 2 -3 =》 cde
- * - * @param str String - * @param fromIndex 开始的index(包括) - * @param toIndex 结束的index(不包括) - * @return 字串 - */ - public static String sub(CharSequence str, int fromIndex, int toIndex) { - if (isEmpty(str)) { - return StringPool.EMPTY; - } - int len = str.length(); + /** + * 改进JDK subString
+ * index从0开始计算,最后一个字符为-1
+ * 如果from和to位置一样,返回 ""
+ * 如果from或to为负数,则按照length从后向前数位置,如果绝对值大于字符串长度,则from归到0,to归到length
+ * 如果经过修正的index中from大于to,则互换from和to example:
+ * abcdefgh 2 3 =》 c
+ * abcdefgh 2 -3 =》 cde
+ * + * @param str String + * @param fromIndex 开始的index(包括) + * @param toIndex 结束的index(不包括) + * @return 字串 + */ + public static String sub(CharSequence str, int fromIndex, int toIndex) { + if (isEmpty(str)) { + return StringPool.EMPTY; + } + int len = str.length(); - if (fromIndex < 0) { - fromIndex = len + fromIndex; - if (fromIndex < 0) { - fromIndex = 0; - } - } else if (fromIndex > len) { - fromIndex = len; - } + if (fromIndex < 0) { + fromIndex = len + fromIndex; + if (fromIndex < 0) { + fromIndex = 0; + } + } else if (fromIndex > len) { + fromIndex = len; + } - if (toIndex < 0) { - toIndex = len + toIndex; - if (toIndex < 0) { - toIndex = len; - } - } else if (toIndex > len) { - toIndex = len; - } + if (toIndex < 0) { + toIndex = len + toIndex; + if (toIndex < 0) { + toIndex = len; + } + } else if (toIndex > len) { + toIndex = len; + } - if (toIndex < fromIndex) { - int tmp = fromIndex; - fromIndex = toIndex; - toIndex = tmp; - } + if (toIndex < fromIndex) { + int tmp = fromIndex; + fromIndex = toIndex; + toIndex = tmp; + } - if (fromIndex == toIndex) { - return StringPool.EMPTY; - } + if (fromIndex == toIndex) { + return StringPool.EMPTY; + } - return str.toString().substring(fromIndex, toIndex); - } + return str.toString().substring(fromIndex, toIndex); + } + /** + * 截取分隔字符串之前的字符串,不包括分隔字符串
+ * 如果给定的字符串为空串(null或"")或者分隔字符串为null,返回原字符串
+ * 如果分隔字符串为空串"",则返回空串,如果分隔字符串未找到,返回原字符串 + *

+ * 栗子: + * + *

+	 * StringUtil.subBefore(null, *)      = null
+	 * StringUtil.subBefore("", *)        = ""
+	 * StringUtil.subBefore("abc", "a")   = ""
+	 * StringUtil.subBefore("abcba", "b") = "a"
+	 * StringUtil.subBefore("abc", "c")   = "ab"
+	 * StringUtil.subBefore("abc", "d")   = "abc"
+	 * StringUtil.subBefore("abc", "")    = ""
+	 * StringUtil.subBefore("abc", null)  = "abc"
+	 * 
+ * + * @param string 被查找的字符串 + * @param separator 分隔字符串(不包括) + * @param isLastSeparator 是否查找最后一个分隔字符串(多次出现分隔字符串时选取最后一个),true为选取最后一个 + * @return 切割后的字符串 + * @since 3.1.1 + */ + public static String subBefore(CharSequence string, CharSequence separator, boolean isLastSeparator) { + if (isEmpty(string) || separator == null) { + return null == string ? null : string.toString(); + } - /** - * 截取分隔字符串之前的字符串,不包括分隔字符串
- * 如果给定的字符串为空串(null或"")或者分隔字符串为null,返回原字符串
- * 如果分隔字符串为空串"",则返回空串,如果分隔字符串未找到,返回原字符串 - * - * 栗子: - * - *
-     * StringUtil.subBefore(null, *)      = null
-     * StringUtil.subBefore("", *)        = ""
-     * StringUtil.subBefore("abc", "a")   = ""
-     * StringUtil.subBefore("abcba", "b") = "a"
-     * StringUtil.subBefore("abc", "c")   = "ab"
-     * StringUtil.subBefore("abc", "d")   = "abc"
-     * StringUtil.subBefore("abc", "")    = ""
-     * StringUtil.subBefore("abc", null)  = "abc"
-     * 
- * - * @param string 被查找的字符串 - * @param separator 分隔字符串(不包括) - * @param isLastSeparator 是否查找最后一个分隔字符串(多次出现分隔字符串时选取最后一个),true为选取最后一个 - * @return 切割后的字符串 - * @since 3.1.1 - */ - public static String subBefore(CharSequence string, CharSequence separator, boolean isLastSeparator) { - if (isEmpty(string) || separator == null) { - return null == string ? null : string.toString(); - } + final String str = string.toString(); + final String sep = separator.toString(); + if (sep.isEmpty()) { + return StringPool.EMPTY; + } + final int pos = isLastSeparator ? str.lastIndexOf(sep) : str.indexOf(sep); + if (pos == INDEX_NOT_FOUND) { + return str; + } + return str.substring(0, pos); + } - final String str = string.toString(); - final String sep = separator.toString(); - if (sep.isEmpty()) { - return StringPool.EMPTY; - } - final int pos = isLastSeparator ? str.lastIndexOf(sep) : str.indexOf(sep); - if (pos == INDEX_NOT_FOUND) { - return str; - } - return str.substring(0, pos); - } + /** + * 截取分隔字符串之后的字符串,不包括分隔字符串
+ * 如果给定的字符串为空串(null或""),返回原字符串
+ * 如果分隔字符串为空串(null或""),则返回空串,如果分隔字符串未找到,返回空串 + *

+ * 栗子: + * + *

+	 * StringUtil.subAfter(null, *)      = null
+	 * StringUtil.subAfter("", *)        = ""
+	 * StringUtil.subAfter(*, null)      = ""
+	 * StringUtil.subAfter("abc", "a")   = "bc"
+	 * StringUtil.subAfter("abcba", "b") = "cba"
+	 * StringUtil.subAfter("abc", "c")   = ""
+	 * StringUtil.subAfter("abc", "d")   = ""
+	 * StringUtil.subAfter("abc", "")    = "abc"
+	 * 
+ * + * @param string 被查找的字符串 + * @param separator 分隔字符串(不包括) + * @param isLastSeparator 是否查找最后一个分隔字符串(多次出现分隔字符串时选取最后一个),true为选取最后一个 + * @return 切割后的字符串 + * @since 3.1.1 + */ + public static String subAfter(CharSequence string, CharSequence separator, boolean isLastSeparator) { + if (isEmpty(string)) { + return null == string ? null : string.toString(); + } + if (separator == null) { + return StringPool.EMPTY; + } + final String str = string.toString(); + final String sep = separator.toString(); + final int pos = isLastSeparator ? str.lastIndexOf(sep) : str.indexOf(sep); + if (pos == INDEX_NOT_FOUND) { + return StringPool.EMPTY; + } + return str.substring(pos + separator.length()); + } - /** - * 截取分隔字符串之后的字符串,不包括分隔字符串
- * 如果给定的字符串为空串(null或""),返回原字符串
- * 如果分隔字符串为空串(null或""),则返回空串,如果分隔字符串未找到,返回空串 - * - * 栗子: - * - *
-     * StringUtil.subAfter(null, *)      = null
-     * StringUtil.subAfter("", *)        = ""
-     * StringUtil.subAfter(*, null)      = ""
-     * StringUtil.subAfter("abc", "a")   = "bc"
-     * StringUtil.subAfter("abcba", "b") = "cba"
-     * StringUtil.subAfter("abc", "c")   = ""
-     * StringUtil.subAfter("abc", "d")   = ""
-     * StringUtil.subAfter("abc", "")    = "abc"
-     * 
- * - * @param string 被查找的字符串 - * @param separator 分隔字符串(不包括) - * @param isLastSeparator 是否查找最后一个分隔字符串(多次出现分隔字符串时选取最后一个),true为选取最后一个 - * @return 切割后的字符串 - * @since 3.1.1 - */ - public static String subAfter(CharSequence string, CharSequence separator, boolean isLastSeparator) { - if (isEmpty(string)) { - return null == string ? null : string.toString(); - } - if (separator == null) { - return StringPool.EMPTY; - } - final String str = string.toString(); - final String sep = separator.toString(); - final int pos = isLastSeparator ? str.lastIndexOf(sep) : str.indexOf(sep); - if (pos == INDEX_NOT_FOUND) { - return StringPool.EMPTY; - } - return str.substring(pos + separator.length()); - } + /** + * 截取指定字符串中间部分,不包括标识字符串
+ *

+ * 栗子: + * + *

+	 * StringUtil.subBetween("wx[b]yz", "[", "]") = "b"
+	 * StringUtil.subBetween(null, *, *)          = null
+	 * StringUtil.subBetween(*, null, *)          = null
+	 * StringUtil.subBetween(*, *, null)          = null
+	 * StringUtil.subBetween("", "", "")          = ""
+	 * StringUtil.subBetween("", "", "]")         = null
+	 * StringUtil.subBetween("", "[", "]")        = null
+	 * StringUtil.subBetween("yabcz", "", "")     = ""
+	 * StringUtil.subBetween("yabcz", "y", "z")   = "abc"
+	 * StringUtil.subBetween("yabczyabcz", "y", "z")   = "abc"
+	 * 
+ * + * @param str 被切割的字符串 + * @param before 截取开始的字符串标识 + * @param after 截取到的字符串标识 + * @return 截取后的字符串 + * @since 3.1.1 + */ + public static String subBetween(CharSequence str, CharSequence before, CharSequence after) { + if (str == null || before == null || after == null) { + return null; + } - /** - * 截取指定字符串中间部分,不包括标识字符串
- * - * 栗子: - * - *
-     * StringUtil.subBetween("wx[b]yz", "[", "]") = "b"
-     * StringUtil.subBetween(null, *, *)          = null
-     * StringUtil.subBetween(*, null, *)          = null
-     * StringUtil.subBetween(*, *, null)          = null
-     * StringUtil.subBetween("", "", "")          = ""
-     * StringUtil.subBetween("", "", "]")         = null
-     * StringUtil.subBetween("", "[", "]")        = null
-     * StringUtil.subBetween("yabcz", "", "")     = ""
-     * StringUtil.subBetween("yabcz", "y", "z")   = "abc"
-     * StringUtil.subBetween("yabczyabcz", "y", "z")   = "abc"
-     * 
- * - * @param str 被切割的字符串 - * @param before 截取开始的字符串标识 - * @param after 截取到的字符串标识 - * @return 截取后的字符串 - * @since 3.1.1 - */ - public static String subBetween(CharSequence str, CharSequence before, CharSequence after) { - if (str == null || before == null || after == null) { - return null; - } + final String str2 = str.toString(); + final String before2 = before.toString(); + final String after2 = after.toString(); - final String str2 = str.toString(); - final String before2 = before.toString(); - final String after2 = after.toString(); + final int start = str2.indexOf(before2); + if (start != INDEX_NOT_FOUND) { + final int end = str2.indexOf(after2, start + before2.length()); + if (end != INDEX_NOT_FOUND) { + return str2.substring(start + before2.length(), end); + } + } + return null; + } - final int start = str2.indexOf(before2); - if (start != INDEX_NOT_FOUND) { - final int end = str2.indexOf(after2, start + before2.length()); - if (end != INDEX_NOT_FOUND) { - return str2.substring(start + before2.length(), end); - } - } - return null; - } + /** + * 截取指定字符串中间部分,不包括标识字符串
+ *

+ * 栗子: + * + *

+	 * StringUtil.subBetween(null, *)            = null
+	 * StringUtil.subBetween("", "")             = ""
+	 * StringUtil.subBetween("", "tag")          = null
+	 * StringUtil.subBetween("tagabctag", null)  = null
+	 * StringUtil.subBetween("tagabctag", "")    = ""
+	 * StringUtil.subBetween("tagabctag", "tag") = "abc"
+	 * 
+ * + * @param str 被切割的字符串 + * @param beforeAndAfter 截取开始和结束的字符串标识 + * @return 截取后的字符串 + * @since 3.1.1 + */ + public static String subBetween(CharSequence str, CharSequence beforeAndAfter) { + return subBetween(str, beforeAndAfter, beforeAndAfter); + } - /** - * 截取指定字符串中间部分,不包括标识字符串
- * - * 栗子: - * - *
-     * StringUtil.subBetween(null, *)            = null
-     * StringUtil.subBetween("", "")             = ""
-     * StringUtil.subBetween("", "tag")          = null
-     * StringUtil.subBetween("tagabctag", null)  = null
-     * StringUtil.subBetween("tagabctag", "")    = ""
-     * StringUtil.subBetween("tagabctag", "tag") = "abc"
-     * 
- * - * @param str 被切割的字符串 - * @param beforeAndAfter 截取开始和结束的字符串标识 - * @return 截取后的字符串 - * @since 3.1.1 - */ - public static String subBetween(CharSequence str, CharSequence beforeAndAfter) { - return subBetween(str, beforeAndAfter, beforeAndAfter); - } + /** + * 去掉指定前缀 + * + * @param str 字符串 + * @param prefix 前缀 + * @return 切掉后的字符串,若前缀不是 preffix, 返回原字符串 + */ + public static String removePrefix(CharSequence str, CharSequence prefix) { + if (isEmpty(str) || isEmpty(prefix)) { + return StringPool.EMPTY; + } - /** - * 去掉指定前缀 - * - * @param str 字符串 - * @param prefix 前缀 - * @return 切掉后的字符串,若前缀不是 preffix, 返回原字符串 - */ - public static String removePrefix(CharSequence str, CharSequence prefix) { - if (isEmpty(str) || isEmpty(prefix)) { - return StringPool.EMPTY; - } + final String str2 = str.toString(); + if (str2.startsWith(prefix.toString())) { + return subSuf(str2, prefix.length());// 截取后半段 + } + return str2; + } - final String str2 = str.toString(); - if (str2.startsWith(prefix.toString())) { - return subSuf(str2, prefix.length());// 截取后半段 - } - return str2; - } + /** + * 忽略大小写去掉指定前缀 + * + * @param str 字符串 + * @param prefix 前缀 + * @return 切掉后的字符串,若前缀不是 prefix, 返回原字符串 + */ + public static String removePrefixIgnoreCase(CharSequence str, CharSequence prefix) { + if (isEmpty(str) || isEmpty(prefix)) { + return StringPool.EMPTY; + } - /** - * 忽略大小写去掉指定前缀 - * - * @param str 字符串 - * @param prefix 前缀 - * @return 切掉后的字符串,若前缀不是 prefix, 返回原字符串 - */ - public static String removePrefixIgnoreCase(CharSequence str, CharSequence prefix) { - if (isEmpty(str) || isEmpty(prefix)) { - return StringPool.EMPTY; - } + final String str2 = str.toString(); + if (str2.toLowerCase().startsWith(prefix.toString().toLowerCase())) { + return subSuf(str2, prefix.length());// 截取后半段 + } + return str2; + } - final String str2 = str.toString(); - if (str2.toLowerCase().startsWith(prefix.toString().toLowerCase())) { - return subSuf(str2, prefix.length());// 截取后半段 - } - return str2; - } + /** + * 去掉指定后缀 + * + * @param str 字符串 + * @param suffix 后缀 + * @return 切掉后的字符串,若后缀不是 suffix, 返回原字符串 + */ + public static String removeSuffix(CharSequence str, CharSequence suffix) { + if (isEmpty(str) || isEmpty(suffix)) { + return StringPool.EMPTY; + } - /** - * 去掉指定后缀 - * - * @param str 字符串 - * @param suffix 后缀 - * @return 切掉后的字符串,若后缀不是 suffix, 返回原字符串 - */ - public static String removeSuffix(CharSequence str, CharSequence suffix) { - if (isEmpty(str) || isEmpty(suffix)) { - return StringPool.EMPTY; - } + final String str2 = str.toString(); + if (str2.endsWith(suffix.toString())) { + return subPre(str2, str2.length() - suffix.length());// 截取前半段 + } + return str2; + } - final String str2 = str.toString(); - if (str2.endsWith(suffix.toString())) { - return subPre(str2, str2.length() - suffix.length());// 截取前半段 - } - return str2; - } + /** + * 去掉指定后缀,并小写首字母 + * + * @param str 字符串 + * @param suffix 后缀 + * @return 切掉后的字符串,若后缀不是 suffix, 返回原字符串 + */ + public static String removeSufAndLowerFirst(CharSequence str, CharSequence suffix) { + return lowerFirst(removeSuffix(str, suffix)); + } - /** - * 去掉指定后缀,并小写首字母 - * - * @param str 字符串 - * @param suffix 后缀 - * @return 切掉后的字符串,若后缀不是 suffix, 返回原字符串 - */ - public static String removeSufAndLowerFirst(CharSequence str, CharSequence suffix) { - return lowerFirst(removeSuffix(str, suffix)); - } + /** + * 忽略大小写去掉指定后缀 + * + * @param str 字符串 + * @param suffix 后缀 + * @return 切掉后的字符串,若后缀不是 suffix, 返回原字符串 + */ + public static String removeSuffixIgnoreCase(CharSequence str, CharSequence suffix) { + if (isEmpty(str) || isEmpty(suffix)) { + return StringPool.EMPTY; + } - /** - * 忽略大小写去掉指定后缀 - * - * @param str 字符串 - * @param suffix 后缀 - * @return 切掉后的字符串,若后缀不是 suffix, 返回原字符串 - */ - public static String removeSuffixIgnoreCase(CharSequence str, CharSequence suffix) { - if (isEmpty(str) || isEmpty(suffix)) { - return StringPool.EMPTY; - } - - final String str2 = str.toString(); - if (str2.toLowerCase().endsWith(suffix.toString().toLowerCase())) { - return subPre(str2, str2.length() - suffix.length()); - } - return str2; - } + final String str2 = str.toString(); + if (str2.toLowerCase().endsWith(suffix.toString().toLowerCase())) { + return subPre(str2, str2.length() - suffix.length()); + } + return str2; + } /** * 首字母变小写 + * * @param str 字符串 * @return {String} */ @@ -834,6 +840,7 @@ public class StringUtil extends org.springframework.util.StringUtils { /** * 首字母变大写 + * * @param str 字符串 * @return {String} */ @@ -847,489 +854,489 @@ public class StringUtil extends org.springframework.util.StringUtils { return str; } - /** - * 切割指定位置之前部分的字符串 - * - * @param string 字符串 - * @param toIndex 切割到的位置(不包括) - * @return 切割后的剩余的前半部分字符串 - */ - public static String subPre(CharSequence string, int toIndex) { - return sub(string, 0, toIndex); - } + /** + * 切割指定位置之前部分的字符串 + * + * @param string 字符串 + * @param toIndex 切割到的位置(不包括) + * @return 切割后的剩余的前半部分字符串 + */ + public static String subPre(CharSequence string, int toIndex) { + return sub(string, 0, toIndex); + } - /** - * 切割指定位置之后部分的字符串 - * - * @param string 字符串 - * @param fromIndex 切割开始的位置(包括) - * @return 切割后后剩余的后半部分字符串 - */ - public static String subSuf(CharSequence string, int fromIndex) { - if (isEmpty(string)) { - return null; - } - return sub(string, fromIndex, string.length()); - } + /** + * 切割指定位置之后部分的字符串 + * + * @param string 字符串 + * @param fromIndex 切割开始的位置(包括) + * @return 切割后后剩余的后半部分字符串 + */ + public static String subSuf(CharSequence string, int fromIndex) { + if (isEmpty(string)) { + return null; + } + return sub(string, fromIndex, string.length()); + } - /** - * 指定范围内查找指定字符 - * - * @param str 字符串 - * @param searchChar 被查找的字符 - * @return 位置 - */ - public static int indexOf(final CharSequence str, char searchChar) { - return indexOf(str, searchChar, 0); - } + /** + * 指定范围内查找指定字符 + * + * @param str 字符串 + * @param searchChar 被查找的字符 + * @return 位置 + */ + public static int indexOf(final CharSequence str, char searchChar) { + return indexOf(str, searchChar, 0); + } - /** - * 指定范围内查找指定字符 - * - * @param str 字符串 - * @param searchChar 被查找的字符 - * @param start 起始位置,如果小于0,从0开始查找 - * @return 位置 - */ - public static int indexOf(final CharSequence str, char searchChar, int start) { - if (str instanceof String) { - return ((String) str).indexOf(searchChar, start); - } else { - return indexOf(str, searchChar, start, -1); - } - } + /** + * 指定范围内查找指定字符 + * + * @param str 字符串 + * @param searchChar 被查找的字符 + * @param start 起始位置,如果小于0,从0开始查找 + * @return 位置 + */ + public static int indexOf(final CharSequence str, char searchChar, int start) { + if (str instanceof String) { + return ((String) str).indexOf(searchChar, start); + } else { + return indexOf(str, searchChar, start, -1); + } + } - /** - * 指定范围内查找指定字符 - * - * @param str 字符串 - * @param searchChar 被查找的字符 - * @param start 起始位置,如果小于0,从0开始查找 - * @param end 终止位置,如果超过str.length()则默认查找到字符串末尾 - * @return 位置 - */ - public static int indexOf(final CharSequence str, char searchChar, int start, int end) { - final int len = str.length(); - if (start < 0 || start > len) { - start = 0; - } - if (end > len || end < 0) { - end = len; - } - for (int i = start; i < end; i++) { - if (str.charAt(i) == searchChar) { - return i; - } - } - return -1; - } + /** + * 指定范围内查找指定字符 + * + * @param str 字符串 + * @param searchChar 被查找的字符 + * @param start 起始位置,如果小于0,从0开始查找 + * @param end 终止位置,如果超过str.length()则默认查找到字符串末尾 + * @return 位置 + */ + public static int indexOf(final CharSequence str, char searchChar, int start, int end) { + final int len = str.length(); + if (start < 0 || start > len) { + start = 0; + } + if (end > len || end < 0) { + end = len; + } + for (int i = start; i < end; i++) { + if (str.charAt(i) == searchChar) { + return i; + } + } + return -1; + } - /** - * 指定范围内查找字符串,忽略大小写
- * - *
-     * StringUtil.indexOfIgnoreCase(null, *, *)          = -1
-     * StringUtil.indexOfIgnoreCase(*, null, *)          = -1
-     * StringUtil.indexOfIgnoreCase("", "", 0)           = 0
-     * StringUtil.indexOfIgnoreCase("aabaabaa", "A", 0)  = 0
-     * StringUtil.indexOfIgnoreCase("aabaabaa", "B", 0)  = 2
-     * StringUtil.indexOfIgnoreCase("aabaabaa", "AB", 0) = 1
-     * StringUtil.indexOfIgnoreCase("aabaabaa", "B", 3)  = 5
-     * StringUtil.indexOfIgnoreCase("aabaabaa", "B", 9)  = -1
-     * StringUtil.indexOfIgnoreCase("aabaabaa", "B", -1) = 2
-     * StringUtil.indexOfIgnoreCase("aabaabaa", "", 2)   = 2
-     * StringUtil.indexOfIgnoreCase("abc", "", 9)        = -1
-     * 
- * - * @param str 字符串 - * @param searchStr 需要查找位置的字符串 - * @return 位置 - * @since 3.2.1 - */ - public static int indexOfIgnoreCase(final CharSequence str, final CharSequence searchStr) { - return indexOfIgnoreCase(str, searchStr, 0); - } + /** + * 指定范围内查找字符串,忽略大小写
+ * + *
+	 * StringUtil.indexOfIgnoreCase(null, *, *)          = -1
+	 * StringUtil.indexOfIgnoreCase(*, null, *)          = -1
+	 * StringUtil.indexOfIgnoreCase("", "", 0)           = 0
+	 * StringUtil.indexOfIgnoreCase("aabaabaa", "A", 0)  = 0
+	 * StringUtil.indexOfIgnoreCase("aabaabaa", "B", 0)  = 2
+	 * StringUtil.indexOfIgnoreCase("aabaabaa", "AB", 0) = 1
+	 * StringUtil.indexOfIgnoreCase("aabaabaa", "B", 3)  = 5
+	 * StringUtil.indexOfIgnoreCase("aabaabaa", "B", 9)  = -1
+	 * StringUtil.indexOfIgnoreCase("aabaabaa", "B", -1) = 2
+	 * StringUtil.indexOfIgnoreCase("aabaabaa", "", 2)   = 2
+	 * StringUtil.indexOfIgnoreCase("abc", "", 9)        = -1
+	 * 
+ * + * @param str 字符串 + * @param searchStr 需要查找位置的字符串 + * @return 位置 + * @since 3.2.1 + */ + public static int indexOfIgnoreCase(final CharSequence str, final CharSequence searchStr) { + return indexOfIgnoreCase(str, searchStr, 0); + } - /** - * 指定范围内查找字符串 - * - *
-     * StringUtil.indexOfIgnoreCase(null, *, *)          = -1
-     * StringUtil.indexOfIgnoreCase(*, null, *)          = -1
-     * StringUtil.indexOfIgnoreCase("", "", 0)           = 0
-     * StringUtil.indexOfIgnoreCase("aabaabaa", "A", 0)  = 0
-     * StringUtil.indexOfIgnoreCase("aabaabaa", "B", 0)  = 2
-     * StringUtil.indexOfIgnoreCase("aabaabaa", "AB", 0) = 1
-     * StringUtil.indexOfIgnoreCase("aabaabaa", "B", 3)  = 5
-     * StringUtil.indexOfIgnoreCase("aabaabaa", "B", 9)  = -1
-     * StringUtil.indexOfIgnoreCase("aabaabaa", "B", -1) = 2
-     * StringUtil.indexOfIgnoreCase("aabaabaa", "", 2)   = 2
-     * StringUtil.indexOfIgnoreCase("abc", "", 9)        = -1
-     * 
- * - * @param str 字符串 - * @param searchStr 需要查找位置的字符串 - * @param fromIndex 起始位置 - * @return 位置 - * @since 3.2.1 - */ - public static int indexOfIgnoreCase(final CharSequence str, final CharSequence searchStr, int fromIndex) { - return indexOf(str, searchStr, fromIndex, true); - } + /** + * 指定范围内查找字符串 + * + *
+	 * StringUtil.indexOfIgnoreCase(null, *, *)          = -1
+	 * StringUtil.indexOfIgnoreCase(*, null, *)          = -1
+	 * StringUtil.indexOfIgnoreCase("", "", 0)           = 0
+	 * StringUtil.indexOfIgnoreCase("aabaabaa", "A", 0)  = 0
+	 * StringUtil.indexOfIgnoreCase("aabaabaa", "B", 0)  = 2
+	 * StringUtil.indexOfIgnoreCase("aabaabaa", "AB", 0) = 1
+	 * StringUtil.indexOfIgnoreCase("aabaabaa", "B", 3)  = 5
+	 * StringUtil.indexOfIgnoreCase("aabaabaa", "B", 9)  = -1
+	 * StringUtil.indexOfIgnoreCase("aabaabaa", "B", -1) = 2
+	 * StringUtil.indexOfIgnoreCase("aabaabaa", "", 2)   = 2
+	 * StringUtil.indexOfIgnoreCase("abc", "", 9)        = -1
+	 * 
+ * + * @param str 字符串 + * @param searchStr 需要查找位置的字符串 + * @param fromIndex 起始位置 + * @return 位置 + * @since 3.2.1 + */ + public static int indexOfIgnoreCase(final CharSequence str, final CharSequence searchStr, int fromIndex) { + return indexOf(str, searchStr, fromIndex, true); + } - /** - * 指定范围内反向查找字符串 - * - * @param str 字符串 - * @param searchStr 需要查找位置的字符串 - * @param fromIndex 起始位置 - * @param ignoreCase 是否忽略大小写 - * @return 位置 - * @since 3.2.1 - */ - public static int indexOf(final CharSequence str, CharSequence searchStr, int fromIndex, boolean ignoreCase) { - if (str == null || searchStr == null) { - return INDEX_NOT_FOUND; - } - if (fromIndex < 0) { - fromIndex = 0; - } + /** + * 指定范围内反向查找字符串 + * + * @param str 字符串 + * @param searchStr 需要查找位置的字符串 + * @param fromIndex 起始位置 + * @param ignoreCase 是否忽略大小写 + * @return 位置 + * @since 3.2.1 + */ + public static int indexOf(final CharSequence str, CharSequence searchStr, int fromIndex, boolean ignoreCase) { + if (str == null || searchStr == null) { + return INDEX_NOT_FOUND; + } + if (fromIndex < 0) { + fromIndex = 0; + } - final int endLimit = str.length() - searchStr.length() + 1; - if (fromIndex > endLimit) { - return INDEX_NOT_FOUND; - } - if (searchStr.length() == 0) { - return fromIndex; - } + final int endLimit = str.length() - searchStr.length() + 1; + if (fromIndex > endLimit) { + return INDEX_NOT_FOUND; + } + if (searchStr.length() == 0) { + return fromIndex; + } - if (false == ignoreCase) { - // 不忽略大小写调用JDK方法 - return str.toString().indexOf(searchStr.toString(), fromIndex); - } + if (false == ignoreCase) { + // 不忽略大小写调用JDK方法 + return str.toString().indexOf(searchStr.toString(), fromIndex); + } - for (int i = fromIndex; i < endLimit; i++) { - if (isSubEquals(str, i, searchStr, 0, searchStr.length(), true)) { - return i; - } - } - return INDEX_NOT_FOUND; - } + for (int i = fromIndex; i < endLimit; i++) { + if (isSubEquals(str, i, searchStr, 0, searchStr.length(), true)) { + return i; + } + } + return INDEX_NOT_FOUND; + } - /** - * 指定范围内查找字符串,忽略大小写
- * - * @param str 字符串 - * @param searchStr 需要查找位置的字符串 - * @return 位置 - * @since 3.2.1 - */ - public static int lastIndexOfIgnoreCase(final CharSequence str, final CharSequence searchStr) { - return lastIndexOfIgnoreCase(str, searchStr, str.length()); - } + /** + * 指定范围内查找字符串,忽略大小写
+ * + * @param str 字符串 + * @param searchStr 需要查找位置的字符串 + * @return 位置 + * @since 3.2.1 + */ + public static int lastIndexOfIgnoreCase(final CharSequence str, final CharSequence searchStr) { + return lastIndexOfIgnoreCase(str, searchStr, str.length()); + } - /** - * 指定范围内查找字符串,忽略大小写
- * - * @param str 字符串 - * @param searchStr 需要查找位置的字符串 - * @param fromIndex 起始位置,从后往前计数 - * @return 位置 - * @since 3.2.1 - */ - public static int lastIndexOfIgnoreCase(final CharSequence str, final CharSequence searchStr, int fromIndex) { - return lastIndexOf(str, searchStr, fromIndex, true); - } + /** + * 指定范围内查找字符串,忽略大小写
+ * + * @param str 字符串 + * @param searchStr 需要查找位置的字符串 + * @param fromIndex 起始位置,从后往前计数 + * @return 位置 + * @since 3.2.1 + */ + public static int lastIndexOfIgnoreCase(final CharSequence str, final CharSequence searchStr, int fromIndex) { + return lastIndexOf(str, searchStr, fromIndex, true); + } - /** - * 指定范围内查找字符串
- * - * @param str 字符串 - * @param searchStr 需要查找位置的字符串 - * @param fromIndex 起始位置,从后往前计数 - * @param ignoreCase 是否忽略大小写 - * @return 位置 - * @since 3.2.1 - */ - public static int lastIndexOf(final CharSequence str, final CharSequence searchStr, int fromIndex, boolean ignoreCase) { - if (str == null || searchStr == null) { - return INDEX_NOT_FOUND; - } - if (fromIndex < 0) { - fromIndex = 0; - } - fromIndex = Math.min(fromIndex, str.length()); + /** + * 指定范围内查找字符串
+ * + * @param str 字符串 + * @param searchStr 需要查找位置的字符串 + * @param fromIndex 起始位置,从后往前计数 + * @param ignoreCase 是否忽略大小写 + * @return 位置 + * @since 3.2.1 + */ + public static int lastIndexOf(final CharSequence str, final CharSequence searchStr, int fromIndex, boolean ignoreCase) { + if (str == null || searchStr == null) { + return INDEX_NOT_FOUND; + } + if (fromIndex < 0) { + fromIndex = 0; + } + fromIndex = Math.min(fromIndex, str.length()); - if (searchStr.length() == 0) { - return fromIndex; - } + if (searchStr.length() == 0) { + return fromIndex; + } - if (false == ignoreCase) { - // 不忽略大小写调用JDK方法 - return str.toString().lastIndexOf(searchStr.toString(), fromIndex); - } + if (false == ignoreCase) { + // 不忽略大小写调用JDK方法 + return str.toString().lastIndexOf(searchStr.toString(), fromIndex); + } - for (int i = fromIndex; i > 0; i--) { - if (isSubEquals(str, i, searchStr, 0, searchStr.length(), true)) { - return i; - } - } - return INDEX_NOT_FOUND; - } + for (int i = fromIndex; i > 0; i--) { + if (isSubEquals(str, i, searchStr, 0, searchStr.length(), true)) { + return i; + } + } + return INDEX_NOT_FOUND; + } - /** - * 返回字符串 searchStr 在字符串 str 中第 ordinal 次出现的位置。
- * 如果 str=null 或 searchStr=null 或 ordinal<=0 则返回-1
- * 此方法来自:Apache-Commons-Lang - *

- * 栗子(*代表任意字符): - * - *

-     * StringUtil.ordinalIndexOf(null, *, *)          = -1
-     * StringUtil.ordinalIndexOf(*, null, *)          = -1
-     * StringUtil.ordinalIndexOf("", "", *)           = 0
-     * StringUtil.ordinalIndexOf("aabaabaa", "a", 1)  = 0
-     * StringUtil.ordinalIndexOf("aabaabaa", "a", 2)  = 1
-     * StringUtil.ordinalIndexOf("aabaabaa", "b", 1)  = 2
-     * StringUtil.ordinalIndexOf("aabaabaa", "b", 2)  = 5
-     * StringUtil.ordinalIndexOf("aabaabaa", "ab", 1) = 1
-     * StringUtil.ordinalIndexOf("aabaabaa", "ab", 2) = 4
-     * StringUtil.ordinalIndexOf("aabaabaa", "", 1)   = 0
-     * StringUtil.ordinalIndexOf("aabaabaa", "", 2)   = 0
-     * 
- * - * @param str 被检查的字符串,可以为null - * @param searchStr 被查找的字符串,可以为null - * @param ordinal 第几次出现的位置 - * @return 查找到的位置 - * @since 3.2.3 - */ - public static int ordinalIndexOf(String str, String searchStr, int ordinal) { - if (str == null || searchStr == null || ordinal <= 0) { - return INDEX_NOT_FOUND; - } - if (searchStr.length() == 0) { - return 0; - } - int found = 0; - int index = INDEX_NOT_FOUND; - do { - index = str.indexOf(searchStr, index + 1); - if (index < 0) { - return index; - } - found++; - } while (found < ordinal); - return index; - } + /** + * 返回字符串 searchStr 在字符串 str 中第 ordinal 次出现的位置。
+ * 如果 str=null 或 searchStr=null 或 ordinal<=0 则返回-1
+ * 此方法来自:Apache-Commons-Lang + *

+ * 栗子(*代表任意字符): + * + *

+	 * StringUtil.ordinalIndexOf(null, *, *)          = -1
+	 * StringUtil.ordinalIndexOf(*, null, *)          = -1
+	 * StringUtil.ordinalIndexOf("", "", *)           = 0
+	 * StringUtil.ordinalIndexOf("aabaabaa", "a", 1)  = 0
+	 * StringUtil.ordinalIndexOf("aabaabaa", "a", 2)  = 1
+	 * StringUtil.ordinalIndexOf("aabaabaa", "b", 1)  = 2
+	 * StringUtil.ordinalIndexOf("aabaabaa", "b", 2)  = 5
+	 * StringUtil.ordinalIndexOf("aabaabaa", "ab", 1) = 1
+	 * StringUtil.ordinalIndexOf("aabaabaa", "ab", 2) = 4
+	 * StringUtil.ordinalIndexOf("aabaabaa", "", 1)   = 0
+	 * StringUtil.ordinalIndexOf("aabaabaa", "", 2)   = 0
+	 * 
+ * + * @param str 被检查的字符串,可以为null + * @param searchStr 被查找的字符串,可以为null + * @param ordinal 第几次出现的位置 + * @return 查找到的位置 + * @since 3.2.3 + */ + public static int ordinalIndexOf(String str, String searchStr, int ordinal) { + if (str == null || searchStr == null || ordinal <= 0) { + return INDEX_NOT_FOUND; + } + if (searchStr.length() == 0) { + return 0; + } + int found = 0; + int index = INDEX_NOT_FOUND; + do { + index = str.indexOf(searchStr, index + 1); + if (index < 0) { + return index; + } + found++; + } while (found < ordinal); + return index; + } - /** - * 截取两个字符串的不同部分(长度一致),判断截取的子串是否相同
- * 任意一个字符串为null返回false - * - * @param str1 第一个字符串 - * @param start1 第一个字符串开始的位置 - * @param str2 第二个字符串 - * @param start2 第二个字符串开始的位置 - * @param length 截取长度 - * @param ignoreCase 是否忽略大小写 - * @return 子串是否相同 - * @since 3.2.1 - */ - public static boolean isSubEquals(CharSequence str1, int start1, CharSequence str2, int start2, int length, boolean ignoreCase) { - if (null == str1 || null == str2) { - return false; - } + /** + * 截取两个字符串的不同部分(长度一致),判断截取的子串是否相同
+ * 任意一个字符串为null返回false + * + * @param str1 第一个字符串 + * @param start1 第一个字符串开始的位置 + * @param str2 第二个字符串 + * @param start2 第二个字符串开始的位置 + * @param length 截取长度 + * @param ignoreCase 是否忽略大小写 + * @return 子串是否相同 + * @since 3.2.1 + */ + public static boolean isSubEquals(CharSequence str1, int start1, CharSequence str2, int start2, int length, boolean ignoreCase) { + if (null == str1 || null == str2) { + return false; + } - return str1.toString().regionMatches(ignoreCase, start1, str2.toString(), start2, length); - } + return str1.toString().regionMatches(ignoreCase, start1, str2.toString(), start2, length); + } - /** - * 比较两个字符串(大小写敏感)。 - * - *
-     * equalsIgnoreCase(null, null)   = true
-     * equalsIgnoreCase(null, "abc")  = false
-     * equalsIgnoreCase("abc", null)  = false
-     * equalsIgnoreCase("abc", "abc") = true
-     * equalsIgnoreCase("abc", "ABC") = true
-     * 
- * - * @param str1 要比较的字符串1 - * @param str2 要比较的字符串2 - * @return 如果两个字符串相同,或者都是null,则返回true - */ - public static boolean equals(CharSequence str1, CharSequence str2) { - return equals(str1, str2, false); - } + /** + * 比较两个字符串(大小写敏感)。 + * + *
+	 * equalsIgnoreCase(null, null)   = true
+	 * equalsIgnoreCase(null, "abc")  = false
+	 * equalsIgnoreCase("abc", null)  = false
+	 * equalsIgnoreCase("abc", "abc") = true
+	 * equalsIgnoreCase("abc", "ABC") = true
+	 * 
+ * + * @param str1 要比较的字符串1 + * @param str2 要比较的字符串2 + * @return 如果两个字符串相同,或者都是null,则返回true + */ + public static boolean equals(CharSequence str1, CharSequence str2) { + return equals(str1, str2, false); + } - /** - * 比较两个字符串(大小写不敏感)。 - * - *
-     * equalsIgnoreCase(null, null)   = true
-     * equalsIgnoreCase(null, "abc")  = false
-     * equalsIgnoreCase("abc", null)  = false
-     * equalsIgnoreCase("abc", "abc") = true
-     * equalsIgnoreCase("abc", "ABC") = true
-     * 
- * - * @param str1 要比较的字符串1 - * @param str2 要比较的字符串2 - * @return 如果两个字符串相同,或者都是null,则返回true - */ - public static boolean equalsIgnoreCase(CharSequence str1, CharSequence str2) { - return equals(str1, str2, true); - } + /** + * 比较两个字符串(大小写不敏感)。 + * + *
+	 * equalsIgnoreCase(null, null)   = true
+	 * equalsIgnoreCase(null, "abc")  = false
+	 * equalsIgnoreCase("abc", null)  = false
+	 * equalsIgnoreCase("abc", "abc") = true
+	 * equalsIgnoreCase("abc", "ABC") = true
+	 * 
+ * + * @param str1 要比较的字符串1 + * @param str2 要比较的字符串2 + * @return 如果两个字符串相同,或者都是null,则返回true + */ + public static boolean equalsIgnoreCase(CharSequence str1, CharSequence str2) { + return equals(str1, str2, true); + } - /** - * 比较两个字符串是否相等。 - * - * @param str1 要比较的字符串1 - * @param str2 要比较的字符串2 - * @param ignoreCase 是否忽略大小写 - * @return 如果两个字符串相同,或者都是null,则返回true - * @since 3.2.0 - */ - public static boolean equals(CharSequence str1, CharSequence str2, boolean ignoreCase) { - if (null == str1) { - // 只有两个都为null才判断相等 - return str2 == null; - } - if (null == str2) { - // 字符串2空,字符串1非空,直接false - return false; - } + /** + * 比较两个字符串是否相等。 + * + * @param str1 要比较的字符串1 + * @param str2 要比较的字符串2 + * @param ignoreCase 是否忽略大小写 + * @return 如果两个字符串相同,或者都是null,则返回true + * @since 3.2.0 + */ + public static boolean equals(CharSequence str1, CharSequence str2, boolean ignoreCase) { + if (null == str1) { + // 只有两个都为null才判断相等 + return str2 == null; + } + if (null == str2) { + // 字符串2空,字符串1非空,直接false + return false; + } - if (ignoreCase) { - return str1.toString().equalsIgnoreCase(str2.toString()); - } else { - return str1.equals(str2); - } - } + if (ignoreCase) { + return str1.toString().equalsIgnoreCase(str2.toString()); + } else { + return str1.equals(str2); + } + } - /** - * 创建StringBuilder对象 - * - * @return StringBuilder对象 - */ - public static StringBuilder builder() { - return new StringBuilder(); - } + /** + * 创建StringBuilder对象 + * + * @return StringBuilder对象 + */ + public static StringBuilder builder() { + return new StringBuilder(); + } - /** - * 创建StringBuilder对象 - * - * @param capacity 初始大小 - * @return StringBuilder对象 - */ - public static StringBuilder builder(int capacity) { - return new StringBuilder(capacity); - } + /** + * 创建StringBuilder对象 + * + * @param capacity 初始大小 + * @return StringBuilder对象 + */ + public static StringBuilder builder(int capacity) { + return new StringBuilder(capacity); + } - /** - * 创建StringBuilder对象 - * - * @param strs 初始字符串列表 - * @return StringBuilder对象 - */ - public static StringBuilder builder(CharSequence... strs) { - final StringBuilder sb = new StringBuilder(); - for (CharSequence str : strs) { - sb.append(str); - } - return sb; - } + /** + * 创建StringBuilder对象 + * + * @param strs 初始字符串列表 + * @return StringBuilder对象 + */ + public static StringBuilder builder(CharSequence... strs) { + final StringBuilder sb = new StringBuilder(); + for (CharSequence str : strs) { + sb.append(str); + } + return sb; + } - /** - * 创建StringBuilder对象 - * - * @param strs 初始字符串列表 - * @return StringBuilder对象 - */ - public static StringBuilder appendBuilder(StringBuilder sb, CharSequence... strs) { - for (CharSequence str : strs) { - sb.append(str); - } - return sb; - } + /** + * 创建StringBuilder对象 + * + * @param strs 初始字符串列表 + * @return StringBuilder对象 + */ + public static StringBuilder appendBuilder(StringBuilder sb, CharSequence... strs) { + for (CharSequence str : strs) { + sb.append(str); + } + return sb; + } - /** - * 获得StringReader - * - * @param str 字符串 - * @return StringReader - */ - public static StringReader getReader(CharSequence str) { - if (null == str) { - return null; - } - return new StringReader(str.toString()); - } + /** + * 获得StringReader + * + * @param str 字符串 + * @return StringReader + */ + public static StringReader getReader(CharSequence str) { + if (null == str) { + return null; + } + return new StringReader(str.toString()); + } - /** - * 获得StringWriter - * - * @return StringWriter - */ - public static StringWriter getWriter() { - return new StringWriter(); - } + /** + * 获得StringWriter + * + * @return StringWriter + */ + public static StringWriter getWriter() { + return new StringWriter(); + } - /** - * 统计指定内容中包含指定字符串的数量
- * 参数为 {@code null} 或者 "" 返回 {@code 0}. - * - *
-     * StringUtil.count(null, *)       = 0
-     * StringUtil.count("", *)         = 0
-     * StringUtil.count("abba", null)  = 0
-     * StringUtil.count("abba", "")    = 0
-     * StringUtil.count("abba", "a")   = 2
-     * StringUtil.count("abba", "ab")  = 1
-     * StringUtil.count("abba", "xxx") = 0
-     * 
- * - * @param content 被查找的字符串 - * @param strForSearch 需要查找的字符串 - * @return 查找到的个数 - */ - public static int count(CharSequence content, CharSequence strForSearch) { - if (Func.hasEmpty(content, strForSearch) || strForSearch.length() > content.length()) { - return 0; - } + /** + * 统计指定内容中包含指定字符串的数量
+ * 参数为 {@code null} 或者 "" 返回 {@code 0}. + * + *
+	 * StringUtil.count(null, *)       = 0
+	 * StringUtil.count("", *)         = 0
+	 * StringUtil.count("abba", null)  = 0
+	 * StringUtil.count("abba", "")    = 0
+	 * StringUtil.count("abba", "a")   = 2
+	 * StringUtil.count("abba", "ab")  = 1
+	 * StringUtil.count("abba", "xxx") = 0
+	 * 
+ * + * @param content 被查找的字符串 + * @param strForSearch 需要查找的字符串 + * @return 查找到的个数 + */ + public static int count(CharSequence content, CharSequence strForSearch) { + if (Func.hasEmpty(content, strForSearch) || strForSearch.length() > content.length()) { + return 0; + } - int count = 0; - int idx = 0; - final String content2 = content.toString(); - final String strForSearch2 = strForSearch.toString(); - while ((idx = content2.indexOf(strForSearch2, idx)) > -1) { - count++; - idx += strForSearch.length(); - } - return count; - } + int count = 0; + int idx = 0; + final String content2 = content.toString(); + final String strForSearch2 = strForSearch.toString(); + while ((idx = content2.indexOf(strForSearch2, idx)) > -1) { + count++; + idx += strForSearch.length(); + } + return count; + } - /** - * 统计指定内容中包含指定字符的数量 - * - * @param content 内容 - * @param charForSearch 被统计的字符 - * @return 包含数量 - */ - public static int count(CharSequence content, char charForSearch) { - int count = 0; - if (isEmpty(content)) { - return 0; - } - int contentLength = content.length(); - for (int i = 0; i < contentLength; i++) { - if (charForSearch == content.charAt(i)) { - count++; - } - } - return count; - } + /** + * 统计指定内容中包含指定字符的数量 + * + * @param content 内容 + * @param charForSearch 被统计的字符 + * @return 包含数量 + */ + public static int count(CharSequence content, char charForSearch) { + int count = 0; + if (isEmpty(content)) { + return 0; + } + int contentLength = content.length(); + for (int i = 0; i < contentLength; i++) { + if (charForSearch == content.charAt(i)) { + count++; + } + } + return count; + } } diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/SuffixFileFilter.java b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/SuffixFileFilter.java index a8d4387..6dd74bc 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/SuffixFileFilter.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/SuffixFileFilter.java @@ -32,7 +32,7 @@ public class SuffixFileFilter implements FileFilter, Serializable { public SuffixFileFilter(final String suffix) { Assert.notNull(suffix, "The suffix must not be null"); - this.suffixes = new String[] {suffix}; + this.suffixes = new String[]{suffix}; } public SuffixFileFilter(final String[] suffixes) { diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/URLUtil.java b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/URLUtil.java index a46dec5..a9c1a2b 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/URLUtil.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/URLUtil.java @@ -21,6 +21,8 @@ import java.nio.charset.Charset; /** * url处理工具类 + * + * @author L.cm */ public class URLUtil extends org.springframework.web.util.UriUtils { @@ -32,8 +34,8 @@ public class URLUtil extends org.springframework.web.util.UriUtils { * @return 编码后的url */ public static String encodeURL(String source, Charset charset) { - return URLUtil.encode(source, charset.name()); - } + return URLUtil.encode(source, charset.name()); + } /** * url 解码 @@ -43,24 +45,25 @@ public class URLUtil extends org.springframework.web.util.UriUtils { * @return 解码url */ public static String decodeURL(String source, Charset charset) { - return URLUtil.decode(source, charset.name()); - } + return URLUtil.decode(source, charset.name()); + } - /** - * 获取url路径 - * @param uriStr - * @return - */ - public static String getPath(String uriStr) { - URI uri; + /** + * 获取url路径 + * + * @param uriStr + * @return + */ + public static String getPath(String uriStr) { + URI uri; - try { - uri = new URI(uriStr); - } catch (URISyntaxException var3) { - throw new RuntimeException(var3); - } + try { + uri = new URI(uriStr); + } catch (URISyntaxException var3) { + throw new RuntimeException(var3); + } - return uri.getPath(); - } + return uri.getPath(); + } } diff --git a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/WebUtil.java b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/WebUtil.java index 62a8181..cdc17a4 100644 --- a/blade-core-tool/src/main/java/org/springblade/core/tool/utils/WebUtil.java +++ b/blade-core-tool/src/main/java/org/springblade/core/tool/utils/WebUtil.java @@ -42,228 +42,229 @@ import java.util.Enumeration; @Slf4j public class WebUtil extends org.springframework.web.util.WebUtils { - public static final String USER_AGENT_HEADER = "user-agent"; + public static final String USER_AGENT_HEADER = "user-agent"; - /** - * 判断是否ajax请求 - * spring ajax 返回含有 ResponseBody 或者 RestController注解 - * - * @param handlerMethod HandlerMethod - * @return 是否ajax请求 - */ - public static boolean isBody(HandlerMethod handlerMethod) { - ResponseBody responseBody = ClassUtil.getAnnotation(handlerMethod, ResponseBody.class); - return responseBody != null; - } + /** + * 判断是否ajax请求 + * spring ajax 返回含有 ResponseBody 或者 RestController注解 + * + * @param handlerMethod HandlerMethod + * @return 是否ajax请求 + */ + public static boolean isBody(HandlerMethod handlerMethod) { + ResponseBody responseBody = ClassUtil.getAnnotation(handlerMethod, ResponseBody.class); + return responseBody != null; + } - /** - * 读取cookie - * - * @param name cookie name - * @return cookie value - */ - @Nullable - public static String getCookieVal(String name) { - HttpServletRequest request = WebUtil.getRequest(); - Assert.notNull(request, "request from RequestContextHolder is null"); - return getCookieVal(request, name); - } + /** + * 读取cookie + * + * @param name cookie name + * @return cookie value + */ + @Nullable + public static String getCookieVal(String name) { + HttpServletRequest request = WebUtil.getRequest(); + Assert.notNull(request, "request from RequestContextHolder is null"); + return getCookieVal(request, name); + } - /** - * 读取cookie - * - * @param request HttpServletRequest - * @param name cookie name - * @return cookie value - */ - @Nullable - public static String getCookieVal(HttpServletRequest request, String name) { - Cookie cookie = getCookie(request, name); - return cookie != null ? cookie.getValue() : null; - } + /** + * 读取cookie + * + * @param request HttpServletRequest + * @param name cookie name + * @return cookie value + */ + @Nullable + public static String getCookieVal(HttpServletRequest request, String name) { + Cookie cookie = getCookie(request, name); + return cookie != null ? cookie.getValue() : null; + } - /** - * 清除 某个指定的cookie - * - * @param response HttpServletResponse - * @param key cookie key - */ - public static void removeCookie(HttpServletResponse response, String key) { - setCookie(response, key, null, 0); - } + /** + * 清除 某个指定的cookie + * + * @param response HttpServletResponse + * @param key cookie key + */ + public static void removeCookie(HttpServletResponse response, String key) { + setCookie(response, key, null, 0); + } - /** - * 设置cookie - * - * @param response HttpServletResponse - * @param name cookie name - * @param value cookie value - * @param maxAgeInSeconds maxage - */ - public static void setCookie(HttpServletResponse response, String name, @Nullable String value, int maxAgeInSeconds) { - Cookie cookie = new Cookie(name, value); - cookie.setPath("/"); - cookie.setMaxAge(maxAgeInSeconds); - cookie.setHttpOnly(true); - response.addCookie(cookie); - } + /** + * 设置cookie + * + * @param response HttpServletResponse + * @param name cookie name + * @param value cookie value + * @param maxAgeInSeconds maxage + */ + public static void setCookie(HttpServletResponse response, String name, @Nullable String value, int maxAgeInSeconds) { + Cookie cookie = new Cookie(name, value); + cookie.setPath("/"); + cookie.setMaxAge(maxAgeInSeconds); + cookie.setHttpOnly(true); + response.addCookie(cookie); + } - /** - * 获取 HttpServletRequest - * - * @return {HttpServletRequest} - */ - public static HttpServletRequest getRequest() { - RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); - return (requestAttributes == null) ? null : ((ServletRequestAttributes) requestAttributes).getRequest(); - } + /** + * 获取 HttpServletRequest + * + * @return {HttpServletRequest} + */ + public static HttpServletRequest getRequest() { + RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); + return (requestAttributes == null) ? null : ((ServletRequestAttributes) requestAttributes).getRequest(); + } - /** - * 返回json - * - * @param response HttpServletResponse - * @param result 结果对象 - */ - public static void renderJson(HttpServletResponse response, Object result) { - renderJson(response, result, MediaType.APPLICATION_JSON_UTF8_VALUE); - } + /** + * 返回json + * + * @param response HttpServletResponse + * @param result 结果对象 + */ + public static void renderJson(HttpServletResponse response, Object result) { + renderJson(response, result, MediaType.APPLICATION_JSON_UTF8_VALUE); + } - /** - * 返回json - * - * @param response HttpServletResponse - * @param result 结果对象 - * @param contentType contentType - */ - public static void renderJson(HttpServletResponse response, Object result, String contentType) { - response.setCharacterEncoding("UTF-8"); - response.setContentType(contentType); - try (PrintWriter out = response.getWriter()) { - out.append(JsonUtil.toJson(result)); - } catch (IOException e) { - log.error(e.getMessage(), e); - } - } + /** + * 返回json + * + * @param response HttpServletResponse + * @param result 结果对象 + * @param contentType contentType + */ + public static void renderJson(HttpServletResponse response, Object result, String contentType) { + response.setCharacterEncoding("UTF-8"); + response.setContentType(contentType); + try (PrintWriter out = response.getWriter()) { + out.append(JsonUtil.toJson(result)); + } catch (IOException e) { + log.error(e.getMessage(), e); + } + } - /** - * 获取ip - * - * @return {String} - */ - public static String getIP() { - return getIP(WebUtil.getRequest()); - } + /** + * 获取ip + * + * @return {String} + */ + public static String getIP() { + return getIP(WebUtil.getRequest()); + } - /** - * 获取ip - * - * @param request HttpServletRequest - * @return {String} - */ - @Nullable - public static String getIP(HttpServletRequest request) { - Assert.notNull(request, "HttpServletRequest is null"); - String ip = request.getHeader("X-Requested-For"); - if (StringUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) { - ip = request.getHeader("X-Forwarded-For"); - } - if (StringUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) { - ip = request.getHeader("Proxy-Client-IP"); - } - if (StringUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) { - ip = request.getHeader("WL-Proxy-Client-IP"); - } - if (StringUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) { - ip = request.getHeader("HTTP_CLIENT_IP"); - } - if (StringUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) { - ip = request.getHeader("HTTP_X_FORWARDED_FOR"); - } - if (StringUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) { - ip = request.getRemoteAddr(); - } - return StringUtil.isBlank(ip) ? null : ip.split(",")[0]; - } + /** + * 获取ip + * + * @param request HttpServletRequest + * @return {String} + */ + @Nullable + public static String getIP(HttpServletRequest request) { + Assert.notNull(request, "HttpServletRequest is null"); + String ip = request.getHeader("X-Requested-For"); + if (StringUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("X-Forwarded-For"); + } + if (StringUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("Proxy-Client-IP"); + } + if (StringUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("WL-Proxy-Client-IP"); + } + if (StringUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("HTTP_CLIENT_IP"); + } + if (StringUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("HTTP_X_FORWARDED_FOR"); + } + if (StringUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) { + ip = request.getRemoteAddr(); + } + return StringUtil.isBlank(ip) ? null : ip.split(",")[0]; + } - /*** - * 获取 request 中 json 字符串的内容 - * - * @param request - * @throws IOException - */ - public static String getRequestParamString(HttpServletRequest request) { - try { - return getRequestStr(request); - } catch (Exception ex) { - return StringPool.EMPTY; - } - } + /*** + * 获取 request 中 json 字符串的内容 + * + * @param request + * @throws IOException + */ + public static String getRequestParamString(HttpServletRequest request) { + try { + return getRequestStr(request); + } catch (Exception ex) { + return StringPool.EMPTY; + } + } - /** - * 获取 request 请求内容 - * - * @param request - * @return - * @throws IOException - */ - public static String getRequestStr(HttpServletRequest request) throws IOException { - String queryString = request.getQueryString(); - if (StringUtil.isNotBlank(queryString)) { - return new String(queryString.getBytes(Charsets.ISO_8859_1), Charsets.UTF_8).replaceAll("&", "&").replaceAll("%22", "\""); - } - return getRequestStr(request, getRequestBytes(request)); - } + /** + * 获取 request 请求内容 + * + * @param request + * @return + * @throws IOException + */ + public static String getRequestStr(HttpServletRequest request) throws IOException { + String queryString = request.getQueryString(); + if (StringUtil.isNotBlank(queryString)) { + return new String(queryString.getBytes(Charsets.ISO_8859_1), Charsets.UTF_8).replaceAll("&", "&").replaceAll("%22", "\""); + } + return getRequestStr(request, getRequestBytes(request)); + } - /** - * 获取 request 请求的 byte[] 数组 - * - * @param request - * @return - * @throws IOException - */ - public static byte[] getRequestBytes(HttpServletRequest request) throws IOException { - int contentLength = request.getContentLength(); - if (contentLength < 0) { - return null; - } - byte buffer[] = new byte[contentLength]; - for (int i = 0; i < contentLength; ) { + /** + * 获取 request 请求的 byte[] 数组 + * + * @param request + * @return + * @throws IOException + */ + public static byte[] getRequestBytes(HttpServletRequest request) throws IOException { + int contentLength = request.getContentLength(); + if (contentLength < 0) { + return null; + } + byte buffer[] = new byte[contentLength]; + for (int i = 0; i < contentLength; ) { - int readlen = request.getInputStream().read(buffer, i, contentLength - i); - if (readlen == -1) { - break; - } - i += readlen; - } - return buffer; - } + int readlen = request.getInputStream().read(buffer, i, contentLength - i); + if (readlen == -1) { + break; + } + i += readlen; + } + return buffer; + } - /** - * 获取 request 请求内容 - * @param request - * @param buffer - * @return - * @throws IOException - */ - public static String getRequestStr(HttpServletRequest request, byte buffer[]) throws IOException { - String charEncoding = request.getCharacterEncoding(); - if (charEncoding == null) { - charEncoding = StringPool.UTF_8; - } - String str = new String(buffer, charEncoding).trim(); - if (StringUtil.isBlank(str)) { - StringBuilder sb = new StringBuilder(); - Enumeration parameterNames = request.getParameterNames(); - while (parameterNames.hasMoreElements()) { - String key = parameterNames.nextElement(); - String value = request.getParameter(key); - StringUtil.appendBuilder(sb, key, "=", value, "&"); - } - str = StringUtil.removeSuffix(sb.toString(), "&"); - } - return str.replaceAll("&", "&"); - } + /** + * 获取 request 请求内容 + * + * @param request + * @param buffer + * @return + * @throws IOException + */ + public static String getRequestStr(HttpServletRequest request, byte buffer[]) throws IOException { + String charEncoding = request.getCharacterEncoding(); + if (charEncoding == null) { + charEncoding = StringPool.UTF_8; + } + String str = new String(buffer, charEncoding).trim(); + if (StringUtil.isBlank(str)) { + StringBuilder sb = new StringBuilder(); + Enumeration parameterNames = request.getParameterNames(); + while (parameterNames.hasMoreElements()) { + String key = parameterNames.nextElement(); + String value = request.getParameter(key); + StringUtil.appendBuilder(sb, key, "=", value, "&"); + } + str = StringUtil.removeSuffix(sb.toString(), "&"); + } + return str.replaceAll("&", "&"); + } }