From 826b66207dafbce24f441cb83fed1b241a6fba27 Mon Sep 17 00:00:00 2001 From: chenjiahe <763432473@qq.com> Date: 星期一, 23 九月 2024 16:30:15 +0800 Subject: [PATCH] 底层4个工具合并 --- hx_common/src/main/java/com/hx/resultTool/Result.java | 125 hx_common/src/main/java/com/hx/exception/TipsException.java | 38 hx_common/src/main/java/com/hx/mp/util/MPWeixinBaseUtil.java | 842 + hx_auto/src/main/java/com/hx/auto/GeneratorReadXmlUtil.java | 192 hx_common/src/main/java/com/hx/redis/RedisUtil.java | 414 hx_common/src/main/java/com/hx/util/gaode/AddressCode.java | 42 hx_common/src/main/java/com/qq/weixin/mp/aes/ByteGroup.java | 26 hx_common/src/main/java/com/hx/corp/util/WxCorpPayUtil.java | 613 + hx_auto/src/main/java/com.hx.auto/GeneratorActionUtil.java | 114 hx_common/src/main/java/com/hx/util/QRCodeUtil.java | 278 hx-redisson/pom.xml | 71 hx_common/src/main/java/com/hx/common/xml/CommonMapper.xml | 19 hx_common/src/main/java/com/hx/mp/util/ResponseHandler.java | 225 hx_common/src/main/java/com/hx/util/JwtTool.java | 94 hx_common/src/main/java/com/hx/mybatis/aes/springbean/FieldData.java | 40 hx_common/src/main/java/com/hx/mybatis/date/handler/GenericDateHandler.java | 38 hx_auto/src/main/java/com/hx/auto/manage/xml/scan/StartScanXmlHandlerImpl.java | 34 hx_common/src/main/java/com/qq/weixin/mp/aes/SHA1.java | 61 hx_common/src/main/java/com/hx/resultTool/ResponseCode.java | 30 hx_auto/src/main/java/com.hx.auto/GeneratorUtil.java | 256 hx_common/src/main/java/com/hx/util/MultipartFileUtil.java | 58 hx_auto/src/main/resources/ftl/Mapper.tpl | 90 hx_common/src/main/java/com/hx/platform/tool/PlatformSign.java | 0 hx_auto/src/main/java/com/hx/auto/manage/xml/scan/StartScanXmlHandler.java | 15 hx_common/src/main/java/com/hx/common/service/CommonService.java | 127 hx_common/src/main/java/com/hx/util/MD5Util.java | 48 hx_common/src/main/java/com/hx/util/code/NumberTool.java | 101 hx_common/src/main/java/com/hx/mybatis/aes/springbean/ExportTableAliasVisitor.java | 53 hx-redisson/src/main/java/com/hx/redisson/entity/RedissondbConfigEntity.java | 30 hx_common/src/main/java/com/hx/exception/ParamException.java | 12 hx_common/src/main/java/com/hx/util/rsa/RSAUtil.java | 121 hx_common/src/main/java/com/hx/mp/util/CertUtil.java | 31 hx_common/src/main/java/com/hx/util/gaode/GaoDeMapUtil.java | 53 hx_common/src/main/java/com/hx/util/HttpServletRequestUtil.java | 53 hx-redisson/src/main/java/com/hx/redisson/config/RedissonConfig.java | 36 hx_common/src/main/java/com/hx/util/NumberUtil.java | 418 hx_common/src/main/java/com/qq/weixin/mp/aes/WXBizMsgCrypt.java | 296 hx_common/src/main/java/com/hx/util/OBSUtil.java | 156 hx_auto/src/main/java/com/hx/auto/file/Action.tpl | 79 hx_common/src/main/java/com/hx/util/StreamUtils.java | 266 hx_common/src/main/java/com/hx/corp/entity/CorpPayResponse.java | 157 hx_common/src/main/java/com/qq/weixin/mp/aes/AesException.java | 59 hx_common/src/main/java/com/hx/util/StringUtils.java | 372 hx_auto/src/main/java/com/hx/auto/file/ServiceImpl.tpl | 101 hx_common/src/main/java/com/hx/common/BaseController.java | 88 hx_auto/src/main/java/com/hx/auto/file/Service.tpl | 33 hx_common/src/main/java/com/hx/util/XmlUtil.java | 113 hx_common/src/main/java/com/hx/util/CreateNoTool.java | 46 hx_common/src/main/java/com/hx/encryption/PTConstant.java | 34 hx_common/src/main/java/com/hx/util/HttpResponse.java | 32 hx_common/src/main/java/com/hx/mp/util/CorpMpUtil.java | 347 hx_common/src/main/java/com/hx/util/SimpleEncrypt.java | 95 hx_common/src/main/java/com/hx/repeat/check/RequestRepeatUtil.java | 76 hx_common/src/main/java/com/hx/util/RegValidatorUtil.java | 272 hx_common/src/main/java/com/hx/util/TempltUtil.java | 150 hx_common/src/main/java/com/hx/util/RequestMethod.java | 197 hx_common/src/main/java/com/hx/common/service/impl/CommonDaoImpl.java | 123 hx_common/pom.xml | 327 hx_common/src/main/java/com/hx/util/COSUtil.java | 237 hx-redisson/src/main/java/com/hx/redisson/manager/RedisManager.java | 46 hx_common/src/main/java/com/hx/bean/annotations/RedisClient.java | 26 hx_common/src/main/java/com/hx/mp/util/ClientResponseHandler.java | 228 hx_auto/src/main/java/com.hx.auto/GeneratorDaoUtil.java | 110 hx_common/src/main/java/com/hx/mybatis/aes/springbean/MySqlInterceptor.java | 101 hx_common/src/main/java/com/hx/util/AesUtil.java | 125 hx_common/src/main/java/com/hx/common/annotations/MysqlHexAes.java | 24 hx_common/src/main/java/com/hx/util/ExcelFileUtil.java | 129 hx_common/src/main/java/com/hx/corp/entity/CorpPayRequest.java | 135 hx_common/src/main/java/com/hx/common/dao/CommonDao.java | 127 hx_common/src/main/java/com/hx/mp/util/HttpClientUtil.java | 340 hx_common/src/main/java/com/hx/util/MapUtil.java | 93 hx_common/src/main/java/com/hx/mp/util/WxMpPayUtil.java | 98 hx_common/src/main/java/com/qq/weixin/mp/aes/PKCS7Encoder.java | 67 hx_auto/src/main/java/com.hx.auto/GeneratorMapperUtil.java | 176 hx_common/src/main/java/com/hx/mp/util/RequestHandler.java | 273 hx_auto/src/main/java/com/hx/auto/manage/xml/scan/util/ConfigUtil.java | 145 hx_common/src/main/java/com/hx/util/FileUtils.java | 666 + hx_auto/src/main/java/com.hx.auto/common/JdbcType.java | 51 hx_common/src/main/java/com/hx/security/request/RequestRestriction.java | 39 hx_common/src/main/java/com/hx/util/JwtConstant.java | 54 hx_common/src/main/java/com/hx/util/corp/entity/AppLetInfo.java | 22 hx_common/src/main/java/com/hx/util/EmailUtil.java | 120 hx_common/src/main/java/com/hx/mp/util/CorpMpSpaceUtil.java | 238 hx_common/src/main/java/com/hx/util/SerializeUtil.java | 72 hx_common/src/main/java/com/hz/util/http/dto/HttpHzResponse.java | 63 hx_common/src/main/java/com/hx/util/BarCodeUtil.java | 57 hx-redisson/.gitignore | 25 hx_common/src/main/java/com/hx/util/HttpUtil.java | 658 + hx_common/src/main/java/com/hx/util/rsa/RSASignature.java | 195 hx_auto/src/main/java/com/hx/auto/util/CommonTool.java | 17 hx_common/src/main/java/com/hx/common/annotations/repeat/RequestRepeat.java | 17 hx_common/src/main/java/com/hx/mp/util/CorpWXPayQrUtil.java | 73 hx_common/src/main/java/com/hx/util/DateUtil.java | 918 ++ hx_common/src/main/java/com/hx/mybatisTool/SqlStringTool.java | 172 hx_common/src/main/java/com/hx/annotation/Jurisdiction.java | 25 hx_auto/src/main/java/com/hx/auto/manage/xml/scan/util/CreateMapperUtil.java | 154 hx_common/src/main/java/com/hx/exception/LoginException.java | 35 hx_common/src/main/java/com/hx/mybatisTool/SqlSentence.java | 251 hx_common/src/main/java/com/hx/util/ThreadPoolUtils.java | 42 hx_common/src/main/java/com/hx/util/ImageBase64Util.java | 79 hx_common/src/main/java/com/hx/mp/util/MpUtil.java | 420 hx_common/src/main/java/com/hx/util/corp/entity/OpenIdAUserId.java | 62 hx_auto/src/main/resources/ftl/Dao.tpl | 37 hx_common/src/main/java/com/hx/util/HttpMethodUtil.java | 151 hx_auto/src/main/java/com/hx/auto/file/Dao.tpl | 35 hx_common/src/main/java/com/hx/util/MyRedisTemplate.java | 139 hx_common/src/main/java/com/hx/redis/RedisConfig.java | 34 hx_common/src/main/java/com/hx/mp/util/CorpMpClientUtil.java | 510 + hx_auto/src/main/resources/ftl/Service.tpl | 33 hx_auto/src/main/resources/ftl/ServiceImpl.tpl | 101 hx_common/src/main/java/com/qq/weixin/mp/aes/XMLParse.java | 106 hx_common/src/main/java/com/hx/bean/annotations/RequestSecurity.java | 21 hx_auto/src/main/java/com/hx/auto/util/GeneratorClassParentUtil.java | 55 hx_common/src/main/java/com/hx/util/corp/entity/WeiXinInfo.java | 113 hx_common/src/main/java/com/hx/util/BlurDataUtil.java | 119 hx_common/src/main/java/com/hx/util/OSSUtil.java | 126 hx_common/src/main/java/com/hx/mybatis/aes/springbean/VariableAesKey.java | 294 hx_auto/src/main/java/com.hx.auto/AutoDomeUtil.java | 53 hx_auto/.gitignore | 26 hx_common/src/main/java/com/hx/bean/annotations/MysqlAutoAes.java | 25 hx_common/src/main/java/com/hx/mp/util/WechatUtil.java | 77 hx_common/src/main/java/com/hz/util/http/HttpHzUtil.java | 114 hx_auto/src/main/java/com/hx/auto/manage/xml/scan/util/Constants.java | 18 hx_common/src/main/java/com/hx/util/corp/CorpMpUtil.java | 101 hx_common/src/main/java/com/hx/mp/util/WXPayUtil.java | 622 + hx_common/src/main/java/com/hx/api/CorpMpSpaceApi.java | 196 hx_common/src/main/java/com/hx/encryption/PTEncryptionUtil.java | 76 hx_common/src/main/java/com/hx/mp/util/XMLUtil.java | 109 hx_auto/src/main/java/com.hx.auto/common/Lob.java | 25 hx_common/src/main/java/com/hx/common/dao/mapper/CommonMapper.java | 20 hx_auto/src/main/java/com.hx.auto/GeneratorServiceUtil.java | 121 hx_common/src/main/java/com/hx/util/DownFileUtil.java | 225 hx-redisson/src/main/java/com/hx/redisson/bean/annotations/RedissonClient.java | 24 hx_common/src/main/java/com/hx/mybatis/aes/springbean/ConstantBean.java | 46 hx_common/.gitignore | 25 hx_common/src/main/java/com/hx/util/rsa/Base64.java | 273 hx_common/src/main/java/com/hx/util/Aes.java | 113 hx_common/src/main/java/com/hx/util/CheckCodeImageUtil.java | 96 hx_common/src/main/java/com/hx/util/ImagesAddDomain.java | 84 hx-redisson/src/main/java/com/hx/redisson/config/RedisBeanInit.java | 92 hx_common/src/main/java/com/hx/util/Base64Util.java | 65 hx_common/src/main/java/com/hx/util/FileConvertTool.java | 351 hx_common/src/main/java/com/hx/util/thread/ExecutorServiceTool.java | 150 hx_common/src/main/java/com/hx/mp/util/TenpayUtil.java | 132 hx_common/src/main/java/com/hx/util/MD5.java | 64 hx-redisson/src/main/java/com/hx/redisson/config/RedissonUtil.java | 1689 +++ hx_common/src/main/java/com/hx/util/BigDecimalUtil.java | 28 hx_common/src/main/java/com/hx/mp/util/WXSignUtils.java | 33 hx_common/src/main/java/com/hx/util/IPUtils.java | 40 hx_auto/src/main/java/com/hx/auto/file/Mapper.tpl | 83 hx_common/src/main/java/com/hx/util/mysql/aes/MysqlHexAesTool.java | 110 hx_common/src/main/java/com/hx/util/CVSUtil.java | 56 hx_common/src/main/java/com/hx/mybatis/aes/handler/GenericStringHandler.java | 72 hx_auto/src/main/resources/ftl/Action.tpl | 79 hx_auto/src/main/java/com.hx.auto/common/UrlData.java | 105 hx_auto/src/main/java/com.hx.auto/common/ReadEntityData.java | 154 hx_common/src/main/java/com/hx/mybatis/aes/springbean/SqlUtils.java | 578 + hx_common/src/main/java/com/hx/mybatis/aes/springbean/InitMysqlData.java | 197 hx_common/src/main/java/com/hx/mp/util/HttpUtil.java | 31 hx_common/src/main/java/com/hx/util/SimpleTool.java | 1097 ++ hx_common/src/main/java/com/hx/common/service/impl/CommonServiceImpl.java | 119 hx_auto/pom.xml | 90 hx_common/src/main/java/com/hx/exception/ServiceException.java | 37 hx-redisson/src/main/java/com/hx/redisson/register/RedisRegister.java | 145 hx_common/src/main/java/com/hx/mp/util/TenpayHttpClient.java | 559 + hx_common/src/main/java/com/hx/util/TengXunMapUtil.java | 191 hx_common/src/main/java/com/hx/wx/gzh/WxGzhUtil.java | 174 hx_common/src/main/java/com/hx/util/FileUtil.java | 94 hx_common/src/main/java/com/hx/mp/util/HttpXmlUtils.java | 63 hx_common/src/main/java/com/hx/util/GsonUtils.java | 29 hx_common/src/main/java/com/hx/mp/util/MD5Util.java | 43 hx_common/src/main/java/com/hx/util/WebUtil.java | 53 hx_common/src/main/java/com/hx/util/ExcelUtil.java | 1133 ++ 173 files changed, 27,501 insertions(+), 0 deletions(-) diff --git a/hx-redisson/.gitignore b/hx-redisson/.gitignore new file mode 100644 index 0000000..6d037e8 --- /dev/null +++ b/hx-redisson/.gitignore @@ -0,0 +1,25 @@ +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +/target +/.idea diff --git a/hx-redisson/pom.xml b/hx-redisson/pom.xml new file mode 100644 index 0000000..5f12ada --- /dev/null +++ b/hx-redisson/pom.xml @@ -0,0 +1,71 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>com.hx.gitee</groupId> + <artifactId>hx-parent</artifactId> + <version>stander</version> + </parent> + + <artifactId>hx-redisson</artifactId> + <packaging>jar</packaging> + + <dependencies> + + <dependency> + <groupId>org.projectlombok</groupId> + <artifactId>lombok</artifactId> + </dependency> + + <dependency> + <groupId>commons-collections</groupId> + <artifactId>commons-collections</artifactId> + </dependency> + + <dependency> + <groupId>com.dtflys.forest</groupId> + <artifactId>spring-boot-starter-forest</artifactId> + </dependency> + + <!-- https://mvnrepository.com/artifact/org.redisson/redisson-spring-boot-starter --> + <dependency> + <groupId>org.redisson</groupId> + <artifactId>redisson-spring-boot-starter</artifactId> + </dependency> + + <!-- redis --> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-data-redis</artifactId> + </dependency> + </dependencies> + + <build> + <finalName>hx-redisson</finalName> + <resources> + <resource> + <directory>src/main/java</directory> + <includes> + <include>**/*.properties</include> + <include>**/*.xml</include> + <include>**/*.tld</include> + <include>**/*.tpl</include> + </includes> + <filtering>false</filtering> + </resource> + <resource> + <directory>src/main/resources</directory> + <excludes> + <exclude>profile-active/**</exclude> + </excludes> + </resource> + <resource> + <directory>${runtime.env}</directory> + </resource> + </resources> + </build> + +</project> \ No newline at end of file diff --git a/hx-redisson/src/main/java/com/hx/redisson/bean/annotations/RedissonClient.java b/hx-redisson/src/main/java/com/hx/redisson/bean/annotations/RedissonClient.java new file mode 100644 index 0000000..ff30a0a --- /dev/null +++ b/hx-redisson/src/main/java/com/hx/redisson/bean/annotations/RedissonClient.java @@ -0,0 +1,24 @@ +package com.hx.redisson.bean.annotations; + +import com.hx.redisson.config.RedisBeanInit; +import com.hx.redisson.config.RedissonConfig; +import com.hx.redisson.config.RedissonUtil; +import com.hx.redisson.register.RedisRegister; +import org.springframework.context.annotation.Import; + +import java.lang.annotation.*; + +/**浣跨敤redis閾炬帴 + *杩欓噷鐨処mport鐨勪袱涓被灏辨槸闇�瑕佸姞杞界殑bean锛岃繖鏍峰氨鍙互閫氳繃绠�鍗曠殑娣诲姞涓�涓敞瑙f潵鍔犺浇鑷繁鑷畾涔夌殑bean浜嗭紝鑰屼笖鍙� + *浠ユ槸寰堝涓紝鍙互鎵撳埌jar鍖呴噷闈㈤�氳繃Maven寮曞叆閮芥槸ok鐨勶紱 + * @author CJH + * @date 202-06-17 + */ +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@Documented +@Import({RedisBeanInit.class,RedisRegister.class, RedissonUtil.class, RedissonConfig.class}) +public @interface RedissonClient { + + +} \ No newline at end of file diff --git a/hx-redisson/src/main/java/com/hx/redisson/config/RedisBeanInit.java b/hx-redisson/src/main/java/com/hx/redisson/config/RedisBeanInit.java new file mode 100644 index 0000000..6a742fc --- /dev/null +++ b/hx-redisson/src/main/java/com/hx/redisson/config/RedisBeanInit.java @@ -0,0 +1,92 @@ +package com.hx.redisson.config; + +import com.hx.redisson.entity.RedissondbConfigEntity; +import com.hx.redisson.manager.RedisManager; +import org.apache.commons.collections.CollectionUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.BeansException; +import org.springframework.boot.autoconfigure.AutoConfigureBefore; +import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; +import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.context.EnvironmentAware; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.data.redis.core.RedisTemplate; + +import javax.annotation.PostConstruct; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * RedisTemplate 鍒濆鍖栫被 + * + * @author CJH + * @date 2020骞�12鏈�16鏃�22:38:46 + */ +/**瑕佸湪RedisAutoConfiguration 鑷姩閰嶇疆鍓嶆墽琛�*/ +@AutoConfigureBefore({RedisAutoConfiguration.class}) +/**瀹炵幇 EnvironmentAware 鐢ㄤ簬鑾峰彇鍏ㄥ眬鐜 +瀹炵幇 ApplicationContextAware 鐢ㄤ簬鑾峰彇Spring Context 涓婁笅鏂�*/ +public class RedisBeanInit implements EnvironmentAware, ApplicationContextAware { + private Logger logger = LoggerFactory.getLogger(RedisBeanInit.class); + + /**鐢ㄤ簬鑾峰彇鐜閰嶇疆*/ + private Environment environment; + /**鐢ㄤ簬缁戝畾瀵硅薄*/ + private Binder binder; + /**Spring context*/ + private ApplicationContext applicationContext; + /**绾跨▼瀹夊叏鐨刪ashmap*/ + private Map<String, RedisTemplate> redisTemplateMap = new ConcurrentHashMap<>(); + + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + this.applicationContext = applicationContext; + } + /** + * 璁剧疆鐜 + * + * @param environment + */ + @Override + public void setEnvironment(Environment environment) { + this.environment = environment; + this.binder = Binder.get(environment); + } + + + @PostConstruct // Constructor >> @Autowired >> @PostConstruct 鐢ㄤ簬鎵ц涓�涓� 闈為潤鎬佺殑void 鏂规硶锛屽父搴旂敤浜庡垵濮嬪寲璧勬簮 + public void initAllRedisTemlate() { + logger.info("<<<鍒濆鍖栫郴缁熺殑RedisTemlate寮�濮�>>>"); + RedissondbConfigEntity redissondb; + try { + redissondb = binder.bind("redissondb", RedissondbConfigEntity.class).get(); + } catch (Exception e) { + logger.error("璇诲彇redissondb鐜閰嶇疆澶辫触", e); + return; + } + List<Integer> databases = redissondb.getDatabases(); + if (CollectionUtils.isNotEmpty(databases)) { + databases.forEach(db -> { + Object bean = applicationContext.getBean("redisTemplate" + db); + if (bean != null && bean instanceof RedisTemplate) { + redisTemplateMap.put("redisTemplate" + db, (RedisTemplate) bean); + } else { + throw new RuntimeException("鍒濆鍖朢edisTemplate" + db + "澶辫触锛岃妫�鏌ラ厤缃�"); + } + }); + } + logger.info("宸茬粡瑁呴厤鐨剅edistempleate锛宮ap:{}", redisTemplateMap); + logger.info("<<<鍒濆鍖栫郴缁熺殑RedisTemlate瀹屾瘯>>>"); + } + + @Bean + public RedisManager getRedisManager() { + return new RedisManager(redisTemplateMap); + } +} diff --git a/hx-redisson/src/main/java/com/hx/redisson/config/RedissonConfig.java b/hx-redisson/src/main/java/com/hx/redisson/config/RedissonConfig.java new file mode 100644 index 0000000..e130d03 --- /dev/null +++ b/hx-redisson/src/main/java/com/hx/redisson/config/RedissonConfig.java @@ -0,0 +1,36 @@ +package com.hx.redisson.config; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.PropertyAccessor; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +/**閰嶇疆瀹炰緥鍖� + * CJH + */ +@Configuration +public class RedissonConfig { + @Bean + public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { + RedisTemplate<String, Object> template = new RedisTemplate<String, Object>(); + template.setConnectionFactory(factory); + Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); + ObjectMapper om = new ObjectMapper(); + om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); + om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); + jackson2JsonRedisSerializer.setObjectMapper(om); + StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); + template.setKeySerializer(stringRedisSerializer); + template.setHashKeySerializer(stringRedisSerializer); + template.setValueSerializer(jackson2JsonRedisSerializer); + template.setHashValueSerializer(jackson2JsonRedisSerializer); + template.afterPropertiesSet(); + return template; + } +} diff --git a/hx-redisson/src/main/java/com/hx/redisson/config/RedissonUtil.java b/hx-redisson/src/main/java/com/hx/redisson/config/RedissonUtil.java new file mode 100644 index 0000000..2d2fbce --- /dev/null +++ b/hx-redisson/src/main/java/com/hx/redisson/config/RedissonUtil.java @@ -0,0 +1,1689 @@ +package com.hx.redisson.config; + +import com.hx.redisson.manager.RedisManager; +import org.redisson.api.RLock; +import org.redisson.api.RedissonClient; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.ZSetOperations; +import org.springframework.util.CollectionUtils; + +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +/** + * <h1>RedisUtil 鎿嶄綔宸ュ叿绫�</h1> + * @author CJH + */ +public class RedissonUtil { + + private Logger logger = LoggerFactory.getLogger(RedissonUtil.class); + + @Autowired + private RedisManager redisManager; + + @Autowired + private RedisTemplate redisTemplate; + + /** + * 鎸囧畾缂撳瓨澶辨晥鏃堕棿 + * @param key 閿� + * @param time 鏃堕棿(绉�) + * @return + */ + public boolean expire(String key, long time) { + try { + if (time < 0) { + throw new RuntimeException("璁剧疆鏃堕棿涓嶈兘涓鸿礋鏁帮細"+time); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 鎸囧畾缂撳瓨澶辨晥鏃堕棿 + * + * @param key 閿� + * @param time 鏃堕棿(绉�) + * @return + */ + public boolean expire(String key, long time,int db) { + try { + if (time < 0) { + throw new RuntimeException("璁剧疆鏃堕棿涓嶈兘涓鸿礋鏁帮細"+time); + } + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + return redisTemplate.expire(key, time, TimeUnit.SECONDS); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + + /** + * 鎸囧畾缂撳瓨澶辨晥鏃堕棿 + * + * @param key 閿� + * @param time 鏃堕棿 + * @param timeUnit 鏃堕棿绫诲瀷 + * @return + */ + public boolean expire(String key, long time, TimeUnit timeUnit) { + try { + if (time < 0) { + throw new RuntimeException("璁剧疆鏃堕棿涓嶈兘涓鸿礋鏁帮細"+time); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 鎸囧畾缂撳瓨澶辨晥鏃堕棿 + * + * @param key 閿� + * @param time 鏃堕棿 + * @param timeUnit 鏃堕棿绫诲瀷 + * @return + */ + public boolean expire(String key, long time, TimeUnit timeUnit,int db) { + try { + if (time < 0) { + throw new RuntimeException("璁剧疆鏃堕棿涓嶈兘涓鸿礋鏁帮細"+time); + } + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + return redisTemplate.expire(key, time, timeUnit); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 鏍规嵁key 鑾峰彇杩囨湡鏃堕棿 + * + * @param key 閿� 涓嶈兘涓簄ull + * @return 鏃堕棿(绉�) 杩斿洖0浠h〃涓烘案涔呮湁鏁� + */ + public long getExpire(String key) { + return redisTemplate.getExpire(key, TimeUnit.SECONDS); + } + + + /** + * 鏍规嵁key 鑾峰彇杩囨湡鏃堕棿 + * + * @param key 閿� 涓嶈兘涓簄ull + * @return 鏃堕棿(绉�) 杩斿洖0浠h〃涓烘案涔呮湁鏁� + */ + public long getExpire(String key,int db) { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + return redisTemplate.getExpire(key, TimeUnit.SECONDS); + } + + + /** + * 鍒ゆ柇key鏄惁瀛樺湪 + * + * @param key 閿� + * @return true 瀛樺湪 false涓嶅瓨鍦� + */ + public boolean hasKey(String key) { + try { + return redisTemplate.hasKey(key); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 鍒ゆ柇key鏄惁瀛樺湪 + * + * @param key 閿� + * @return true 瀛樺湪 false涓嶅瓨鍦� + */ + public boolean hasKey(String key,int db) { + try { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + return redisTemplate.hasKey(key); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 鍒犻櫎缂撳瓨 + * + * @param key 鍙互浼犱竴涓�� 鎴栧涓� + */ + @SuppressWarnings("unchecked") + public void del(String... key) { + if (key != null && key.length > 0) { + if (key.length == 1) { + redisTemplate.delete(key[0]); + } else { + redisTemplate.delete(CollectionUtils.arrayToList(key)); + } + } + } + + /** + * 鍒犻櫎缂撳瓨 + * + * @param key 鍙互浼犱竴涓�� 鎴栧涓� + */ + @SuppressWarnings("unchecked") + public void del(int db,String... key) { + if (key != null && key.length > 0) { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + if (key.length == 1) { + redisTemplate.delete(key[0]); + } else { + redisTemplate.delete(CollectionUtils.arrayToList(key)); + } + } + } + + // ============================String============================= + + /** + * 鏅�氱紦瀛樿幏鍙� + * + * @param key 閿� + * @return 鍊� + */ + public Object get(String key) { + return key == null ? null : redisTemplate.opsForValue().get(key); + } + + /** + * 鏅�氱紦瀛樿幏鍙� + * + * @param key 閿� + * @return 鍊� + */ + public Object get(String key,int db) { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + return key == null ? null : redisTemplate.opsForValue().get(key); + } + + /** + * 鏅�氱紦瀛樻斁鍏� + * + * @param key 閿� + * @param value 鍊� + * @return true鎴愬姛 false澶辫触 + */ + public boolean set(String key, Object value) { + try { + redisTemplate.opsForValue().set(key, value); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + + } + + /** + * 鏅�氱紦瀛樻斁鍏� + * + * @param key 閿� + * @param value 鍊� + * @return true鎴愬姛 false澶辫触 + */ + public boolean set(String key, Object value,int db) { + try { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + redisTemplate.opsForValue().set(key, value); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + + } + + + /** + * 鏅�氱紦瀛樻斁鍏ュ苟璁剧疆鏃堕棿 + * + * @param key 閿� + * @param value 鍊� + * @param time 鏃堕棿(绉�) time瑕佸ぇ浜�0 濡傛灉time灏忎簬绛変簬0 灏嗚缃棤闄愭湡 + * @return true鎴愬姛 false 澶辫触 + */ + public boolean set(String key, Object value, long time) { + try { + if (time > 0) { + redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); + } else { + set(key, value); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 鏅�氱紦瀛樻斁鍏ュ苟璁剧疆鏃堕棿 + * + * @param key 閿� + * @param value 鍊� + * @param time 鏃堕棿(绉�) time瑕佸ぇ浜�0 濡傛灉time灏忎簬绛変簬0 灏嗚缃棤闄愭湡 + * @return true鎴愬姛 false 澶辫触 + */ + public boolean set(String key, Object value, long time,int db) { + try { + if (time > 0) { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); + } else { + set(key, value,db); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 鏅�氱紦瀛樻斁鍏ュ苟璁剧疆鏃堕棿锛屽苟澧炲姞鏃堕棿绫诲瀷閫夋嫨 + * + * @param key 閿� + * @param value 鍊� + * @param time 鏃堕棿 time瑕佸ぇ浜�0 濡傛灉time灏忎簬绛変簬0 灏嗚缃棤闄愭湡 + * @param timeUnit 鏃堕棿绫诲瀷 + * @return + */ + public boolean set(String key, Object value, long time, TimeUnit timeUnit) { + try { + if (time > 0) { + redisTemplate.opsForValue().set(key, value, time, timeUnit); + } else { + set(key, value); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 鏅�氱紦瀛樻斁鍏ュ苟璁剧疆鏃堕棿锛屽苟澧炲姞鏃堕棿绫诲瀷閫夋嫨 + * + * @param key 閿� + * @param value 鍊� + * @param time 鏃堕棿 time瑕佸ぇ浜�0 濡傛灉time灏忎簬绛変簬0 灏嗚缃棤闄愭湡 + * @param timeUnit 鏃堕棿绫诲瀷 + * @return + */ + public boolean set(String key, Object value, long time, TimeUnit timeUnit,int db) { + try { + if (time > 0) { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + redisTemplate.opsForValue().set(key, value, time, timeUnit); + } else { + set(key, value,db); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 閫掑 + * + * @param key 閿� + * @param delta 瑕佸鍔犲嚑(澶т簬0) + * @return + */ + public long incr(String key, long delta) { + if (delta < 0) { + throw new RuntimeException("閫掑鍥犲瓙蹇呴』澶т簬0"); + } + return redisTemplate.opsForValue().increment(key, delta); + } + + /** + * 閫掑 + * + * @param key 閿� + * @param delta 瑕佸鍔犲嚑(澶т簬0) + * @return + */ + public long incr(String key, long delta,int db) { + if (delta < 0) { + throw new RuntimeException("閫掑鍥犲瓙蹇呴』澶т簬0"); + } + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + return redisTemplate.opsForValue().increment(key, delta); + } + + /** + * 閫掑噺 + * + * @param key 閿� + * @param delta 瑕佸噺灏戝嚑(灏忎簬0) + * @return + */ + public long decr(String key, long delta) { + if (delta < 0) { + throw new RuntimeException("閫掑噺鍥犲瓙蹇呴』澶т簬0"); + } + return redisTemplate.opsForValue().increment(key, -delta); + } + + /** + * 閫掑噺 + * + * @param key 閿� + * @param delta 瑕佸噺灏戝嚑(灏忎簬0) + * @return + */ + public long decr(String key, long delta,int db) { + if (delta < 0) { + throw new RuntimeException("閫掑噺鍥犲瓙蹇呴』澶т簬0"); + } + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + return redisTemplate.opsForValue().increment(key, -delta); + } + + + /**濡傛灉鍊煎瓨鍦ㄥ氨涓嶅瓨鍏ワ紝濡傛灉涓嶅瓨鍦ㄥ氨瀛樺叆 + * @param key 閿� + * @param value 鍊� + * @param timeOut 鏃堕棿 + * @param unit 鏃堕棿鍗曚綅 + */ + public Boolean setIfAbsent(String key, Object value, long timeOut, TimeUnit unit) { + try { + return redisTemplate.opsForValue().setIfAbsent(key, value, timeOut, unit); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /**濡傛灉鍊煎瓨鍦ㄥ氨涓嶅瓨鍏ワ紝濡傛灉涓嶅瓨鍦ㄥ氨瀛樺叆 + * @param key 閿� + * @param value 鍊� + * @param timeOut 鏃堕棿 + * @param unit 鏃堕棿鍗曚綅 + */ + public Boolean setIfAbsent(String key, Object value, long timeOut, TimeUnit unit,int db) { + try { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + return redisTemplate.opsForValue().setIfAbsent(key, value, timeOut, unit); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + // ================================Map================================= + + /** + * HashGet + * + * @param key 閿� 涓嶈兘涓簄ull + * @param item 椤� 涓嶈兘涓簄ull + * @return 鍊� + */ + public Object hget(String key, String item) { + return redisTemplate.opsForHash().get(key, item); + } + + /** + * HashGet + * + * @param key 閿� 涓嶈兘涓簄ull + * @param item 椤� 涓嶈兘涓簄ull + * @return 鍊� + */ + public Object hget(String key, String item,int db) { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + return redisTemplate.opsForHash().get(key, item); + } + + /** + * 鑾峰彇hashKey瀵瑰簲鐨勬墍鏈夐敭鍊� + * + * @param key 閿� + * @return 瀵瑰簲鐨勫涓敭鍊� + */ + public Map<Object, Object> hmget(String key) { + return redisTemplate.opsForHash().entries(key); + } + + /** + * 鑾峰彇hashKey瀵瑰簲鐨勬墍鏈夐敭鍊� + * + * @param key 閿� + * @return 瀵瑰簲鐨勫涓敭鍊� + */ + public Map<Object, Object> hmget(String key,int db) { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + return redisTemplate.opsForHash().entries(key); + } + + + /** + * HashSet + * + * @param key 閿� + * @param map 瀵瑰簲澶氫釜閿�� + * @return true 鎴愬姛 false 澶辫触 + */ + public boolean hmset(String key, Map<String, Object> map) { + try { + redisTemplate.opsForHash().putAll(key, map); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * HashSet + * + * @param key 閿� + * @param map 瀵瑰簲澶氫釜閿�� + * @return true 鎴愬姛 false 澶辫触 + */ + public boolean hmset(String key, Map<String, Object> map,int db) { + try { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + redisTemplate.opsForHash().putAll(key, map); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * HashSet 骞惰缃椂闂� + * + * @param key 閿� + * @param map 瀵瑰簲澶氫釜閿�� + * @param time 鏃堕棿(绉�) + * @return true鎴愬姛 false澶辫触 + */ + public boolean hmset(String key, Map<String, Object> map, long time) { + try { + redisTemplate.opsForHash().putAll(key, map); + if (time > 0) { + expire(key, time); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * HashSet 骞惰缃椂闂� + * + * @param key 閿� + * @param map 瀵瑰簲澶氫釜閿�� + * @param time 鏃堕棿(绉�) + * @return true鎴愬姛 false澶辫触 + */ + public boolean hmset(String key, Map<String, Object> map, long time,int db) { + try { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + redisTemplate.opsForHash().putAll(key, map); + if (time > 0) { + expire(key, time,db); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 鍚戜竴寮爃ash琛ㄤ腑鏀惧叆鏁版嵁,濡傛灉涓嶅瓨鍦ㄥ皢鍒涘缓 + * + * @param key 閿� + * @param item 椤� + * @param value 鍊� + * @return true 鎴愬姛 false澶辫触 + */ + public boolean hset(String key, String item, Object value) { + try { + redisTemplate.opsForHash().put(key, item, value); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 鍚戜竴寮爃ash琛ㄤ腑鏀惧叆鏁版嵁,濡傛灉涓嶅瓨鍦ㄥ皢鍒涘缓 + * + * @param key 閿� + * @param item 椤� + * @param value 鍊� + * @return true 鎴愬姛 false澶辫触 + */ + public boolean hset(String key, String item, Object value,int db) { + try { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + redisTemplate.opsForHash().put(key, item, value); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 鍚戜竴寮爃ash琛ㄤ腑鏀惧叆鏁版嵁,濡傛灉涓嶅瓨鍦ㄥ皢鍒涘缓 + * + * @param key 閿� + * @param item 椤� + * @param value 鍊� + * @param time 鏃堕棿(绉�) 娉ㄦ剰:濡傛灉宸插瓨鍦ㄧ殑hash琛ㄦ湁鏃堕棿,杩欓噷灏嗕細鏇挎崲鍘熸湁鐨勬椂闂� + * @return true 鎴愬姛 false澶辫触 + */ + public boolean hset(String key, String item, Object value, long time) { + try { + redisTemplate.opsForHash().put(key, item, value); + if (time > 0) { + expire(key, time); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 鍚戜竴寮爃ash琛ㄤ腑鏀惧叆鏁版嵁,濡傛灉涓嶅瓨鍦ㄥ皢鍒涘缓 + * + * @param key 閿� + * @param item 椤� + * @param value 鍊� + * @param time 鏃堕棿(绉�) 娉ㄦ剰:濡傛灉宸插瓨鍦ㄧ殑hash琛ㄦ湁鏃堕棿,杩欓噷灏嗕細鏇挎崲鍘熸湁鐨勬椂闂� + * @return true 鎴愬姛 false澶辫触 + */ + public boolean hset(String key, String item, Object value, long time,int db) { + try { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + redisTemplate.opsForHash().put(key, item, value); + if (time > 0) { + expire(key, time,db); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 鍒犻櫎hash琛ㄤ腑鐨勫�� + * + * @param key 閿� 涓嶈兘涓簄ull + * @param item 椤� 鍙互浣垮涓� 涓嶈兘涓簄ull + */ + public void hdel(String key, Object... item) { + redisTemplate.opsForHash().delete(key, item); + } + + /** + * 鍒犻櫎hash琛ㄤ腑鐨勫�� + * + * @param key 閿� 涓嶈兘涓簄ull + * @param item 椤� 鍙互浣垮涓� 涓嶈兘涓簄ull + */ + public void hdel(int db,String key, Object... item) { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + redisTemplate.opsForHash().delete(key, item); + } + + /** + * 鍒ゆ柇hash琛ㄤ腑鏄惁鏈夎椤圭殑鍊� + * + * @param key 閿� 涓嶈兘涓簄ull + * @param item 椤� 涓嶈兘涓簄ull + * @return true 瀛樺湪 false涓嶅瓨鍦� + */ + public boolean hHasKey(String key, String item) { + return redisTemplate.opsForHash().hasKey(key, item); + } + + /** + * 鍒ゆ柇hash琛ㄤ腑鏄惁鏈夎椤圭殑鍊� + * + * @param key 閿� 涓嶈兘涓簄ull + * @param item 椤� 涓嶈兘涓簄ull + * @return true 瀛樺湪 false涓嶅瓨鍦� + */ + public boolean hHasKey(String key, String item,int db) { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + return redisTemplate.opsForHash().hasKey(key, item); + } + + + /** + * hash閫掑 濡傛灉涓嶅瓨鍦�,灏变細鍒涘缓涓�涓� 骞舵妸鏂板鍚庣殑鍊艰繑鍥� + * + * @param key 閿� + * @param item 椤� + * @param by 瑕佸鍔犲嚑(澶т簬0) + * @return + */ + public double hincr(String key, String item, double by) { + return redisTemplate.opsForHash().increment(key, item, by); + } + + /** + * hash閫掑 濡傛灉涓嶅瓨鍦�,灏变細鍒涘缓涓�涓� 骞舵妸鏂板鍚庣殑鍊艰繑鍥� + * + * @param key 閿� + * @param item 椤� + * @param by 瑕佸鍔犲嚑(澶т簬0) + * @return + */ + public double hincr(String key, String item, double by,int db) { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + return redisTemplate.opsForHash().increment(key, item, by); + } + + /** + * hash閫掑噺 + * + * @param key 閿� + * @param item 椤� + * @param by 瑕佸噺灏戣(灏忎簬0) + * @return + */ + public double hdecr(String key, String item, double by) { + return redisTemplate.opsForHash().increment(key, item, -by); + } + + /** + * hash閫掑噺 + * + * @param key 閿� + * @param item 椤� + * @param by 瑕佸噺灏戣(灏忎簬0) + * @return + */ + public double hdecr(String key, String item, double by,int db) { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + return redisTemplate.opsForHash().increment(key, item, -by); + } + + // ============================set============================= + + /** + * 鏍规嵁key鑾峰彇Set涓殑鎵�鏈夊�� + * + * @param key 閿� + * @return + */ + public Set<Object> sGet(String key) { + try { + return redisTemplate.opsForSet().members(key); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * 鏍规嵁key鑾峰彇Set涓殑鎵�鏈夊�� + * + * @param key 閿� + * @return + */ + public Set<Object> sGet(String key,int db) { + try { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + return redisTemplate.opsForSet().members(key); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * 鏍规嵁key鑾峰彇Set涓殑鎸囧畾鍑犱釜闅忔満鍐呭 + * + * @param key 閿� + * @param size 涓暟 + * @return + */ + public List sRandomGet(String key, Integer size) { + try { + return redisTemplate.opsForSet().randomMembers(key, size); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * 鏍规嵁key鑾峰彇Set涓殑鎸囧畾鍑犱釜闅忔満鍐呭 + * + * @param key 閿� + * @param size 涓暟 + * @return + */ + public List sRandomGet(String key, Integer size,int db) { + try { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + return redisTemplate.opsForSet().randomMembers(key, size); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * 鏍规嵁value浠庝竴涓猻et涓煡璇�,鏄惁瀛樺湪 + * + * @param key 閿� + * @param value 鍊� + * @return true 瀛樺湪 false涓嶅瓨鍦� + */ + public boolean sHasKey(String key, Object value) { + try { + return redisTemplate.opsForSet().isMember(key, value); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 鏍规嵁value浠庝竴涓猻et涓煡璇�,鏄惁瀛樺湪 + * + * @param key 閿� + * @param value 鍊� + * @return true 瀛樺湪 false涓嶅瓨鍦� + */ + public boolean sHasKey(String key, Object value,int db) { + try { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + return redisTemplate.opsForSet().isMember(key, value); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 灏嗘暟鎹斁鍏et缂撳瓨 + * + * @param key 閿� + * @param values 鍊� 鍙互鏄涓� + * @return 鎴愬姛涓暟 + */ + public long sSet(String key, Object... values) { + try { + return redisTemplate.opsForSet().add(key, values); + } catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + + /** + * 灏嗘暟鎹斁鍏et缂撳瓨 + * + * @param key 閿� + * @param values 鍊� 鍙互鏄涓� + * @return 鎴愬姛涓暟 + */ + public long sSet(int db,String key, Object... values) { + try { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + return redisTemplate.opsForSet().add(key, values); + } catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + + /** + * 灏唖et鏁版嵁鏀惧叆缂撳瓨 + * + * @param key 閿� + * @param time 鏃堕棿(绉�) + * @param values 鍊� 鍙互鏄涓� + * @return 鎴愬姛涓暟 + */ + public long sSetAndTime(String key, long time, Object... values) { + try { + Long count = redisTemplate.opsForSet().add(key, values); + if (time > 0) { + expire(key, time); + } + return count; + } catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + + /** + * 灏唖et鏁版嵁鏀惧叆缂撳瓨 + * + * @param key 閿� + * @param time 鏃堕棿(绉�) + * @param values 鍊� 鍙互鏄涓� + * @return 鎴愬姛涓暟 + */ + public long sSetAndTime(int db,String key, long time, Object... values) { + try { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + Long count = redisTemplate.opsForSet().add(key, values); + if (time > 0) { + expire(key, time,db); + } + return count; + } catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + + /** + * 鑾峰彇set缂撳瓨鐨勯暱搴� + * + * @param key 閿� + * @return + */ + public long sGetSetSize(String key) { + try { + return redisTemplate.opsForSet().size(key); + } catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + + /** + * 鑾峰彇set缂撳瓨鐨勯暱搴� + * + * @param key 閿� + * @return + */ + public long sGetSetSize(String key,int db) { + try { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + return redisTemplate.opsForSet().size(key); + } catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + + /** + * 绉婚櫎鍊间负value鐨� + * + * @param key 閿� + * @param values 鍊� 鍙互鏄涓� + * @return 绉婚櫎鐨勪釜鏁� + */ + public long setRemove(String key, Object... values) { + try { + Long count = redisTemplate.opsForSet().remove(key, values); + return count; + } catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + + + /** + * 绉婚櫎鍊间负value鐨� + * + * @param key 閿� + * @param values 鍊� 鍙互鏄涓� + * @return 绉婚櫎鐨勪釜鏁� + */ + public long setRemove(int db,String key, Object... values) { + try { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + Long count = redisTemplate.opsForSet().remove(key, values); + return count; + } catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + // ===============================list================================= + + /** + * 鑾峰彇list缂撳瓨鐨勫唴瀹� + * + * @param key 閿� + * @param start 寮�濮� + * @param end 缁撴潫 0 鍒� -1浠h〃鎵�鏈夊�� + * @return + */ + public List<Object> lGet(String key, long start, long end) { + try { + return redisTemplate.opsForList().range(key, start, end); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * 鑾峰彇list缂撳瓨鐨勫唴瀹� + * + * @param key 閿� + * @param start 寮�濮� + * @param end 缁撴潫 0 鍒� -1浠h〃鎵�鏈夊�� + * @return + */ + public List<Object> lGet(String key, long start, long end,int db) { + try { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + return redisTemplate.opsForList().range(key, start, end); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * 鑾峰彇list缂撳瓨鐨勯暱搴� + * + * @param key 閿� + * @return + */ + public long lGetListSize(String key) { + try { + return redisTemplate.opsForList().size(key); + } catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + + /** + * 鑾峰彇list缂撳瓨鐨勯暱搴� + * + * @param key 閿� + * @return + */ + public long lGetListSize(String key,int db) { + try { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + return redisTemplate.opsForList().size(key); + } catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + + /** + * 閫氳繃绱㈠紩 鑾峰彇list涓殑鍊� + * + * @param key 閿� + * @param index 绱㈠紩 index>=0鏃讹紝 0 琛ㄥご锛�1 绗簩涓厓绱狅紝渚濇绫绘帹锛沬ndex<0鏃讹紝-1锛岃〃灏撅紝-2鍊掓暟绗簩涓厓绱狅紝渚濇绫绘帹 + * @return + */ + public Object lGetIndex(String key, long index) { + try { + return redisTemplate.opsForList().index(key, index); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * 閫氳繃绱㈠紩 鑾峰彇list涓殑鍊� + * + * @param key 閿� + * @param index 绱㈠紩 index>=0鏃讹紝 0 琛ㄥご锛�1 绗簩涓厓绱狅紝渚濇绫绘帹锛沬ndex<0鏃讹紝-1锛岃〃灏撅紝-2鍊掓暟绗簩涓厓绱狅紝渚濇绫绘帹 + * @return + */ + public Object lGetIndex(String key, long index,int db) { + try { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + return redisTemplate.opsForList().index(key, index); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * 灏唋ist鏀惧叆缂撳瓨 + * + * @param key 閿� + * @param value 鍊� + * @return + */ + public boolean lSet(String key, Object value) { + try { + redisTemplate.opsForList().rightPush(key, value); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 灏唋ist鏀惧叆缂撳瓨 + * + * @param key 閿� + * @param value 鍊� + * @return + */ + public boolean lSet(String key, Object value,int db) { + try { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + redisTemplate.opsForList().rightPush(key, value); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 灏唋ist鏀惧叆缂撳瓨 + * + * @param key 閿� + * @param value 鍊� + * @param time 鏃堕棿(绉�) + * @return + */ + public boolean lSet(String key, Object value, long time) { + try { + redisTemplate.opsForList().rightPush(key, value); + if (time > 0) { + expire(key, time); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 灏唋ist鏀惧叆缂撳瓨 + * + * @param key 閿� + * @param value 鍊� + * @param time 鏃堕棿(绉�) + * @return + */ + public boolean lSet(String key, Object value, long time,int db) { + try { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + redisTemplate.opsForList().rightPush(key, value); + if (time > 0) { + expire(key, time,db); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 灏唋ist鏀惧叆缂撳瓨 + * + * @param key 閿� + * @param value 鍊� + * @return + */ + public boolean lSetAll(String key, List<Object> value) { + try { + redisTemplate.opsForList().rightPushAll(key, value); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 灏唋ist鏀惧叆缂撳瓨 + * + * @param key 閿� + * @param value 鍊� + * @return + */ + public boolean lSetAll(String key, List<Object> value,int db) { + try { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + redisTemplate.opsForList().rightPushAll(key, value); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 灏唋ist鏀惧叆缂撳瓨 + * + * @param key 閿� + * @param value 鍊� + * @param time 鏃堕棿(绉�) + * @return + */ + public boolean lSetAll(String key, List<Object> value, long time) { + try { + // 璁剧疆瓒呮椂鏃堕棿 鍘熷瓙鍖� + redisTemplate.opsForList().rightPushAll(key, value); + if (time > 0) { + expire(key, time); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 灏唋ist鏀惧叆缂撳瓨 + * + * @param key 閿� + * @param value 鍊� + * @param time 鏃堕棿(绉�) + * @return + */ + public boolean lSetAll(String key, List<Object> value, long time,int db) { + try { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + // 璁剧疆瓒呮椂鏃堕棿 鍘熷瓙鍖� + redisTemplate.opsForList().rightPushAll(key, value); + if (time > 0) { + expire(key, time,db); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 鏍规嵁绱㈠紩淇敼list涓殑鏌愭潯鏁版嵁 + * + * @param key 閿� + * @param index 绱㈠紩 + * @param value 鍊� + * @return + */ + public boolean lUpdateIndex(String key, long index, Object value) { + try { + redisTemplate.opsForList().set(key, index, value); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 鏍规嵁绱㈠紩淇敼list涓殑鏌愭潯鏁版嵁 + * + * @param key 閿� + * @param index 绱㈠紩 + * @param value 鍊� + * @return + */ + public boolean lUpdateIndex(String key, long index, Object value,int db) { + try { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + redisTemplate.opsForList().set(key, index, value); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 绉婚櫎N涓�间负value + * + * @param key 閿� + * @param count 绉婚櫎澶氬皯涓� + * @param value 鍊� + * @return 绉婚櫎鐨勪釜鏁� + */ + public long lRemove(String key, long count, Object value) { + try { + Long remove = redisTemplate.opsForList().remove(key, count, value); + return remove; + } catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + + /** + * 绉婚櫎N涓�间负value + * + * @param key 閿� + * @param count 绉婚櫎澶氬皯涓� + * @param value 鍊� + * @return 绉婚櫎鐨勪釜鏁� + */ + public long lRemove(String key, long count, Object value,int db) { + try { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + Long remove = redisTemplate.opsForList().remove(key, count, value); + return remove; + } catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + + + /** + * 鏍规嵁缁欏畾鐨勫竷闅嗚繃婊ゅ櫒娣诲姞鍊� + * + * @param bloomFilterHelper bloom甯冮殕杩囨护鍣ㄨВ鏋愮被 + * @param key redis 鐨刱ey + * @param value redis 鐨剉alue + * @param <T> 鍊肩殑绫诲瀷 + */ + /*public <T> void addByBloomFilter(BloomFilterHelper<T> bloomFilterHelper, String key, T value) { + Preconditions.checkArgument(bloomFilterHelper != null, "bloomFilterHelper涓嶈兘涓虹┖"); + int[] offset = bloomFilterHelper.murmurHashOffset(value); + for (int i : offset) { + redisTemplate.opsForValue().setBit(key, i, true); + } + }*/ + + + /** + * 鏍规嵁缁欏畾鐨勫竷闅嗚繃婊ゅ櫒鍒ゆ柇鍊兼槸鍚﹀瓨鍦� + * + * @param bloomFilterHelper bloom甯冮殕杩囨护鍣ㄨВ鏋愮被 + * @param key redis 鐨刱ey + * @param value redis 鐨剉alue + * @param <T> 鍊肩殑绫诲瀷 + * @return 瀛樺湪 true + */ + /* public <T> boolean includeByBloomFilter(BloomFilterHelper<T> bloomFilterHelper, String key, T value) { + Preconditions.checkArgument(bloomFilterHelper != null, "bloomFilterHelper涓嶈兘涓虹┖"); + int[] offset = bloomFilterHelper.murmurHashOffset(value); + for (int i : offset) { + if (!redisTemplate.opsForValue().getBit(key, i)) { + return false; + } + } + return true; + }*/ + + + /** + * zset 娣诲姞鍏冪礌 + * + * @param key + * @param time + * @param tuples + * @return + */ + public long zsSetAndTime(String key, long time, Set<ZSetOperations.TypedTuple<Object>> tuples) { + try { + Long count = redisTemplate.opsForZSet().add(key, tuples); + if (time > 0) { + expire(key, time); + } + return count; + } catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + + /** + * zset 娣诲姞鍏冪礌 + * + * @param key + * @param time + * @param tuples + * @return + */ + public long zsSetAndTime(String key, long time, Set<ZSetOperations.TypedTuple<Object>> tuples,int db) { + try { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + Long count = redisTemplate.opsForZSet().add(key, tuples); + if (time > 0) { + expire(key, time,db); + } + return count; + } catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + + /** + * zset 娣诲姞鍏冪礌 + * + * @param key + * @param tuples + * @return + */ + public long zsSet(String key, Set<ZSetOperations.TypedTuple<Object>> tuples) { + try { + Long count = redisTemplate.opsForZSet().add(key, tuples); + return count; + } catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + + /** + * zset 娣诲姞鍏冪礌 + * + * @param key + * @param tuples + * @return + */ + public long zsSet(String key, Set<ZSetOperations.TypedTuple<Object>> tuples,int db) { + try { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + Long count = redisTemplate.opsForZSet().add(key, tuples); + return count; + } catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + + /** + * zs 绉婚櫎鍏冪礌 + * + * @param key + * @param values + * @return + */ + public long zsRemove(String key, Object... values) { + try { + Long remove = redisTemplate.opsForZSet().remove(key, values); + return remove; + } catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + + + /** + * zs 绉婚櫎鍏冪礌 + * + * @param key + * @param values + * @return + */ + public long zsRemove(int db,String key, Object... values) { + try { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + Long remove = redisTemplate.opsForZSet().remove(key, values); + return remove; + } catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + + /** + * 閫氳繃绱㈠紩鍖洪棿杩斿洖鏈夊簭闆嗗悎鎴愭寚瀹氬尯闂村唴鐨勬垚鍛橈紝鍏朵腑鏈夊簭闆嗘垚鍛樻寜鍒嗘暟鍊奸�掑(浠庡皬鍒板ぇ)椤哄簭鎺掑垪 + * + * @param key 閿� + * @param start 璧峰浣嶇疆 0 + * @param end 鏈熬浣嶇疆 -1 + * @return 0 -1 杩斿洖鎸夊垎鏁伴�掑鐨勯『搴忛泦鍚� 浠呰繑鍥� key + */ + public Set zsGet(String key, long start, long end) { + try { + return redisTemplate.opsForZSet().range(key, start, end); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * 閫氳繃绱㈠紩鍖洪棿杩斿洖鏈夊簭闆嗗悎鎴愭寚瀹氬尯闂村唴鐨勬垚鍛橈紝鍏朵腑鏈夊簭闆嗘垚鍛樻寜鍒嗘暟鍊奸�掑(浠庡皬鍒板ぇ)椤哄簭鎺掑垪 + * + * @param key 閿� + * @param start 璧峰浣嶇疆 0 + * @param end 鏈熬浣嶇疆 -1 + * @return 0 -1 杩斿洖鎸夊垎鏁伴�掑鐨勯『搴忛泦鍚� 浠呰繑鍥� key + */ + public Set zsGet(String key, long start, long end,int db) { + try { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + return redisTemplate.opsForZSet().range(key, start, end); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + + /** + * 閫氳繃绱㈠紩鍖洪棿杩斿洖鏈夊簭闆嗗悎鎴愭寚瀹氬尯闂村唴鐨勬垚鍛橈紝鍏朵腑鏈夊簭闆嗘垚鍛樻寜鍒嗘暟鍊奸�掑(浠庡皬鍒板ぇ)椤哄簭鎺掑垪 + * + * @param key 閿� + * @param start 璧峰浣嶇疆 0 + * @param end 鏈熬浣嶇疆 -1 + * @return 0 -1 杩斿洖鎸夊垎鏁伴�掑鐨勯『搴忛泦鍚堬紝杩斿洖鎴愬憳瀵硅薄 + */ + public Set zsGetWithScores(String key, long start, long end) { + try { + return redisTemplate.opsForZSet().rangeWithScores(key, start, end); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * 閫氳繃绱㈠紩鍖洪棿杩斿洖鏈夊簭闆嗗悎鎴愭寚瀹氬尯闂村唴鐨勬垚鍛橈紝鍏朵腑鏈夊簭闆嗘垚鍛樻寜鍒嗘暟鍊奸�掑(浠庡皬鍒板ぇ)椤哄簭鎺掑垪 + * + * @param key 閿� + * @param start 璧峰浣嶇疆 0 + * @param end 鏈熬浣嶇疆 -1 + * @return 0 -1 杩斿洖鎸夊垎鏁伴�掑鐨勯『搴忛泦鍚堬紝杩斿洖鎴愬憳瀵硅薄 + */ + public Set zsGetWithScores(String key, long start, long end,int db) { + try { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + return redisTemplate.opsForZSet().rangeWithScores(key, start, end); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * 閫氳繃绱㈠紩鍖洪棿杩斿洖鏈夊簭闆嗗悎鎴愭寚瀹氬尯闂村唴鐨勬垚鍛橈紝鍏朵腑鏈夊簭闆嗘垚鍛樻寜鍒嗘暟鍊奸�掑噺(浠庡ぇ鍒板皬)椤哄簭鎺掑垪 + * + * @param key 閿� + * @param start 璧峰浣嶇疆 0 + * @param end 鏈熬浣嶇疆 -1 + * @return 0 -1 杩斿洖鎸夊垎鏁伴�掑鐨勯『搴忛泦鍚� 浠呰繑鍥� key + */ + public Set zsGetReverse(String key, long start, long end) { + try { + return redisTemplate.opsForZSet().reverseRange(key, start, end); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * 閫氳繃绱㈠紩鍖洪棿杩斿洖鏈夊簭闆嗗悎鎴愭寚瀹氬尯闂村唴鐨勬垚鍛橈紝鍏朵腑鏈夊簭闆嗘垚鍛樻寜鍒嗘暟鍊奸�掑噺(浠庡ぇ鍒板皬)椤哄簭鎺掑垪 + * + * @param key 閿� + * @param start 璧峰浣嶇疆 0 + * @param end 鏈熬浣嶇疆 -1 + * @return 0 -1 杩斿洖鎸夊垎鏁伴�掑鐨勯『搴忛泦鍚� 浠呰繑鍥� key + */ + public Set zsGetReverse(String key, long start, long end,int db) { + try { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + return redisTemplate.opsForZSet().reverseRange(key, start, end); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * 閫氳繃绱㈠紩鍖洪棿杩斿洖鏈夊簭闆嗗悎鎴愭寚瀹氬尯闂村唴鐨勬垚鍛樺璞★紝鍏朵腑鏈夊簭闆嗘垚鍛樻寜鍒嗘暟鍊奸�掑噺(浠庡ぇ鍒板皬)椤哄簭鎺掑垪 + * + * @param key 閿� + * @param start 璧峰浣嶇疆 0 + * @param end 鏈熬浣嶇疆 -1 + * @return 0 -1 杩斿洖鎸夊垎鏁伴�掑鐨勯『搴忛泦鍚堬紝杩斿洖鎴愬憳瀵硅薄 + */ + public Set zsGetReverseWithScores(String key, long start, long end) { + try { + return redisTemplate.opsForZSet().reverseRangeWithScores(key, start, end); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * 閫氳繃绱㈠紩鍖洪棿杩斿洖鏈夊簭闆嗗悎鎴愭寚瀹氬尯闂村唴鐨勬垚鍛樺璞★紝鍏朵腑鏈夊簭闆嗘垚鍛樻寜鍒嗘暟鍊奸�掑噺(浠庡ぇ鍒板皬)椤哄簭鎺掑垪 + * + * @param key 閿� + * @param start 璧峰浣嶇疆 0 + * @param end 鏈熬浣嶇疆 -1 + * @return 0 -1 杩斿洖鎸夊垎鏁伴�掑鐨勯『搴忛泦鍚堬紝杩斿洖鎴愬憳瀵硅薄 + */ + public Set zsGetReverseWithScores(String key, long start, long end,int db) { + try { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + return redisTemplate.opsForZSet().reverseRangeWithScores(key, start, end); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * 鍘熷瓙鍔� + * @param key 閿� + * @param num 鏁伴噺 + */ + public Long increment(String key,long num) { + try { + return redisTemplate.opsForValue().increment(key, num); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * 鍘熷瓙鍔� + * @param key 閿� + * @param num 鏁伴噺 + * @param db 鏁版嵁搴� + */ + public Long increment(String key,long num,int db) { + try { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + return redisTemplate.opsForValue().increment(key, num); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * 鍘熷瓙鍑� + * @param key 閿� + * @param num 鏁伴噺 + */ + public Long decrement(String key,long num) { + try { + return redisTemplate.opsForValue().decrement(key, num); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * 鍘熷瓙鍑� + * @param key 閿� + * @param num 鏁伴噺 + * @param db 鏁版嵁搴� + */ + public Long decrement(String key,long num,int db) { + try { + RedisTemplate redisTemplate = redisManager.getRedisTemplate(db); + return redisTemplate.opsForValue().decrement(key, num); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + + /** + * 鑾峰彇绾㈤攣 + * @param key 閿乲ey + * @param db 鏁版嵁搴撶紪鍙� + */ + public RLock getRLock(String key,int db) { + RLock lock = null; + try { + RedissonClient redissonClient = RedisManager.redissonTemplateMap.get(db+""); + lock = redissonClient.getLock(key); + } catch (Exception e) { + e.printStackTrace(); + } + return lock; + } + +} diff --git a/hx-redisson/src/main/java/com/hx/redisson/entity/RedissondbConfigEntity.java b/hx-redisson/src/main/java/com/hx/redisson/entity/RedissondbConfigEntity.java new file mode 100644 index 0000000..205c261 --- /dev/null +++ b/hx-redisson/src/main/java/com/hx/redisson/entity/RedissondbConfigEntity.java @@ -0,0 +1,30 @@ +package com.hx.redisson.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +/** + * redisconfig 閰嶇疆瀹炰綋绫� + * + * @author CJH + * @date 2022-06-27 + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +public class RedissondbConfigEntity implements Serializable { + /**鍦板潃*/ + private String host; + /**绔彛*/ + private String port; + /**瀵嗙爜*/ + private String password; + /**鎵�鏈夌殑db搴忓彿*/ + private List<Integer> databases = new ArrayList<>(); +} + diff --git a/hx-redisson/src/main/java/com/hx/redisson/manager/RedisManager.java b/hx-redisson/src/main/java/com/hx/redisson/manager/RedisManager.java new file mode 100644 index 0000000..6798614 --- /dev/null +++ b/hx-redisson/src/main/java/com/hx/redisson/manager/RedisManager.java @@ -0,0 +1,46 @@ +package com.hx.redisson.manager; + +import org.redisson.api.RedissonClient; +import org.springframework.data.redis.core.RedisTemplate; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * redis绠$悊 + * + * @author CJH + * @date 2022-06-27 + */ +public class RedisManager { + + private Map<String, RedisTemplate> redisTemplateMap = new ConcurrentHashMap<>(); + + public static Map<String, RedissonClient> redissonTemplateMap = new ConcurrentHashMap<>(); + + /** + * 鏋勯�犳柟娉曞垵濮嬪寲 redisTemplateMap 鐨勬暟鎹� + * + * @param redisTemplateMap + */ + public RedisManager(Map<String, RedisTemplate> redisTemplateMap) { + this.redisTemplateMap = redisTemplateMap; + } + + + /** + * 鏍规嵁鏁版嵁搴撳簭鍙凤紝杩斿洖瀵瑰簲鐨凴edisTemplate + * + * @param dbIndex 搴忓彿 + * @return {@link RedisTemplate} + */ + public RedisTemplate getRedisTemplate(Integer dbIndex) { + RedisTemplate redisTemplate = redisTemplateMap.get("redisTemplate" + dbIndex); + if (redisTemplate == null) { + throw new RuntimeException("Map涓嶅瓨鍦ㄨredisTemplate"); + } + return redisTemplate; + } + + +} diff --git a/hx-redisson/src/main/java/com/hx/redisson/register/RedisRegister.java b/hx-redisson/src/main/java/com/hx/redisson/register/RedisRegister.java new file mode 100644 index 0000000..2be389c --- /dev/null +++ b/hx-redisson/src/main/java/com/hx/redisson/register/RedisRegister.java @@ -0,0 +1,145 @@ +package com.hx.redisson.register; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.PropertyAccessor; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator; +import com.hx.redisson.entity.RedissondbConfigEntity; +import com.hx.redisson.manager.RedisManager; +import org.apache.commons.collections.CollectionUtils; +import org.redisson.Redisson; +import org.redisson.api.RedissonClient; +import org.redisson.client.codec.StringCodec; +import org.redisson.config.Config; +import org.redisson.config.SingleServerConfig; +import org.redisson.spring.data.connection.RedissonConnectionFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.AutowireCapableBeanFactory; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.beans.factory.support.GenericBeanDefinition; +import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.context.EnvironmentAware; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; +import org.springframework.core.env.Environment; +import org.springframework.core.type.AnnotationMetadata; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.RedisSerializer; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +import java.util.List; + +/** + * <h1>redistemplate鍒濆鍖�</h1> + * <p> + * 浣滅敤锛� + * <p> + * 璇诲彇绯荤粺閰嶇疆锛岀郴缁熷惎鍔ㄦ椂锛岃鍙杛edis 鐨勯厤缃紝鍒濆鍖栨墍鏈夌殑redistemplate + * 骞跺姩鎬佹敞鍐屼负bean + * + * @author gengzi + * @date 2021骞�1鏈�5鏃�22:16:29 + */ +@Configuration +public class RedisRegister implements EnvironmentAware, ImportBeanDefinitionRegistrar { + + private Logger logger = LoggerFactory.getLogger(RedisRegister.class); + + /**鐢ㄤ簬鑾峰彇鐜閰嶇疆*/ + private Environment environment; + /**鐢ㄤ簬缁戝畾瀵硅薄*/ + private Binder binder; + + /** + * 璁剧疆鐜 + * + * @param environment + */ + @Override + public void setEnvironment(Environment environment) { + this.environment = environment; + this.binder = Binder.get(environment); + } + + /** + * 娉ㄥ唽bean + * + * @param importingClassMetadata + * @param registry + */ + @Override + public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { + logger.info("銆娿�娿�婂姩鎬佹敞鍐宐ean寮�濮嬨�嬨�嬨��"); + RedissondbConfigEntity redissondb; + try { + redissondb = binder.bind("redissondb", RedissondbConfigEntity.class).get(); + } catch (Exception e) { + logger.error("璇诲彇redissondb鐜閰嶇疆澶辫触", e); + return; + } + List<Integer> databases = redissondb.getDatabases(); + if (CollectionUtils.isNotEmpty(databases)) { + databases.forEach(db -> { + // 鍗曟満妯″紡锛岄泦缇ゅ彧鑳戒娇鐢╠b0 + Config config = new Config(); + config.setCodec(StringCodec.INSTANCE); + SingleServerConfig singleConfig = config.useSingleServer(); + singleConfig.setAddress("redis://"+redissondb.getHost()+":"+redissondb.getPort()); + singleConfig.setPassword(redissondb.getPassword()); + singleConfig.setDatabase(db); + + System.out.println("getHost:"+singleConfig.getAddress()); + System.out.println("getHost:"+singleConfig.getPassword()); + RedissonClient redissonClient = Redisson.create(config); + + // 鏋勯�燫edissonConnectionFactory + RedissonConnectionFactory redisConnectionFactory = new RedissonConnectionFactory(redissonClient); + // bean瀹氫箟 + GenericBeanDefinition redisTemplate = new GenericBeanDefinition(); + // 璁剧疆bean 鐨勭被鍨� + redisTemplate.setBeanClass(RedisTemplate.class); + // 璁剧疆鑷姩娉ㄥ叆鐨勫舰寮忥紝鏍规嵁鍚嶇О + redisTemplate.setAutowireMode(AutowireCapableBeanFactory.AUTOWIRE_BY_NAME); + // redisTemplate 鐨勫睘鎬ч厤缃� + redisTemplate(redisTemplate, redisConnectionFactory); + // 娉ㄥ唽Bean + registry.registerBeanDefinition("redisTemplate" + db, redisTemplate); + + RedisManager.redissonTemplateMap.put(db+"",redissonClient); + }); + } + logger.info("銆娿�娿�婂姩鎬佹敞鍐宐ean缁撴潫銆嬨�嬨��"); + + } + + /** + * redisTemplate 鐨勫睘鎬ч厤缃� + * + * @param redisTemplate 娉涘瀷bean + * @param redisConnectionFactory 杩炴帴宸ュ巶 + * @return + */ + public GenericBeanDefinition redisTemplate(GenericBeanDefinition redisTemplate, RedisConnectionFactory redisConnectionFactory) { + RedisSerializer<String> stringRedisSerializer = new StringRedisSerializer(); + Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); + // 瑙e喅鏌ヨ缂撳瓨杞崲寮傚父鐨勯棶棰� + ObjectMapper om = new ObjectMapper(); + om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); + om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, + ObjectMapper.DefaultTyping.NON_FINAL); + jackson2JsonRedisSerializer.setObjectMapper(om); + // key閲囩敤String鐨勫簭鍒楀寲鏂瑰紡锛寁alue閲囩敤json搴忓垪鍖栨柟寮� + // 閫氳繃鏂规硶璁剧疆灞炴�у�� + redisTemplate.getPropertyValues().add("connectionFactory", redisConnectionFactory); + redisTemplate.getPropertyValues().add("keySerializer", stringRedisSerializer); + redisTemplate.getPropertyValues().add("hashKeySerializer", stringRedisSerializer); + redisTemplate.getPropertyValues().add("valueSerializer", jackson2JsonRedisSerializer); + redisTemplate.getPropertyValues().add("hashValueSerializer", jackson2JsonRedisSerializer); + + return redisTemplate; + } +} + diff --git a/hx_auto/.gitignore b/hx_auto/.gitignore new file mode 100644 index 0000000..5a07695 --- /dev/null +++ b/hx_auto/.gitignore @@ -0,0 +1,26 @@ +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar +*.iml + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +/target/ +/.idea diff --git a/hx_auto/pom.xml b/hx_auto/pom.xml new file mode 100644 index 0000000..eeb8d3c --- /dev/null +++ b/hx_auto/pom.xml @@ -0,0 +1,90 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <groupId>com.hx.gitee</groupId> + <artifactId>hx-auto</artifactId> + <version>stander</version> + + <properties> + <!--妯℃澘--> + <freemarker.version>2.3.28</freemarker.version> + <!--mybatis鑷姩鐢熸垚--> + <mybatis.actable>1.1.1.RELEASE</mybatis.actable> + </properties> + + <dependencies> + + <dependency> + <groupId>org.freemarker</groupId> + <artifactId>freemarker</artifactId> + <version>${freemarker.version}</version> + </dependency> + <!-- 鏁版嵁搴撹嚜鍔ㄧ敓鎴愯〃 --> + <dependency> + <groupId>com.gitee.sunchenbin.mybatis.actable</groupId> + <artifactId>mybatis-enhance-actable</artifactId> + <version>${mybatis.actable}</version> + </dependency> + <dependency> + <groupId>org.springframework</groupId> + <artifactId>spring-context</artifactId> + <version>5.2.5.RELEASE</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-api</artifactId> + <version>1.7.30</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>org.springframework</groupId> + <artifactId>spring-beans</artifactId> + <version>5.2.5.RELEASE</version> + <scope>compile</scope> + </dependency> + + </dependencies> + + + <build> + <resources> + <resource> + <directory>src/main/java</directory> + <includes> + <include>**/*.properties</include> + <include>**/*.xml</include> + <include>**/*.tld</include> + <include>**/*.tpl</include> + </includes> + <filtering>false</filtering> + </resource> + <resource> + <directory>src/main/resources</directory> + <includes> + <include>**/*.properties</include> + <include>**/*.xml</include> + <include>**/*.tld</include> + <include>**/*.tpl</include> + </includes> + </resource> + <resource> + <directory>${runtime.env}</directory> + </resource> + </resources> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-compiler-plugin</artifactId> + <configuration> + <source>6</source> + <target>6</target> + </configuration> + </plugin> + </plugins> + </build> + +</project> \ No newline at end of file diff --git a/hx_auto/src/main/java/com.hx.auto/AutoDomeUtil.java b/hx_auto/src/main/java/com.hx.auto/AutoDomeUtil.java new file mode 100644 index 0000000..243573d --- /dev/null +++ b/hx_auto/src/main/java/com.hx.auto/AutoDomeUtil.java @@ -0,0 +1,53 @@ +package com.hx.auto; + +import com.hx.auto.common.UrlData; + +import java.util.Map; + +/** + * 鑷姩鐢熸垚宸ュ叿 + * 2019-08-29 + * @author cjh + * + */ +public class AutoDomeUtil { + + public static void main(String[] args) throws Exception { + System.out.println("寮�濮�"); + UrlData urlData = new UrlData(); + urlData.setTotalUrl("com.hx"); + urlData.actionUrlData("hx-web.src.main.java","com.hx.controller.admin"); + urlData.daoUrlData("hx-web.src.main.java","com.hx.dao.mapper"); + urlData.serviceUrlData("hx-web.src.main.java","com.hx.service"); + urlData.serviceImplUrlData("hx-web.src.main.java","com.hx.service.impl"); + urlData.mapperUrlData("hx-web.src.main.java", "com.hx.dao.mapperXml"); + + /* + //dao + GeneratorUtil.generatorDao(SysAdmin.class,urlData); + //mapper + GeneratorUtil.generatorMapper(SysAdmin.class, urlData); + //action + GeneratorUtil.generatorAction(SysAdmin.class,urlData); + // 鐢熸垚service + GeneratorUtil.generatorService(SysAdmin.class,urlData); + + //閫氳繃瀹炰綋绫荤殑鍖呰幏鍙栨墍鏈夌殑琛紝鐩存帴鍏ㄩ儴鐢熸垚 + //GeneratorUtil.generatorTableByPackUrl("com.hx.model", urlData); + */ + //generatorTableByPackUrl(packPath, urlData); + + /*Class cl = TestM2.class; + Field[] fields = cl.getDeclaredFields(); + for(Field field:fields) { + System.out.println("field.getName():"+field.getName()); + System.out.println("field.getType():"+field.getType()); + System.out.println("field.getGenericType():"+field.getGenericType()); + System.out.println("field.getModifiers():"+field.getModifiers()); + }*/ + + //StringBuffer stringBuffer = SimpleToolUtil.getFileContent("com/cjh/auto/file/test.txt"); + //System.out.println("stringBuffer:"+stringBuffer); + } + +} \ No newline at end of file diff --git a/hx_auto/src/main/java/com.hx.auto/GeneratorActionUtil.java b/hx_auto/src/main/java/com.hx.auto/GeneratorActionUtil.java new file mode 100644 index 0000000..8ebd999 --- /dev/null +++ b/hx_auto/src/main/java/com.hx.auto/GeneratorActionUtil.java @@ -0,0 +1,114 @@ +package com.hx.auto; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.util.HashMap; + +import com.hx.auto.common.UrlData; +import com.hx.auto.util.CommonTool; +import freemarker.template.Configuration; +import freemarker.template.DefaultObjectWrapper; +import freemarker.template.Template; + +/** + * 鑷姩鐢熸垚action + * + * @author chenjiahe 2019骞�09鏈�08鏃�16:57:47 + * + */ +public class GeneratorActionUtil { + + private static String templateDir = "/ftl";//鑾峰彇妯℃澘璺緞 + private static String templateName = "Action.tpl";//action妯℃澘鍚嶇О + + /**鐢熸垚action + * @param cl 瀹炰綋绫� + * @param urlData 鐢熸垚閰嶇疆淇℃伅 + * @param sqlParam 鏄惁鐢熸垚鍔ㄦ�乻ql鐨勬枃浠讹紙sqlSentence.java锛�,宸茬粡鐢熸垚灏变笉鐢ㄧ敓鎴� + * @throws Exception + */ + public static void generatorAction(Class<?> cl, UrlData urlData, boolean sqlParam) throws Exception { + try { + + // 鍙嶅皠start + // 绫诲悕 + String entityName = cl.getSimpleName(); + // 绫诲悕棣栧瓧姣嶅皬鍐� + String initial = entityName.substring(0, 1).toLowerCase(); + String entityNameSmall = initial + entityName.substring(1, entityName.length()); + + //鍒ゆ柇鏄惁瀛樺湪 + //鐢熸垚鏂囦欢璺緞 + String targetFile = urlData.getActionUrl()[1].replace(".", "/")+"/"; + //鐢熸垚鏂囦欢鍚嶇О + targetFile += entityName + "Controller.java"; + targetFile = "./"+urlData.getActionUrl()[0].replace(".", "/")+"/"+targetFile; + File file = new File(targetFile); + if(file.exists()){ + //瀛樺湪灏辩粨鏉� + return; + } + + //鑾峰彇瀹炰綋绫诲寘鍚� + String[] strs = cl.getName().split("\\."); + String packageName = ""; + //鍘绘帀绫诲悕 + for(int i=0;i<strs.length-1;i++) { + packageName += "."+strs[i]; + } + packageName = packageName.replaceFirst(".", ""); + + //鑾峰彇妯℃澘 + Configuration configuration = new Configuration(Configuration.getVersion()); + configuration.setClassForTemplateLoading(GeneratorActionUtil.class, templateDir); + //configuration.setTemplateLoader(new ClassTemplateLoader(this.getClass(), "濉綘鐨剅esource涓嬬殑璺緞锛屾瘮濡�/ftl")); + Template template = configuration.getTemplate(templateName); + + // 鍒涘缓鏁版嵁妯″瀷 + HashMap<String, Object> root = new HashMap<String, Object>(); + + //action鍖呭悕 + if(!CommonTool.checkNotNull(urlData.getActionUrl())) { + System.err.println("娌℃湁鐢熸垚action璺緞"); + return; + } + root.put("packageName",urlData.getActionUrl()[1]); + //瀹炰綋绫荤殑绫诲悕 + root.put("entityName", entityName); + //瀹炰綋绫荤殑绫诲悕锛堥瀛楁瘝灏忓啓锛� + root.put("entityNameSmall", entityNameSmall); + + if(!CommonTool.checkNotNull(urlData.getTotalUrl())) { + System.err.println("娌℃湁璁剧疆鎬诲寘璺緞"); + return; + } + //dao鐨勫寘鍚� + if(!CommonTool.checkNotNull(urlData.getDaoUrl())) { + System.err.println("娌℃湁dao璺緞"); + return; + } + root.put("TotalPackageName",urlData.getTotalUrl()); + root.put("DAOPackageName",urlData.getDaoUrl()[1]); + //瀹炰綋绫荤殑鍖呭悕 + root.put("entityPackageName",packageName); + //service鐨勫寘鍚� + if(!CommonTool.checkNotNull(urlData.getServiceUrl())) { + System.err.println("娌℃湁service璺緞"); + return; + } + root.put("servicePackageName",urlData.getServiceUrl()[1]); + + // 灏嗘ā鏉垮拰鏁版嵁妯″瀷鍚堝苟 杈撳嚭鍒癈onsole + Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile), "UTF-8")); + template.process(root, out); + out.flush(); + out.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/hx_auto/src/main/java/com.hx.auto/GeneratorDaoUtil.java b/hx_auto/src/main/java/com.hx.auto/GeneratorDaoUtil.java new file mode 100644 index 0000000..3ba6837 --- /dev/null +++ b/hx_auto/src/main/java/com.hx.auto/GeneratorDaoUtil.java @@ -0,0 +1,110 @@ +package com.hx.auto; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.util.HashMap; + +import com.hx.auto.common.UrlData; +import com.hx.auto.util.CommonTool; + +import freemarker.template.Configuration; +import freemarker.template.DefaultObjectWrapper; +import freemarker.template.Template; + +/** + * 鑷姩鐢熸垚DAO + * @author chenjiahe 2019骞�09鏈�08鏃�16:57:47 + * + */ +public class GeneratorDaoUtil { + + private static String templateDir = "/ftl";//鑾峰彇妯℃澘璺緞 + private static String templateName = "Dao.tpl";//action妯℃澘鍚嶇О + + /**鐢熸垚Dao + * @param cl 瀹炰綋绫� + * @param urlData 鐢熸垚閰嶇疆淇℃伅 + * @throws Exception + */ + public static void generatorDao(Class<?> cl,UrlData urlData) throws Exception { + try { + // 鍙嶅皠start + // 绫诲悕 + String entityName = cl.getSimpleName(); + // 绫诲悕棣栧瓧姣嶅皬鍐� + String initial = entityName.substring(0, 1).toLowerCase(); + String entityNameSmall = initial + entityName.substring(1, entityName.length()); + + //鐢熸垚鏂囦欢璺緞 + String targetFile = urlData.getDaoUrl()[1].replace(".", "/")+"/"; + //鐢熸垚鏂囦欢鍚嶇О + targetFile += entityName + "Mapper.java"; + //鏄犲皠鏂囦欢鐨勬枃浠跺す + //琛ュ叏璺緞 + targetFile = "./"+urlData.getDaoUrl()[0].replace(".", "/")+"/"+targetFile; + File file = new File(targetFile); + if(file.exists()){ + //System.out.println("瀛樺湪333...:"); + //瀛樺湪灏辩粨鏉� + return; + } + + //鑾峰彇瀹炰綋绫诲寘鍚� + String[] strs = cl.getName().split("\\."); + String packageName = ""; + //鍘绘帀绫诲悕 + for(int i=0;i<strs.length-1;i++) { + packageName += "."+strs[i]; + } + packageName = packageName.replaceFirst(".", ""); + + //鑾峰彇妯℃澘 + Configuration configuration = new Configuration(Configuration.getVersion()); + configuration.setClassForTemplateLoading(GeneratorDaoUtil.class, templateDir); + //configuration.setTemplateLoader(new ClassTemplateLoader(this.getClass(), "濉綘鐨剅esource涓嬬殑璺緞锛屾瘮濡�/ftl")); + Template template = configuration.getTemplate(templateName); + + // 鍒涘缓鏁版嵁妯″瀷 + HashMap<String, Object> root = new HashMap<String, Object>(); + + //action鍖呭悕 + if(!CommonTool.checkNotNull(urlData.getActionUrl())) { + System.err.println("娌℃湁鐢熸垚action璺緞"); + return; + } + root.put("packageName",urlData.getActionUrl()[1]); + //瀹炰綋绫荤殑绫诲悕 + root.put("entityName", entityName); + //瀹炰綋绫荤殑绫诲悕锛堥瀛楁瘝灏忓啓锛� + root.put("entityNameSmall", entityNameSmall); + + //dao鐨勫寘鍚� + if(!CommonTool.checkNotNull(urlData.getDaoUrl())) { + System.err.println("娌℃湁dao璺緞"); + return; + } + + if(!CommonTool.checkNotNull(urlData.getTotalUrl())) { + System.err.println("娌℃湁璁剧疆鎬诲寘璺緞"); + return; + } + root.put("TotalPackageName",urlData.getTotalUrl()); + root.put("DAOPackageName",urlData.getDaoUrl()[1]); + //瀹炰綋绫荤殑鍖呭悕 + root.put("entityPackageName",packageName); + + System.out.println("actionUrl:"+targetFile); + // 灏嗘ā鏉垮拰鏁版嵁妯″瀷鍚堝苟 杈撳嚭鍒癈onsole + Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile), "UTF-8")); + template.process(root, out); + out.flush(); + out.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/hx_auto/src/main/java/com.hx.auto/GeneratorMapperUtil.java b/hx_auto/src/main/java/com.hx.auto/GeneratorMapperUtil.java new file mode 100644 index 0000000..556d133 --- /dev/null +++ b/hx_auto/src/main/java/com.hx.auto/GeneratorMapperUtil.java @@ -0,0 +1,176 @@ +package com.hx.auto; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.zip.ZipOutputStream; + +import com.gitee.sunchenbin.mybatis.actable.annotation.Column; +import com.gitee.sunchenbin.mybatis.actable.annotation.Table; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlTypeConstant; +import com.hx.auto.common.JdbcType; +import com.hx.auto.common.ReadEntityData; +import com.hx.auto.common.UrlData; +import com.hx.auto.util.CommonTool; + +import com.hx.auto.util.GeneratorClassParentUtil; +import freemarker.template.Configuration; +import freemarker.template.DefaultObjectWrapper; +import freemarker.template.Template; + +/** + * 鑷姩鐢熸垚mapper.xml + * + * @author chenjiahe 2019骞�09鏈�08鏃�23:57:47 + * + */ +public class GeneratorMapperUtil { + + private static String templateDir = "/ftl";//鑾峰彇妯℃澘璺緞 + private static String templateName = "Mapper.tpl";//action妯℃澘鍚嶇О + + /**鐢熸垚mapper.xml + * @param cl 瀹炰綋绫� + * @param urlData 鐢熸垚閰嶇疆淇℃伅 + * @throws Exception + */ + public static void generatorMapper(Class<?> cl,UrlData urlData) throws Exception { + try { + // 鍙嶅皠start + // 绫诲悕 + String entityName = cl.getSimpleName(); + // 绫诲悕棣栧瓧姣嶅皬鍐� + String initial = entityName.substring(0, 1).toLowerCase(); + String entityNameSmall = initial + entityName.substring(1, entityName.length()); + + //鑾峰彇瀹炰綋绫诲寘鍚� + String[] strs = cl.getName().split("\\."); + String packageName = ""; + //鍘绘帀绫诲悕 + for(int i=0;i<strs.length-1;i++) { + packageName += "."+strs[i]; + } + packageName = packageName.replaceFirst(".", ""); + + //鑾峰彇妯℃澘 + Configuration configuration = new Configuration(Configuration.getVersion()); + configuration.setClassForTemplateLoading(GeneratorMapperUtil.class, templateDir); + //configuration.setTemplateLoader(new ClassTemplateLoader(this.getClass(), "濉綘鐨剅esource涓嬬殑璺緞锛屾瘮濡�/ftl")); + Template template = configuration.getTemplate(templateName); + + //瀹炰綋绫绘墍鏈夌殑瀛楁 + //鐢ㄦ潵瀛樺偍鏁版嵁 + ReadEntityData readEntityData = new ReadEntityData(); + //琛ㄥ悕绉� + Table table = cl.getAnnotation(Table.class); + readEntityData.setTableName(table.name()); + // 鍙栧緱鏈被鐨勫叏閮ㄥ睘鎬� + Field[] fields = cl.getDeclaredFields(); + fields = GeneratorClassParentUtil.getPatentFields(fields,cl); + for (Field field:fields) { + // 鍒ゆ柇鏂规硶涓槸鍚︽湁鎸囧畾娉ㄨВ绫诲瀷鐨勬敞瑙� + boolean hasAnnotation = field.isAnnotationPresent(Column.class); + if (hasAnnotation) { + // 鏍规嵁娉ㄨВ绫诲瀷杩斿洖鏂规硶鐨勬寚瀹氱被鍨嬫敞瑙� + Column column = field.getAnnotation(Column.class); + + //鍒ゆ柇鏄笉鏄� + boolean isBol = false; + Integer isBlob = 0; + if(column.type().equals(MySqlTypeConstant.TEXT)||column.type().equals(MySqlTypeConstant.LONGTEXT) + ||column.type().equals(MySqlTypeConstant.LONGBLOB)){ + isBol = true; + isBlob = 1; + } + + //绫诲瀷 + //String type = column.type().toUpperCase(); + String type = JdbcType.jdbcTypeData(field.getType().getTypeName().toUpperCase(),isBol); + //涓婚敭 + if (column.isKey()) { + readEntityData.setEntityIdName(field.getName()); + readEntityData.setEntityIdData("#{"+field.getName()+"}"); + if(!CommonTool.checkNotNull(column.name())) { + readEntityData.setTableIdName(field.getName()); + }else { + readEntityData.setTableIdName(column.name()); + } + readEntityData.setKeyType(type); + continue; + } + //瀛樺偍鏁版嵁 + if(!CommonTool.checkNotNull(column.name())) { + readEntityData.fielData(field.getName(),field.getName(),type,isBlob,"#{"+field.getName()+"}"); + }else { + readEntityData.fielData(field.getName(),column.name(),type,isBlob,"#{"+field.getName()+"}"); + } + } + } + // 鍒涘缓鏁版嵁妯″瀷 + HashMap<String, Object> root = new HashMap<String, Object>(); + + //action鍖呭悕 + if(!CommonTool.checkNotNull(urlData.getActionUrl())) { + System.err.println("娌℃湁鐢熸垚action璺緞"); + return; + } + if(!CommonTool.checkNotNull(urlData.getTotalUrl())) { + System.err.println("娌℃湁璁剧疆鎬诲寘璺緞"); + return; + } + root.put("TotalPackageName",urlData.getTotalUrl()); + root.put("packageActionName",urlData.getActionUrl()[1]); + root.put("packageEntityName",packageName); + //瀹炰綋绫荤殑绫诲悕 + root.put("entityName", entityName); + //瀹炰綋绫荤殑绫诲悕锛堥瀛楁瘝灏忓啓锛� + root.put("entityNameSmall", entityNameSmall); + //琛ㄥ瓧娈� 鏁版嵁 + root.put("fieldData",readEntityData); + + root.put("sqlSentence","${sqlSentence}"); + //root.put("sqlSentence","${sqlSentence}"); + //root.put("sqlSentence","${sqlSentence}"); + + //dao鐨勫寘鍚� + if(!CommonTool.checkNotNull(urlData.getDaoUrl())) { + System.err.println("娌℃湁dao璺緞"); + return; + } + root.put("DAOPackageName",urlData.getDaoUrl()[1]); + //瀹炰綋绫荤殑鍖呭悕 + root.put("entityPackageName",packageName); + + //鐢熸垚鏂囦欢璺緞 + String targetFile = urlData.getMapperUrl()[1].replace(".", "/")+"/"; + //鐢熸垚鏂囦欢鍚嶇О + targetFile += entityName + "Mapper.xml"; + //琛ュ叏璺緞 + targetFile = "./"+urlData.getMapperUrl()[0].replace(".", "/")+"/"+targetFile; + //鑾峰彇鏄惁宸茬粡鐢熸垚杩囨枃浠讹紝鎷垮彇鑷畾涔夌殑鍐呭 + String xmlStr = GeneratorReadXmlUtil.readMapperXml(targetFile); + if(!"false".equals(xmlStr)){ + root.put("customData",GeneratorReadXmlUtil.readMapperXml(targetFile)); + }else{ + root.put("customData",""); + } + + System.out.println("mapperUrl:"+targetFile); + // 灏嗘ā鏉垮拰鏁版嵁妯″瀷鍚堝苟 杈撳嚭鍒癈onsole + Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile), "UTF-8")); + template.process(root, out); + + + + out.flush(); + out.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/hx_auto/src/main/java/com.hx.auto/GeneratorServiceUtil.java b/hx_auto/src/main/java/com.hx.auto/GeneratorServiceUtil.java new file mode 100644 index 0000000..14a9103 --- /dev/null +++ b/hx_auto/src/main/java/com.hx.auto/GeneratorServiceUtil.java @@ -0,0 +1,121 @@ +package com.hx.auto; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.util.HashMap; + +import com.hx.auto.common.UrlData; +import com.hx.auto.util.CommonTool; +import freemarker.template.Configuration; +import freemarker.template.DefaultObjectWrapper; +import freemarker.template.Template; +import freemarker.template.TemplateException; + +/** + * 鑷姩鐢熸垚Service and ServiceImpl + * + * @author chenjiahe 2019骞�09鏈�08鏃�16:57:47 + * + */ +public class GeneratorServiceUtil { + + private static String templateDir = "/ftl";//鑾峰彇妯℃澘璺緞 + + private static String templateServiceName = "Service.tpl";//service鍚嶇О + private static String templateServiceImplName = "ServiceImpl.tpl";//serviceImpl鍚嶇О + /** + * @param cl 瀹炰綋绫� + * @param urlData 閰嶇疆淇℃伅 + * @throws Exception + */ + @SuppressWarnings("deprecation") + public static void generatorService(Class<?> cl, UrlData urlData) throws Exception { + try { + //鑾峰彇绫荤殑鍖呭悕 + String className = cl.getSimpleName(); + String[] strs = cl.getName().split("\\."); + String packageName = ""; + for(int i=0;i<strs.length-1;i++) { + packageName += "."+strs[i]; + } + packageName = packageName.replaceFirst(".",""); + + // 绫诲悕棣栧瓧姣嶅皬鍐� + String initial = className.substring(0, 1).toLowerCase(); + String classNamex = initial + className.substring(1, className.length()); + // 鍙栧緱鏈被鐨勫叏閮ㄥ睘鎬� + + String targetFile = urlData.getServiceUrl()[1].replace(".", "/")+"/"; + targetFile += className + "Service.java"; + //琛ュ叏璺緞 + targetFile = "./"+urlData.getServiceUrl()[0].replace(".", "/")+"/"+targetFile; + File fileService = new File(targetFile); + if(fileService.exists()){ + //瀛樺湪灏辩粨鏉� + return; + } + + + String targetFile2 = urlData.getServiceImplUrl()[1].replace(".", "/")+"/"; + targetFile2 += className + "ServiceImpl.java"; + //琛ュ叏璺緞 + targetFile2 = "./"+urlData.getServiceImplUrl()[0].replace(".", "/")+"/"+targetFile2; + File fileServiceImple = new File(targetFile2); + if(fileServiceImple.exists()){ + System.out.println("fileServiceImple:"+targetFile2); + //瀛樺湪灏辩粨鏉� + return; + } + + //鑾峰彇妯℃澘 + Configuration configuration = new Configuration(Configuration.getVersion()); + configuration.setClassForTemplateLoading(GeneratorServiceUtil.class, templateDir); + //configuration.setTemplateLoader(new ClassTemplateLoader(this.getClass(), "濉綘鐨剅esource涓嬬殑璺緞锛屾瘮濡�/ftl")); + + // 鑾峰彇鎴栧垱寤烘ā鏉� + Template template = configuration.getTemplate(templateServiceName); + + // 鍒涘缓鏁版嵁妯″瀷 + HashMap<String, Object> root = new HashMap<String, Object>(); + root.put("className", classNamex); + root.put("classNameUP", className); + root.put("packageName", packageName); + root.put("servicePack", urlData.getServiceUrl()[1]); + root.put("actionPack", urlData.getActionUrl()[1]); + + + System.out.println("serviceUrl:"+targetFile); + // 灏嗘ā鏉垮拰鏁版嵁妯″瀷鍚堝苟 杈撳嚭鍒癈onsole + Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile), "UTF-8")); + template.process(root, out); + out.flush(); + out.close(); + + if(!CommonTool.checkNotNull(urlData.getTotalUrl())) { + System.err.println("娌℃湁璁剧疆鎬诲寘璺緞"); + return; + } + root.put("TotalPackageName",urlData.getTotalUrl()); + root.put("serviceImpPack", urlData.getServiceImplUrl()[1]); + root.put("daoPack", urlData.getDaoUrl()[1]); + //serviceImp鏂囦欢 + // 鑾峰彇鎴栧垱寤烘ā鏉� + Template template2 = configuration.getTemplate(templateServiceImplName); + + System.out.println("serviceImpUrl:"+targetFile2); + // 灏嗘ā鏉垮拰鏁版嵁妯″瀷鍚堝苟 杈撳嚭鍒癈onsole + Writer out2 = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile2), "UTF-8")); + template2.process(root, out2); + out2.flush(); + out2.close(); + } catch (IOException e) { + e.printStackTrace(); + } catch (TemplateException e) { + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/hx_auto/src/main/java/com.hx.auto/GeneratorUtil.java b/hx_auto/src/main/java/com.hx.auto/GeneratorUtil.java new file mode 100644 index 0000000..bc84bb5 --- /dev/null +++ b/hx_auto/src/main/java/com.hx.auto/GeneratorUtil.java @@ -0,0 +1,256 @@ +package com.hx.auto; + +import java.io.File; +import java.io.FileFilter; +import java.io.IOException; +import java.net.URL; +import java.net.URLDecoder; +import java.util.Enumeration; +import java.util.LinkedHashSet; +import java.util.Set; + +import com.gitee.sunchenbin.mybatis.actable.annotation.Table; +import com.hx.auto.common.UrlData; + +/** + * 鑷姩鐢熸垚宸ュ叿 + * 2019-08-29 + * @author hx + * + */ +public class GeneratorUtil { + + public static void main(String[] args) throws Exception { + System.out.println("寮�濮�"); + UrlData urlData = new UrlData(); + urlData.setTotalUrl("com.hx"); + urlData.actionUrlData("src.main.java","com.hx.controller.admin"); + urlData.daoUrlData("src.main.java","com.hx.dao.mapper"); + urlData.serviceUrlData("src.main.java","com.hx.service"); + urlData.serviceImplUrlData("src.main.java","com.hx.service.impl"); + urlData.mapperUrlData("src.main.java", "com.hx.dao.mapperXml"); + + /*//dao + generatorDao(SysAdmin.class,urlData); + //mapper + generatorMapper(SysAdmin.class, urlData); + //action + generatorAction(SysAdmin.class,urlData); + // 鐢熸垚service + generatorService(SysAdmin.class,urlData);*/ + + //generatorTableByPackUrl(packPath, urlData); + + /*Class cl = TestM2.class; + Field[] fields = cl.getDeclaredFields(); + for(Field field:fields) { + System.out.println("field.getName():"+field.getName()); + System.out.println("field.getType():"+field.getType()); + System.out.println("field.getGenericType():"+field.getGenericType()); + System.out.println("field.getModifiers():"+field.getModifiers()); + }*/ + + //StringBuffer stringBuffer = SimpleToolUtil.getFileContent("com/hx/auto/file/test.txt"); + //System.out.println("stringBuffer:"+stringBuffer); + } + + /**閫氳繃鍖呰矾寰勮幏鍙杧ml鍜宮apper + * + * @param packPath 鍖呰矾寰� + * @param urlData 鐢熸垚鏂囦欢鐨勯厤缃� + */ + public static <T> void generatorXmlAndMapper(String packPath,UrlData urlData) { + try { + Set<Class<?>> classes = classData(packPath); + for(Class<?> cl:classes) { + //action + //generatorAction(cl,urlData); + //dao + generatorDao(cl,urlData); + //mapper.xml + generatorMapper(cl, urlData); + // 鐢熸垚service + //generatorService(cl,urlData); + } + }catch (Exception e) { + e.printStackTrace(); + } + } + + /**閫氳繃鍖呰矾寰勮幏鍙栨墍鏈夋枃浠� + * + * @param packPath 鍖呰矾寰� + * @param urlData 鐢熸垚鏂囦欢鐨勯厤缃� + */ + public static <T> void generatorTableByPackUrl(String packPath,UrlData urlData) { + try { + Set<Class<?>> classes = classData(packPath); + for(Class<?> cl:classes) { + //action + generatorAction(cl,urlData); + //dao + generatorDao(cl,urlData); + //mapper.xml + generatorMapper(cl, urlData); + // 鐢熸垚service + generatorService(cl,urlData); + } + }catch (Exception e) { + e.printStackTrace(); + } + } + + /**鑷姩鐢熸垚dao鏂囦欢 + * + * @param cl 鎸囧畾鐢熸垚绫� + * @param urlData 鐢熸垚鏂囦欢鐨勯厤缃枃浠� + */ + public static <T> void generatorDao(Class<?> cl,UrlData urlData) { + try { + //鍒ゆ柇鏄惁鏈夋爣蹇楋紝娌℃湁鏍囧織灏辫烦杩� + if (null != cl.getAnnotation(Table.class)) { + // 鐢熸垚action + GeneratorDaoUtil.generatorDao(cl,urlData); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + /**鑷姩鐢熸垚mapper.xml鏂囦欢 + * + * @param cl 鎸囧畾鐢熸垚绫� + * @param urlData 鐢熸垚鏂囦欢鐨勯厤缃枃浠� + */ + public static <T> void generatorMapper(Class<?> cl,UrlData urlData) { + try { + //鍒ゆ柇鏄惁鏈夋爣蹇楋紝娌℃湁鏍囧織灏辫烦杩� + if (null != cl.getAnnotation(Table.class)) { + // 鐢熸垚action + GeneratorMapperUtil.generatorMapper(cl, urlData); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + + /**鑷姩鐢熸垚action鏂囦欢 + * + * @param cl 鎸囧畾鐢熸垚绫� + * @param urlData 鐢熸垚鏂囦欢鐨勯厤缃枃浠� + */ + public static <T> void generatorAction(Class<?> cl,UrlData urlData) { + try { + //鐢熸垚鍔ㄦ�乻ql鐨勬枃浠讹紙sqlSentence.java锛�,宸茬粡鐢熸垚灏变笉鐢ㄧ敓鎴�,鍚﹀垯浼氳鐩� + /*if(sqlParam) { + GeneratorsqlSentenceUtil.GeneratorsqlSentence(urlData); + }*/ + //鍒ゆ柇鏄惁鏈夋爣蹇楋紝娌℃湁鏍囧織灏辫烦杩� + if (null != cl.getAnnotation(Table.class)) { + // 鐢熸垚action + GeneratorActionUtil.generatorAction(cl, urlData, false); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + /**鑷姩鐢熸垚Service and ServiceImpl鏂囦欢 + * + * @param cl 鎸囧畾鐢熸垚绫� + * @param urlData 鐢熸垚鏂囦欢鐨勯厤缃枃浠� + */ + public static <T> void generatorService(Class<?> cl,UrlData urlData) { + try { + //鍒ゆ柇鏄惁鏈夋爣蹇楋紝娌℃湁鏍囧織灏辫烦杩� + if (null != cl.getAnnotation(Table.class)) { + // 鐢熸垚action + GeneratorServiceUtil.generatorService(cl,urlData); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + /**鑾峰彇鍖呬笅闈㈢殑鎵�鏈夋枃浠�*/ + public static Set<Class<?>> classData(String packPath){ + Set<Class<?>> classes = new LinkedHashSet<Class<?>>(); + // 鏄惁寰幆杩唬 + boolean recursive = true; + // 鑾峰彇鍖呯殑鍚嶅瓧 骞惰繘琛屾浛鎹� + String packageName = packPath; + String packageDirName = packageName.replace('.', '/'); + // 瀹氫箟涓�涓灇涓剧殑闆嗗悎 骞惰繘琛屽惊鐜潵澶勭悊杩欎釜鐩綍涓嬬殑things + Enumeration<URL> dirs; + try{ + dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName); + // 寰幆杩唬涓嬪幓 + while (dirs.hasMoreElements()){ + // 鑾峰彇涓嬩竴涓厓绱� + URL url = dirs.nextElement(); + // 寰楀埌鍗忚鐨勫悕绉� + String protocol = url.getProtocol(); + // 濡傛灉鏄互鏂囦欢鐨勫舰寮忎繚瀛樺湪鏈嶅姟鍣ㄤ笂 + if ("file".equals(protocol)) { + System.err.println("file绫诲瀷鐨勬壂鎻�:" + packPath); + // 鑾峰彇鍖呯殑鐗╃悊璺緞 + String filePath = URLDecoder.decode(url.getFile(), "UTF-8"); + // 浠ユ枃浠剁殑鏂瑰紡鎵弿鏁翠釜鍖呬笅鐨勬枃浠� 骞舵坊鍔犲埌闆嗗悎涓� + findAndAddClassesInPackageByFile(packageName, filePath, recursive, classes); + } + } + }catch (IOException e){ + e.printStackTrace(); + } + return classes; + } + + /** + * 浠ユ枃浠剁殑褰㈠紡鏉ヨ幏鍙栧寘涓嬬殑鎵�鏈塁lass + * + * @param packageName + * @param packagePath + * @param recursive + * @param classes + */ + public static void findAndAddClassesInPackageByFile( + String packageName, + String packagePath, + final boolean recursive, + Set<Class<?>> classes){ + // 鑾峰彇姝ゅ寘鐨勭洰褰� 寤虹珛涓�涓狥ile + File dir = new File(packagePath); + // 濡傛灉涓嶅瓨鍦ㄦ垨鑰� 涔熶笉鏄洰褰曞氨鐩存帴杩斿洖 + if (!dir.exists() || !dir.isDirectory()) { + // log.warn("鐢ㄦ埛瀹氫箟鍖呭悕 " + packageName + " 涓嬫病鏈変换浣曟枃浠�"); + return; + } + // 濡傛灉瀛樺湪 灏辫幏鍙栧寘涓嬬殑鎵�鏈夋枃浠� 鍖呮嫭鐩綍 + File[] dirfiles = dir.listFiles(new FileFilter(){ + // 鑷畾涔夎繃婊よ鍒� 濡傛灉鍙互寰幆(鍖呭惈瀛愮洰褰�) 鎴栧垯鏄互.class缁撳熬鐨勬枃浠�(缂栬瘧濂界殑java绫绘枃浠�) + public boolean accept(File file){ + return (recursive && file.isDirectory()) || (file.getName().endsWith(".class")); + } + }); + // 寰幆鎵�鏈夋枃浠� + for (File file : dirfiles){ + // 濡傛灉鏄洰褰� 鍒欑户缁壂鎻� + if (file.isDirectory()) { + findAndAddClassesInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), recursive, classes); + }else{ + // 濡傛灉鏄痡ava绫绘枃浠� 鍘绘帀鍚庨潰鐨�.class 鍙暀涓嬬被鍚� + String className = file.getName().substring(0, file.getName().length() - 6); + try{ + // 娣诲姞鍒伴泦鍚堜腑鍘� + // classes.add(Class.forName(packageName + '.' + + // className)); + // 缁忚繃鍥炲鍚屽鐨勬彁閱掞紝杩欓噷鐢╢orName鏈変竴浜涗笉濂斤紝浼氳Е鍙憇tatic鏂规硶锛屾病鏈変娇鐢╟lassLoader鐨刲oad骞插噣 + classes.add(Thread.currentThread().getContextClassLoader().loadClass(packageName + '.' + className)); + }catch (ClassNotFoundException e){ + // log.error("娣诲姞鐢ㄦ埛鑷畾涔夎鍥剧被閿欒 鎵句笉鍒版绫荤殑.class鏂囦欢"); + e.printStackTrace(); + } + } + } + } +} \ No newline at end of file diff --git a/hx_auto/src/main/java/com.hx.auto/common/JdbcType.java b/hx_auto/src/main/java/com.hx.auto/common/JdbcType.java new file mode 100644 index 0000000..33cc2b6 --- /dev/null +++ b/hx_auto/src/main/java/com.hx.auto/common/JdbcType.java @@ -0,0 +1,51 @@ +package com.hx.auto.common; + +/**javaType鍜宩dbcType瀵规瘮 + * + * @author chenjiahe + * + */ +public class JdbcType { + + /** + * @param type 瀛楁绫诲瀷 + * @param isBol 鏄惁闀垮瓧绗︿覆 + * @return + */ + public static String jdbcTypeData(String type,boolean isBol) { + //瀛楁瘝杞寲涓哄皬瀛楁瘝 + type = type.toLowerCase(); + if(type.equals("java.lang.string")) { + if(!isBol) { + type = "VARCHAR"; + }else { + type = "LONGVARCHAR"; + } + }else if(type.equals("int")) { + type = "INTEGER"; + }else if(type.equals("java.lang.integer")) { + type = "INTEGER"; + }else if(type.equals("boolean")) { + type = "BOOLEAN"; + }else if(type.equals("byte")) { + type = "TINYINT"; + }else if(type.equals("short")) { + type = "SMALLINT"; + }else if(type.equals("long")) { + type = "BIGINT"; + }else if(type.equals("float")) { + type = "REAL"; + }else if(type.equals("double")) { + type = "DOUBLE"; + }else if(type.equals("java.lang.double")) { + type = "DOUBLE"; + }else if(type.equals("java.util.date")) { + type = "TIMESTAMP"; + }else if(type.equals("java.sql.date")) { + type = "TIMESTAMP"; + }else if(type.equals("blob")) { + type = "BLOB"; + } + return type; + } +} diff --git a/hx_auto/src/main/java/com.hx.auto/common/Lob.java b/hx_auto/src/main/java/com.hx.auto/common/Lob.java new file mode 100644 index 0000000..6853a2c --- /dev/null +++ b/hx_auto/src/main/java/com.hx.auto/common/Lob.java @@ -0,0 +1,25 @@ +package com.hx.auto.common; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + + +/**闀垮瓧绗︿覆 + * @author chenjiahe + * @version 2019骞�09鏈�14鏃� 涓嬪崍6:13:37 + */ +//琛ㄧず娉ㄨВ鍔犲湪鎺ュ彛銆佺被銆佹灇涓剧瓑 +@Target(ElementType.TYPE) +//VM灏嗗湪杩愯鏈熶篃淇濈暀娉ㄩ噴锛屽洜姝ゅ彲浠ラ�氳繃鍙嶅皠鏈哄埗璇诲彇娉ㄨВ鐨勪俊鎭� +@Retention(RetentionPolicy.RUNTIME) +//灏嗘娉ㄨВ鍖呭惈鍦╦avadoc涓� +@Documented +//鍏佽瀛愮被缁ф壙鐖剁被涓殑娉ㄨВ +@Inherited +public @interface Lob { + +} diff --git a/hx_auto/src/main/java/com.hx.auto/common/ReadEntityData.java b/hx_auto/src/main/java/com.hx.auto/common/ReadEntityData.java new file mode 100644 index 0000000..a257e32 --- /dev/null +++ b/hx_auto/src/main/java/com.hx.auto/common/ReadEntityData.java @@ -0,0 +1,154 @@ +package com.hx.auto.common; + +import java.util.ArrayList; +import java.util.List; + +/**瀹炰綋绫诲搴旂敓鎴恗apper.xml鐨勬暟鎹�*/ +public class ReadEntityData { + //瀹炰綋绫荤殑涓婚敭id鍚嶇О + private String entityIdName; + //琛ㄧ殑涓婚敭id鍚嶇О + private String tableIdName; + //涓婚敭绫诲瀷 + private String keyType; + //琛ㄧ殑鍚嶇О + private String tableName; + //瀹炰綋绫诲拰琛ㄧ殑鎵�鏈夊瓧娈靛悕绉帮紙闄や簡涓婚敭锛� + private List<FieldAttribute> fields = new ArrayList<FieldAttribute>(); + //鐗规畩瀛楁锛屼富閿甶d,濡傦細#{id} + private String entityIdData; + //鐗规畩瀛楁锛宮ybatis鐨勬帓搴� + private String orderBy = "${orderBy}"; + //鐗规畩瀛楁锛宮ybatis鐨勫疄浣撶被鍖归厤琛ㄥ瓧娈� + private String createData = "#{createData.obj}"; + //鐗规畩瀛楁锛宮ybatis鐨勪紶鐨勫�� + private String valueData = "#{value}"; + + /********************************************************************/ + /** 瀛樺偍瀹炰綋绫荤殑琛ㄥ瓧娈� + * @param entityName 瀹炰綋绫诲瓧娈靛悕绉� + * @param tableName1 琛ㄥ悕绉� + * @param dataType 绫诲瀷 + */ + public void fielData(String entityName,String tableName1,String dataType,Integer isBlob,String mybatisName) { + fields.add(new FieldAttribute(entityName,tableName1, dataType,isBlob,mybatisName)); + } + + /******************************************************************/ + public String getEntityIdName() { + return entityIdName; + } + public void setEntityIdName(String entityIdName) { + this.entityIdName = entityIdName; + } + public String getTableIdName() { + return tableIdName; + } + public void setTableIdName(String tableIdName) { + this.tableIdName = tableIdName; + } + public String getTableName() { + return tableName; + } + public void setTableName(String tableName) { + this.tableName = tableName; + } + public List<FieldAttribute> getFields() { + return fields; + } + public void setFields(List<FieldAttribute> fields) { + this.fields = fields; + } + public String getOrderBy() { + return orderBy; + } + public void setOrderBy(String orderBy) { + this.orderBy = orderBy; + } + public String getKeyType() { + return keyType; + } + public void setKeyType(String keyType) { + this.keyType = keyType; + } + + public String getCreateData() { + return createData; + } + public void setCreateData(String createData) { + this.createData = createData; + } + public String getValueData() { + return valueData; + } + + public void setValueData(String valueData) { + this.valueData = valueData; + } + + public String getEntityIdData() { + return entityIdData; + } + + public void setEntityIdData(String entityIdData) { + this.entityIdData = entityIdData; + } + + /*****************************************************************/ + public static class FieldAttribute { + //瀹炰綋绫诲瓧娈靛悕绉� + private String entityName; + //琛ㄥ瓧娈靛悕绉� + private String tableName; + //鏁版嵁搴撶被鍨� + private String dataType; + //鏄惁澶ф暟鎹� + private Integer isBlob = 0; + //鐗规畩瀛楁,濡傚湪mybati涓� #{id}鐨勮〃绀� + private String mybatisName; + + /**********************************/ + public FieldAttribute(String entityName,String tableName,String dataType,Integer isBlob + ,String mybatisName) { + this.entityName = entityName; + this.tableName = tableName; + this.dataType = dataType; + this.isBlob = isBlob; + this.mybatisName = mybatisName; + } + + /*********************************/ + public String getDataType() { + return dataType; + } + public void setDataType(String dataType) { + this.dataType = dataType; + } + public String getEntityName() { + return entityName; + } + public void setEntityName(String entityName) { + this.entityName = entityName; + } + public String getTableName() { + return tableName; + } + public void setTableName(String tableName) { + this.tableName = tableName; + } + public Integer getIsBlob() { + return isBlob; + } + public void setIsBlob(Integer isBlob) { + this.isBlob = isBlob; + } + + public String getMybatisName() { + return mybatisName; + } + public void setMybatisName(String mybatisName) { + this.mybatisName = mybatisName; + } + } +} + diff --git a/hx_auto/src/main/java/com.hx.auto/common/UrlData.java b/hx_auto/src/main/java/com.hx.auto/common/UrlData.java new file mode 100644 index 0000000..baf7aa8 --- /dev/null +++ b/hx_auto/src/main/java/com.hx.auto/common/UrlData.java @@ -0,0 +1,105 @@ +package com.hx.auto.common; + +/**灞炴�т繚瀛�*/ +public class UrlData { + + /**鎬诲寘*/ + private String totalUrl; + /**鐢熸垚action鐨勫寘璺緞*/ + private String[] actionUrl; + /**鐢熸垚mapper.xml璺緞*/ + private String[] mapperUrl; + /**鐢熸垚DAO鐨勫寘璺緞*/ + private String[] daoUrl; + /**鐢熸垚service鎺ュ彛鐨勫寘璺緞*/ + private String[] serviceUrl; + /**鐢熸垚serviceImpl鎺ュ彛鐨勫寘璺緞*/ + private String[] serviceImplUrl; + /**********************************/ + /** + * 涓�涓嬬被寮曞叆鐨勮矾寰勯渶瑕� + * @param totalUrl 鎬诲寘锛屽锛歝om.songSir + */ + public void totalUrlData(String totalUrl){ + this.totalUrl = totalUrl; + } + + /**鐢熸垚action鐨勫寘璺緞 + * @param packRoot 鏍圭洰褰曪紝濡傦細src.main.java + * @param actionPack 鍖呯洰褰曪紝濡傦細com.songSir.model + */ + public void actionUrlData(String packRoot,String actionPack) { + actionUrl = new String[] {packRoot,actionPack}; + } + /**鐢熸垚mapper.xml璺緞 + * + * @param packRoot 鏍圭洰褰曪紝濡傦細src.main.java + * @param mapperPack 鍖呯洰褰�/鏂囦欢鐩綍锛屽锛歝om.songSir.mapper 鎴栬�� com/songSir/mapper + */ + public void mapperUrlData(String packRoot,String mapperPack) { + mapperUrl = new String[] {packRoot,mapperPack}; + } + /**鐢熸垚DAO鐨勫寘璺緞 + * + * @param packRoot 鏍圭洰褰曪紝濡傦細src.main.java + * @param daoPack 鍖呯洰褰曪紝濡傦細com.songSir.dao + */ + public void daoUrlData(String packRoot,String daoPack) { + daoUrl = new String[] {packRoot,daoPack}; + } + /**鐢熸垚service鎺ュ彛鐨勫寘璺緞 + * + * @param packRoot 鏍圭洰褰曪紝濡傦細src.main.java + * @param servicePack 鍖呯洰褰曪紝濡傦細com.songSir.service + */ + public void serviceUrlData(String packRoot,String servicePack) { + serviceUrl = new String[] {packRoot,servicePack}; + } + /**鐢熸垚service鎺ュ彛鐨勫寘璺緞 + * + * @param packRoot 鏍圭洰褰曪紝濡傦細src.main.java + * @param serviceImpUrlPack 鍖呯洰褰曪紝濡傦細com.songSir.serviceImp + */ + public void serviceImplUrlData(String packRoot,String serviceImpUrlPack) { + serviceImplUrl = new String[] {packRoot,serviceImpUrlPack}; + } + /*********************************/ + public String[] getActionUrl() { + return actionUrl; + } + public void setActionUrl(String[] actionUrl) { + this.actionUrl = actionUrl; + } + public String[] getMapperUrl() { + return mapperUrl; + } + public void setMapperUrl(String[] mapperUrl) { + this.mapperUrl = mapperUrl; + } + public String[] getDaoUrl() { + return daoUrl; + } + public void setDaoUrl(String[] daoUrl) { + this.daoUrl = daoUrl; + } + public String[] getServiceUrl() { + return serviceUrl; + } + public void setServiceUrl(String[] serviceUrl) { + this.serviceUrl = serviceUrl; + } + public String[] getServiceImplUrl() { + return serviceImplUrl; + } + public void setServiceImplUrl(String[] serviceImplUrl) { + this.serviceImplUrl = serviceImplUrl; + } + + public String getTotalUrl() { + return totalUrl; + } + + public void setTotalUrl(String totalUrl) { + this.totalUrl = totalUrl; + } +} diff --git a/hx_auto/src/main/java/com/hx/auto/GeneratorReadXmlUtil.java b/hx_auto/src/main/java/com/hx/auto/GeneratorReadXmlUtil.java new file mode 100644 index 0000000..64c2a91 --- /dev/null +++ b/hx_auto/src/main/java/com/hx/auto/GeneratorReadXmlUtil.java @@ -0,0 +1,192 @@ +package com.hx.auto; + +import org.w3c.dom.Document; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import java.io.*; +import java.util.*; + +/** + * 鑷姩鐢熸垚Service and ServiceImpl + * + * @author chenjiahe 2020-06-28 + * + */ +public class GeneratorReadXmlUtil { + + /** + * + * @param targetFile 鏂囦欢璺緞 + * @return 杩斿洖鑷畾涔夌殑sql + */ + public static String readMapperXml(String targetFile) throws ParserConfigurationException, IOException, SAXException { + String temp = ""; + + //鏄犲皠鏂囦欢鐨勬枃浠跺す + File file = new File(targetFile); + if(!file.exists()){ + return "false"; + } + + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + Document doc = builder.parse(file); + Node Node= doc.getLastChild(); + NodeList nodeList = Node.getChildNodes(); + + String comment = ""; + for(int i=0;i<nodeList.getLength();i++) { + //浠庤妭鐐归泦涓幏鍙杋涓猙ook鑺傜偣 + Node childNode = nodeList.item(i); + //鑾峰彇瀛愯妭鐐瑰唴鐨勬枃鏈唴瀹� + String content = childNode.getTextContent(); + //鑾峰彇鑺傜偣鍚� + String name = childNode.getNodeName(); + //System.out.println("content:"+content+";name:"+name); + //System.out.println("name....:"+name); + if(!"#text".equals(name)&&!"#comment".equals(name)){ + //鑾峰彇绗竴涓妭鐐瑰唴鐨勬墍鏈夊睘鎬� + NamedNodeMap nameNodeMap = childNode.getAttributes(); + //鑾峰彇鑺傜偣鍐呭悕涓篿d鐨勫睘鎬х殑鍊� + String id = nameNodeMap.getNamedItem("id").getTextContent(); + if(isCustom(nameNodeMap.getNamedItem("id").getTextContent())){ + String con = NodetoString(childNode); + //鍘绘帀闄勫甫鐨勫唴瀹� + con = con.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>",""); + String con2 = con; + con = con.replaceAll("\t","").replaceAll("\n",""); + if(con.length()>3){ + con= con2; + } + temp+=comment+"\n\t"+con; + } + comment = ""; + }else{ + String con = NodetoString(childNode); + //鍘绘帀闄勫甫鐨勫唴瀹� + con = con.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>",""); + String con2 = con; + //鍘绘帀澶氫綑鐨� + con = con.replaceAll("\t","").replaceAll("\n",""); + if(con.length()>5){ + comment+= con2; + } + } + } + System.out.println("temp:...:"+temp); + return temp; + } + + public static boolean isCustom(String id){ + boolean custom = true; + Set<String> noCustomIds = new HashSet<String>(); + noCustomIds.add("BaseResultMap"); + noCustomIds.add("Entity_Id"); + noCustomIds.add("Table_Id"); + noCustomIds.add("Table_Name"); + noCustomIds.add("Base_Column_List"); + noCustomIds.add("Blob_Column_List"); + noCustomIds.add("Insert_Column_All"); + noCustomIds.add("Update_Column_All"); + noCustomIds.add("Update_Column_NoNull"); + noCustomIds.add("keyFind"); + noCustomIds.add("insert"); + noCustomIds.add("insertById"); + noCustomIds.add("selectList"); + noCustomIds.add("selectListBlob"); + noCustomIds.add("selectOne"); + noCustomIds.add("selectOneBlob"); + noCustomIds.add("selectOneByKey"); + noCustomIds.add("selectOneByKeyBlob"); + noCustomIds.add("updateWhere"); + noCustomIds.add("updateAll"); + noCustomIds.add("updateByNoNull"); + noCustomIds.add("deleteWhere"); + noCustomIds.add("deleteById"); + noCustomIds.add("selectCount"); + noCustomIds.add("Insert_Values_All"); + noCustomIds.add("selectListMap"); + noCustomIds.add("selectOneMap"); + noCustomIds.add("selectCountSql"); + if (noCustomIds.contains(id)){ + custom = false; + } + return custom; + } + + + + /* + * 鎶奷om鏂囦欢杞崲涓簒ml瀛楃涓� + */ + public static String toStringFromDoc(Document document) throws IOException { + String result = null; + + if (document != null) { + StringWriter strWtr = new StringWriter(); + StreamResult strResult = new StreamResult(strWtr); + TransformerFactory tfac = TransformerFactory.newInstance(); + try { + javax.xml.transform.Transformer t = tfac.newTransformer(); + t.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); + t.setOutputProperty(OutputKeys.INDENT, "yes"); + t.setOutputProperty(OutputKeys.METHOD, "xml"); // xml, html, +// text + t.setOutputProperty( + "{http://xml.apache.org/xslt}indent-amount", "4"); + t.transform(new DOMSource(document.getDocumentElement()), + strResult); + } catch (Exception e) { + System.err.println("XML.toString(Document): " + e); + } + result = strResult.getWriter().toString(); + strWtr.close(); + } + return result; + } + + + /** + * 灏嗕紶鍏ョ殑涓�涓狣OM Node瀵硅薄杈撳嚭鎴愬瓧绗︿覆銆傚鏋滃け璐ュ垯杩斿洖涓�涓┖瀛楃涓�""銆� + * + * @param node + * DOM Node 瀵硅薄銆� + * @return a XML String from node + */ + public static String NodetoString(Node node) { + Transformer transformer = null; + String result = null; + if (node == null) { + throw new IllegalArgumentException(); + } + try { + transformer = TransformerFactory.newInstance().newTransformer(); + } catch (Exception e) { + throw new RuntimeException(e.getMessage()); + } + if (transformer != null) { + try { + StringWriter sw = new StringWriter(); + transformer.transform(new DOMSource(node), new StreamResult(sw)); + return sw.toString(); + } catch (TransformerException te) { + throw new RuntimeException(te.getMessage()); + } + } + return result; + } + + +} \ No newline at end of file diff --git a/hx_auto/src/main/java/com/hx/auto/file/Action.tpl b/hx_auto/src/main/java/com/hx/auto/file/Action.tpl new file mode 100644 index 0000000..0aa4b1a --- /dev/null +++ b/hx_auto/src/main/java/com/hx/auto/file/Action.tpl @@ -0,0 +1,79 @@ +package ${packageName}; + +import java.util.List; +import javax.annotation.Resource; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; + +import com.hx.common.BaseController; +import com.hx.mybatisTool.SqlSentence; +import ${DAOPackageName}.${entityName}Mapper; +import ${entityPackageName}.${entityName}; +import ${servicePackageName}.${entityName}Service; +import com.hx.resultTool.Result; +import com.hx.util.SimpleTool; +import net.sf.json.JSONObject; +import com.hx.phitab.common.AuthConstants; + +@RestController +@RequestMapping("${entityNameSmall}") +public class ${entityName}Controller extends BaseController { + + @Resource + private ${entityName}Service service; + + /**鍒楄〃*/ + @Authority(tag = AuthConstants.${entityName}.SEE) + @RequestMapping("/list") + public Result listData(Integer pageNum,Integer pageSize) { + //pageNum褰撳墠绗嚑椤� + //rowCount 鎷垮嚑鏉� + + //鍒嗛〉鎻掍欢 + PageHelper.startPage(pageNum==null?1:pageNum,pageSize==null?20:pageSize); + SqlSentence sqlSentence = new SqlSentence(); + List<${entityName}> ${entityNameSmall}s = service.selectList(sqlSentence); + PageInfo pageInfo = new PageInfo<${entityName}>(${entityNameSmall}s); + Map<String,Object> data = new HashMap<>(); + data.put("pageNum",pageInfo.getPageNum()); + data.put("pageSize",pageInfo.getPageSize()); + data.put("total",pageInfo.getTotal()); + data.put("isLastPage",pageInfo.isIsLastPage()); + data.put("list",pageInfo.getList()); + return Result.success(data); + } + + /**鏂板*/ + @Authority(tag = AuthConstants.${entityName}.ADD) + @RequestMapping("/add") + public Result addData(${entityName} ${entityNameSmall}) { + service.insert(${entityNameSmall}); + return Result.success(); + } + + /**鑾峰彇鏁版嵁*/ + @Authority(tag = AuthConstants.${entityName}.SEE) + @RequestMapping("/see") + public Result editeData(String id) { + ${entityName} ${entityNameSmall} = service.selectOneByKeyBlob(id); + return Result.success(${entityNameSmall}); + } + + /**淇敼鏁版嵁*/ + @Authority(tag = AuthConstants.${entityName}.EDIT) + @RequestMapping("/update") + public Result updateData(${entityName} ${entityNameSmall}) { + service.updateAll(${entityNameSmall}); + return Result.success(); + } + + /**鍒犻櫎鏁版嵁锛堝崟涓級*/ + @Authority(tag = AuthConstants.${entityName}.DELETE) + @RequestMapping("/delete/one") + public Result deleteData(String id) { + service.deleteOne(id); + return Result.success(); + } +} diff --git a/hx_auto/src/main/java/com/hx/auto/file/Dao.tpl b/hx_auto/src/main/java/com/hx/auto/file/Dao.tpl new file mode 100644 index 0000000..74f5c5c --- /dev/null +++ b/hx_auto/src/main/java/com/hx/auto/file/Dao.tpl @@ -0,0 +1,35 @@ +package ${DAOPackageName}; + +import java.util.List; +import java.util.Map; +import com.hx.mybatisTool.SqlSentence; +import ${entityPackageName}.${entityName}; + +public interface ${entityName}Mapper { + /**鏂板锛岃繑鍥炰富閿�*/ + int insert(${entityName} ${entityNameSmall}); + /**鏂板锛岃繑鍥炰富閿�*/ + int insertById(${entityName} ${entityNameSmall}); + /**鏌ヨ鏉℃暟*/ + int selectCount(SqlSentence sqlSentence); + /**鏌ヨ鍒楄〃锛岃繑鍥炲疄浣撶被鐨凩ist*/ + List<${entityName}> selectList(SqlSentence sqlSentence); + /**鏌ヨ鍒楄〃锛岃繑鍥濵ap鐨凩ist*/ + List<Map<String,Object>> selectListMap(SqlSentence sqlSentence); + /**鏌ヨ锛岃繑鍥炲崟涓疄浣�*/ + ${entityName} selectOne(SqlSentence sqlSentence); + /**鏌ヨ锛岃繑鍥炲崟涓猰ap*/ + Map<String,Object> selectOneMap(SqlSentence sqlSentence); + /**鏌ヨ锛岃繑鍥炲疄浣撶被娌℃湁澶ф暟鎹殑*/ + ${entityName} selectOneByKey(Object object); + /**鏌ヨ锛岃繑鍥炲疄浣撶被鏈夊ぇ鏁版嵁鐨�*/ + ${entityName} selectOneByKeyBlob(Object object); + /**鏇存柊锛岃繑鍥炴洿鏂版暟閲�*/ + int updateWhere(SqlSentence sqlSentence); + /**鏇存柊锛岃繑鍥炴洿鏂版暟閲�*/ + int updateAll(${entityName} ${entityNameSmall}); + /**鍒犻櫎锛岃繑鍥炲垹闄ゆ暟閲�*/ + int deleteWhere(SqlSentence sqlSentence); + /**鍒犻櫎锛岃繑鍥炲垹闄ゆ暟閲�*/ + int deleteById(Object object); +} \ No newline at end of file diff --git a/hx_auto/src/main/java/com/hx/auto/file/Mapper.tpl b/hx_auto/src/main/java/com/hx/auto/file/Mapper.tpl new file mode 100644 index 0000000..a192d1a --- /dev/null +++ b/hx_auto/src/main/java/com/hx/auto/file/Mapper.tpl @@ -0,0 +1,83 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<!DOCTYPE mapper +PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" +"http://mybatis.org/dtd/mybatis-3-mapper.dtd"> +<!-- namespace:璇apper.xml鏄犲皠鏂囦欢鐨� 鍞竴鏍囪瘑 --> +<mapper namespace="${DAOPackageName}.${entityName}Mapper"> + + <!-- 鏁翠釜瀹炰綋绫讳慨鏀癸紝琛ㄥ瓧娈�=瀹炰綋绫诲瓧娈�--> + <sql id="Update_Column_All"> + <trim prefixOverrides=","> + <#list fieldData.fields as item>,${item.tableName} = ${item.mybatisName}</#list> + </trim> + </sql> + + <!-- 鍚庣画閫氳繃 namespace.id--> + <!--parameterType:杈撳叆鍙傛暟鐨勭被鍨� + resultType锛氭煡璇㈣繑鍥炵粨鏋滃�肩殑绫诲瀷 锛岃繑鍥炵被鍨� --> + <insert id="insert" parameterType="${packageEntityName}.${entityName}"> + <selectKey keyProperty="id" resultType="String" order="BEFORE"> + select replace(uuid(),'-','') from dual + </selectKey> + insert into ${fieldData.tableName} (${fieldData.tableIdName}<#list fieldData.fields as item>,${item.tableName}</#list>) + values (${fieldData.entityIdData}<#list fieldData.fields as item>,${item.mybatisName}</#list>) + </insert> + + <select id="selectList" resultType="${packageEntityName}.${entityName}" parameterType="com.hx.mybatisTool.SqlSentence" > + ${sqlSentence} + </select> + + <select id="selectListMap" resultType="java.util.Map" parameterType="com.hx.mybatisTool.SqlSentence" > + ${sqlSentence} + </select> + + <select id="selectOne" resultType="${packageEntityName}.${entityName}" parameterType="com.hx.mybatisTool.SqlSentence" > + ${sqlSentence} + </select> + + <select id="selectOneMap" resultType="java.util.Map" parameterType="com.hx.mybatisTool.SqlSentence" > + ${sqlSentence} + </select> + + <select id="selectCount" resultType="int" parameterType="com.hx.mybatisTool.SqlSentence" > + select + COUNT(*) + from ${fieldData.tableName} + WHERE ${sqlSentence} + </select> + + <select id="selectOneByKey" resultType="${packageEntityName}.${entityName}" parameterType="java.lang.Object" > + select + ${fieldData.tableIdName}<#list fieldData.fields as item>,${item.tableName}</#list> + from ${fieldData.tableName} + WHERE ${fieldData.tableIdName} = ${fieldData.valueData} + </select> + + <select id="selectOneByKeyBlob" resultType="${packageEntityName}.${entityName}" parameterType="java.lang.Object" > + select + ${fieldData.tableIdName}<#list fieldData.fields as item>,${item.tableName}</#list> + from ${fieldData.tableName} + WHERE ${fieldData.tableIdName} = ${fieldData.valueData} + </select> + + <update id="updateWhere" parameterType="com.hx.mybatisTool.SqlSentence"> + update + ${fieldData.tableName} + SET ${sqlSentence} + </update> + + <update id="updateAll" parameterType="${packageEntityName}.${entityName}"> + update ${fieldData.tableName} + SET <include refid="Update_Column_All"/> + WHERE ${fieldData.tableIdName} = ${fieldData.entityIdData} + </update> + + <delete id="deleteWhere" parameterType="com.hx.mybatisTool.SqlSentence"> + delete from ${fieldData.tableName} WHERE ${sqlSentence} + </delete> + + <delete id="deleteById" parameterType="java.lang.Object"> + delete from ${fieldData.tableName} WHERE ${fieldData.tableIdName} = ${fieldData.valueData} + </delete> + ${customData} +</mapper> \ No newline at end of file diff --git a/hx_auto/src/main/java/com/hx/auto/file/Service.tpl b/hx_auto/src/main/java/com/hx/auto/file/Service.tpl new file mode 100644 index 0000000..46bb5a9 --- /dev/null +++ b/hx_auto/src/main/java/com/hx/auto/file/Service.tpl @@ -0,0 +1,33 @@ +package ${servicePack}; + +import ${packageName}.${classNameUP}; +import com.hx.mybatisTool.SqlSentence; +import java.util.List; +import java.util.Map; + +public interface ${classNameUP}Service { + + int selectCount(SqlSentence sqlSentence); + + void insert(${classNameUP} ${className}); + + List<${classNameUP}> selectList(SqlSentence sqlSentence); + + List<Map<String,Object>> selectListMap(SqlSentence sqlSentence); + + ${classNameUP} selectOne(SqlSentence sqlSentence); + + Map<String,Object> selectOneMap(SqlSentence sqlSentence); + + ${classNameUP} selectOneByKey(Object object); + + ${classNameUP} selectOneByKeyBlob(Object object); + + void updateAll(${classNameUP} ${className}); + + void updateWhere(SqlSentence sqlSentence); + + void deleteOne(String delId); + + +} diff --git a/hx_auto/src/main/java/com/hx/auto/file/ServiceImpl.tpl b/hx_auto/src/main/java/com/hx/auto/file/ServiceImpl.tpl new file mode 100644 index 0000000..698808c --- /dev/null +++ b/hx_auto/src/main/java/com/hx/auto/file/ServiceImpl.tpl @@ -0,0 +1,101 @@ +package ${serviceImpPack}; + +import javax.annotation.Resource; + +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.hx.exception.TipsException; +import ${daoPack}.${classNameUP}Mapper; +import ${packageName}.${classNameUP}; +import ${servicePack}.${classNameUP}Service; +import com.hx.mybatisTool.SqlSentence; +import java.util.List; +import java.util.Map; + +@Transactional +@Service +public class ${classNameUP}ServiceImpl implements ${classNameUP}Service { + + @Resource + private ${classNameUP}Mapper ${className}Mapper; + + /**鏌ヨ鍒楄〃*/ + @Override + public List<${classNameUP}> selectList(SqlSentence sqlSentence) { + return ${className}Mapper.selectList(sqlSentence); + } + + /**鏌ヨ鍒楄〃*/ + @Override + public List<Map<String,Object>> selectListMap(SqlSentence sqlSentence) { + return ${className}Mapper.selectListMap(sqlSentence); + } + + /**鏌ヨ鍗曚釜*/ + @Override + public ${classNameUP} selectOne(SqlSentence sqlSentence) { + return ${className}Mapper.selectOne(sqlSentence); + } + + /**鏌ヨ鍗曚釜*/ + @Override + public Map<String,Object> selectOneMap(SqlSentence sqlSentence) { + return ${className}Mapper.selectOneMap(sqlSentence); + } + + /**鏌ヨ鍗曚釜锛屽ぇ鏁版嵁涓嶆嬁鍙�*/ + @Override + public ${classNameUP} selectOneByKey(Object object) { + return ${className}Mapper.selectOneByKey(object); + } + + /**鏌ヨ鍗曚釜锛屽ぇ鏁版嵁鎷垮彇*/ + @Override + public ${classNameUP} selectOneByKeyBlob(Object object) { + return ${className}Mapper.selectOneByKeyBlob(object); + } + + /**鏂板*/ + @Override + public void insert(${classNameUP} ${className}) { + int count = ${className}Mapper.insert(${className}); + if(count != 1) { + throw new TipsException("鏂板澶辫触锛�"); + } + } + + /**淇敼*/ + @Override + public void updateAll(${classNameUP} ${className}) { + int count = ${className}Mapper.updateAll(${className}); + if(count!=1) { + throw new TipsException("淇濆瓨澶辫触锛�"); + } + } + + /**淇敼*/ + @Override + public void updateWhere(SqlSentence sqlSentence) { + int count = ${className}Mapper.updateWhere(sqlSentence); + if(count!=1) { + throw new TipsException("淇濆瓨澶辫触锛�"); + } + } + + /**鍒犻櫎涓�涓�*/ + @Override + public void deleteOne(String delId) { + int count = ${className}Mapper.deleteById(delId); + if(count!=1) { + throw new TipsException("鍒犻櫎澶辫触锛�"); + } + } + + /**鏌ヨ鏉℃暟*/ + @Override + public int selectCount(SqlSentence sqlSentence) { + int count = ${className}Mapper.selectCount(sqlSentence); + return count; + } +} diff --git a/hx_auto/src/main/java/com/hx/auto/manage/xml/scan/StartScanXmlHandler.java b/hx_auto/src/main/java/com/hx/auto/manage/xml/scan/StartScanXmlHandler.java new file mode 100644 index 0000000..f54bc59 --- /dev/null +++ b/hx_auto/src/main/java/com/hx/auto/manage/xml/scan/StartScanXmlHandler.java @@ -0,0 +1,15 @@ +package com.hx.auto.manage.xml.scan; + + +/** + * 鍚姩鏃舵墽琛屽鐞嗙殑鎺ュ彛 + * @author chenbin.sun + * + */ +public interface StartScanXmlHandler { + + /** + * 寤鸿〃寮�濮� + */ + void startHandler() throws Exception; +} diff --git a/hx_auto/src/main/java/com/hx/auto/manage/xml/scan/StartScanXmlHandlerImpl.java b/hx_auto/src/main/java/com/hx/auto/manage/xml/scan/StartScanXmlHandlerImpl.java new file mode 100644 index 0000000..4994169 --- /dev/null +++ b/hx_auto/src/main/java/com/hx/auto/manage/xml/scan/StartScanXmlHandlerImpl.java @@ -0,0 +1,34 @@ +package com.hx.auto.manage.xml.scan; + +import com.hx.auto.GeneratorUtil; +import com.hx.auto.manage.xml.scan.util.ConfigUtil; +import com.hx.auto.manage.xml.scan.util.CreateMapperUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import java.util.Set; + +/** + * 鍚姩鏃惰繘琛屽鐞嗙殑瀹炵幇绫� + * @author chenbin.sun + * + */ +@SuppressWarnings("restriction") +@Service +public class StartScanXmlHandlerImpl implements StartScanXmlHandler { + + @Autowired + private ConfigUtil configUtil; + + @PostConstruct + public void startHandler() throws Exception { + if(configUtil.getIsScan()){ + System.out.println("寮�濮嬫壂鎻忔洿鏂皒ml鏂囦欢"); + Set<Class<?>> classes = GeneratorUtil.classData(configUtil.getModelPack()); + for(Class<?> cl:classes) { + CreateMapperUtil.generatorMapper(cl,configUtil); + } + } + } +} diff --git a/hx_auto/src/main/java/com/hx/auto/manage/xml/scan/util/ConfigUtil.java b/hx_auto/src/main/java/com/hx/auto/manage/xml/scan/util/ConfigUtil.java new file mode 100644 index 0000000..80165f1 --- /dev/null +++ b/hx_auto/src/main/java/com/hx/auto/manage/xml/scan/util/ConfigUtil.java @@ -0,0 +1,145 @@ +package com.hx.auto.manage.xml.scan.util; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.beans.factory.config.BeanFactoryPostProcessor; +import org.springframework.beans.factory.config.PropertyResourceConfigurer; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.core.io.support.PropertiesLoaderSupport; +import org.springframework.stereotype.Component; + +import java.lang.reflect.Method; +import java.util.Properties; + +@Component +public class ConfigUtil implements ApplicationContextAware { + + private static ApplicationContext applicationContext; + + private static Properties properties = null; + + @Value(Constants.CJH_SCAN_XML_SUPPLY) + private String isScan; + + @Value(Constants.CJH_PACKAGE_FILE_NAME_URL) + private String packFileName; + + @Value(Constants.CJH_PACKAGE_MODEL_URL) + private String modelPack; + + @Value(Constants.CJH_CREATE_XML_URL) + private String xmlUrl; + + @Value(Constants.CJH_CREATE_DAO_URL) + private String daoUrl; + + /** + * 瀹炵幇ApplicationContextAware鎺ュ彛鐨勫洖璋冩柟娉曪紝璁剧疆涓婁笅鏂囩幆澧� + */ + @Override + public void setApplicationContext(ApplicationContext applicationContext) { + ConfigUtil.applicationContext = applicationContext; + } + + /** + * 鑾峰緱spring涓婁笅鏂� + * + * @return ApplicationContext spring涓婁笅鏂� + */ + public ApplicationContext getApplicationContext() { + return applicationContext; + } + + /** + * 鑾峰彇bean + * + * @param name + * service娉ㄨВ鏂瑰紡name涓哄皬椹煎嘲鏍煎紡 + * @return Object bean鐨勫疄渚嬪璞� + */ + public Object getBean(String name) throws BeansException { + return applicationContext.getBean(name); + } + + private void initProperties() { + + properties = new Properties(); + try { + String[] postProcessorNames = applicationContext.getBeanNamesForType(BeanFactoryPostProcessor.class, true, + true); + for (String ppName : postProcessorNames) { + BeanFactoryPostProcessor beanProcessor = applicationContext.getBean(ppName, + BeanFactoryPostProcessor.class); + if (beanProcessor instanceof PropertyResourceConfigurer) { + PropertyResourceConfigurer propertyResourceConfigurer = (PropertyResourceConfigurer) beanProcessor; + Method mergeProperties = PropertiesLoaderSupport.class.getDeclaredMethod("mergeProperties"); + mergeProperties.setAccessible(true); + Properties props = (Properties) mergeProperties.invoke(propertyResourceConfigurer); + + // get the method convertProperties + // in class PropertyResourceConfigurer + Method convertProperties = PropertyResourceConfigurer.class.getDeclaredMethod("convertProperties", + Properties.class); + // convert properties + convertProperties.setAccessible(true); + convertProperties.invoke(propertyResourceConfigurer, props); + + properties.putAll(props); + } + } + + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + + public static Properties getProperties() { + return properties; + } + + public static void setProperties(Properties properties) { + ConfigUtil.properties = properties; + } + + public String getModelPack() { + return modelPack; + } + + public void setModelPack(String modelPack) { + this.modelPack = modelPack; + } + + public Boolean getIsScan() { + return "true".equals(isScan); + } + + public void setIsScan(String isScan) { + this.isScan = isScan; + } + + public String getPackFileName() { + return packFileName; + } + + public void setPackFileName(String packFileName) { + this.packFileName = packFileName; + } + + public String getXmlUrl() { + return xmlUrl; + } + + public void setXmlUrl(String xmlUrl) { + this.xmlUrl = xmlUrl; + } + + public String getDaoUrl() { + return daoUrl; + } + + public void setDaoUrl(String daoUrl) { + this.daoUrl = daoUrl; + } +} diff --git a/hx_auto/src/main/java/com/hx/auto/manage/xml/scan/util/Constants.java b/hx_auto/src/main/java/com/hx/auto/manage/xml/scan/util/Constants.java new file mode 100644 index 0000000..baa459c --- /dev/null +++ b/hx_auto/src/main/java/com/hx/auto/manage/xml/scan/util/Constants.java @@ -0,0 +1,18 @@ +package com.hx.auto.manage.xml.scan.util; + +public class Constants { + + /**鏄惁鎵弿琛ュ厖xml鏂囦欢*/ + public static final String CJH_SCAN_XML_SUPPLY = "${xml.scan.xml.supply}"; + /**椤圭洰鍚嶇О*/ + public static final String CJH_PROJECT_NAME = "${xml.priject.name}"; + /**鍖呮墍鍦ㄧ殑鏂囦欢澶硅矾寰�*/ + public static final String CJH_PACKAGE_FILE_NAME_URL = "${xml.package.file.name}"; + /**鐢熸垚DAO璺緞*/ + public static final String CJH_CREATE_DAO_URL = "${xml.create.dao.url}"; + /**鐢熸垚璺緞*/ + public static final String CJH_CREATE_XML_URL = "${xml.create.xml.url}"; + /**瀹炰綋绫诲寘璺緞*/ + public static final String CJH_PACKAGE_MODEL_URL = "${xml.model.name}"; + +} diff --git a/hx_auto/src/main/java/com/hx/auto/manage/xml/scan/util/CreateMapperUtil.java b/hx_auto/src/main/java/com/hx/auto/manage/xml/scan/util/CreateMapperUtil.java new file mode 100644 index 0000000..2041540 --- /dev/null +++ b/hx_auto/src/main/java/com/hx/auto/manage/xml/scan/util/CreateMapperUtil.java @@ -0,0 +1,154 @@ +package com.hx.auto.manage.xml.scan.util; + +import com.gitee.sunchenbin.mybatis.actable.annotation.Column; +import com.gitee.sunchenbin.mybatis.actable.annotation.Table; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlTypeConstant; +import com.hx.auto.GeneratorMapperUtil; +import com.hx.auto.GeneratorReadXmlUtil; +import com.hx.auto.common.JdbcType; +import com.hx.auto.common.ReadEntityData; +import com.hx.auto.util.CommonTool; +import com.hx.auto.util.GeneratorClassParentUtil; +import freemarker.template.Configuration; +import freemarker.template.DefaultObjectWrapper; +import freemarker.template.Template; + +import java.io.*; +import java.lang.reflect.Field; +import java.util.HashMap; + +/** + * 鑷姩鐢熸垚mapper.xml + * + * @author chenjiahe 2019骞�09鏈�08鏃�23:57:47 + * + */ +public class CreateMapperUtil { + + private static String templateDir = "/ftl";//鑾峰彇妯℃澘璺緞 + private static String templateName = "Mapper.tpl";//action妯℃澘鍚嶇О + + /**鐢熸垚mapper.xml + * @param cl 瀹炰綋绫� + * @param configUtil 鐢熸垚閰嶇疆淇℃伅 + * @throws Exception + */ + public static void generatorMapper(Class<?> cl, ConfigUtil configUtil) throws Exception { + try { + + // 鍙嶅皠start + // 绫诲悕 + String entityName = cl.getSimpleName(); + + //鐢熸垚鏂囦欢璺緞 + String targetFile = configUtil.getXmlUrl().replace(".", "/")+"/"; + //鐢熸垚鏂囦欢鍚嶇О + targetFile += entityName + "Mapper.xml"; + //琛ュ叏璺緞 + targetFile = "./"+configUtil.getPackFileName().replace(".", "/")+"/"+targetFile; + //鑾峰彇鏄惁宸茬粡鐢熸垚杩囨枃浠讹紝鎷垮彇鑷畾涔夌殑鍐呭 + String xmlData = GeneratorReadXmlUtil.readMapperXml(targetFile); + + //濡傛灉涓嶅瓨鍦ㄥ氨鐩存帴璺宠繃 + if("false".equals(xmlData)){ + return; + } + + // 绫诲悕棣栧瓧姣嶅皬鍐� + String initial = entityName.substring(0, 1).toLowerCase(); + String entityNameSmall = initial + entityName.substring(1, entityName.length()); + + //鑾峰彇瀹炰綋绫诲寘鍚� + String[] strs = cl.getName().split("\\."); + String packageName = ""; + //鍘绘帀绫诲悕 + for(int i=0;i<strs.length-1;i++) { + packageName += "."+strs[i]; + } + packageName = packageName.replaceFirst(".", ""); + + //鑾峰彇妯℃澘 + Configuration configuration = new Configuration(Configuration.getVersion()); + configuration.setClassForTemplateLoading(GeneratorMapperUtil.class, templateDir); + // 鑾峰彇鎴栧垱寤烘ā鏉� + Template template = configuration.getTemplate(templateName); + + //瀹炰綋绫绘墍鏈夌殑瀛楁 + //鐢ㄦ潵瀛樺偍鏁版嵁 + ReadEntityData readEntityData = new ReadEntityData(); + //琛ㄥ悕绉� + Table table = cl.getAnnotation(Table.class); + readEntityData.setTableName(table.name()); + // 鍙栧緱鏈被鐨勫叏閮ㄥ睘鎬� + Field[] fields = cl.getDeclaredFields(); + fields = GeneratorClassParentUtil.getPatentFields(fields,cl); + for (Field field:fields) { + // 鍒ゆ柇鏂规硶涓槸鍚︽湁鎸囧畾娉ㄨВ绫诲瀷鐨勬敞瑙� + boolean hasAnnotation = field.isAnnotationPresent(Column.class); + if (hasAnnotation) { + // 鏍规嵁娉ㄨВ绫诲瀷杩斿洖鏂规硶鐨勬寚瀹氱被鍨嬫敞瑙� + Column column = field.getAnnotation(Column.class); + + //鍒ゆ柇鏄笉鏄� + boolean isBol = false; + Integer isBlob = 0; + if(column.type().equals(MySqlTypeConstant.TEXT)||column.type().equals(MySqlTypeConstant.LONGTEXT) + ||column.type().equals(MySqlTypeConstant.LONGBLOB)){ + isBol = true; + isBlob = 1; + } + + //绫诲瀷 + //String type = column.type().toUpperCase(); + String type = JdbcType.jdbcTypeData(field.getType().getTypeName().toUpperCase(),isBol); + //涓婚敭 + if (column.isKey()) { + readEntityData.setEntityIdName(field.getName()); + readEntityData.setEntityIdData("#{"+field.getName()+"}"); + if(!CommonTool.checkNotNull(column.name())) { + readEntityData.setTableIdName(field.getName()); + }else { + readEntityData.setTableIdName(column.name()); + } + readEntityData.setKeyType(type); + continue; + } + //瀛樺偍鏁版嵁 + if(!CommonTool.checkNotNull(column.name())) { + readEntityData.fielData(field.getName(),field.getName(),type,isBlob,"#{"+field.getName()+"}"); + }else { + readEntityData.fielData(field.getName(),column.name(),type,isBlob,"#{"+field.getName()+"}"); + } + } + } + // 鍒涘缓鏁版嵁妯″瀷 + HashMap<String, Object> root = new HashMap<String, Object>(); + + root.put("packageEntityName",packageName); + //瀹炰綋绫荤殑绫诲悕 + root.put("entityName", entityName); + //瀹炰綋绫荤殑绫诲悕锛堥瀛楁瘝灏忓啓锛� + root.put("entityNameSmall", entityNameSmall); + //琛ㄥ瓧娈� 鏁版嵁 + root.put("fieldData",readEntityData); + + root.put("sqlSentence","${sqlSentence}"); + + root.put("DAOPackageName",configUtil.getDaoUrl()); + //瀹炰綋绫荤殑鍖呭悕 + root.put("entityPackageName",packageName); + + //鑾峰彇鏄惁宸茬粡鐢熸垚杩囨枃浠讹紝鎷垮彇鑷畾涔夌殑鍐呭 + root.put("customData",xmlData); + + System.out.println("mapperUrl:"+targetFile); + // 灏嗘ā鏉垮拰鏁版嵁妯″瀷鍚堝苟 杈撳嚭鍒癈onsole + Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile), "UTF-8")); + template.process(root, out); + out.flush(); + out.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/hx_auto/src/main/java/com/hx/auto/util/CommonTool.java b/hx_auto/src/main/java/com/hx/auto/util/CommonTool.java new file mode 100644 index 0000000..f322f96 --- /dev/null +++ b/hx_auto/src/main/java/com/hx/auto/util/CommonTool.java @@ -0,0 +1,17 @@ +package com.hx.auto.util; + +public class CommonTool { + + /** + * 鍒ゆ柇鏄惁涓虹┖ + */ + public static boolean checkNotNull(Object o) { + boolean b = false; + if (o != null && !"".equals(o)&&!"undefind".equals(o)) { + b = true; + } + return b; + } + + +} diff --git a/hx_auto/src/main/java/com/hx/auto/util/GeneratorClassParentUtil.java b/hx_auto/src/main/java/com/hx/auto/util/GeneratorClassParentUtil.java new file mode 100644 index 0000000..9065fd9 --- /dev/null +++ b/hx_auto/src/main/java/com/hx/auto/util/GeneratorClassParentUtil.java @@ -0,0 +1,55 @@ +package com.hx.auto.util; + +import org.w3c.dom.Document; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import java.io.File; +import java.io.IOException; +import java.io.StringWriter; +import java.lang.reflect.Field; +import java.util.*; + +/** + * + * @author chenjiahe 2020-06-28 + * + */ +public class GeneratorClassParentUtil { + + /** + * 鑾峰彇鐖剁被鐨勫瓧娈� + * @param fields + * @param clas + * @return + */ + public static Field[] getPatentFields(Field[] fields,Class<?> clas){ + if (clas.getSuperclass() != null) { + Class clsSup = clas.getSuperclass(); + List<Field> fieldList = new ArrayList<Field>(); + fieldList.addAll(Arrays.asList(fields)); + fieldList.addAll(Arrays.asList(clsSup.getDeclaredFields())); + fields = new Field[fieldList.size()]; + int i = 0; + for (Object field : fieldList.toArray()) { + fields[i] = (Field) field; + i++; + } + fields = getPatentFields(fields,clsSup); + } + return fields; + } + + +} \ No newline at end of file diff --git a/hx_auto/src/main/resources/ftl/Action.tpl b/hx_auto/src/main/resources/ftl/Action.tpl new file mode 100644 index 0000000..0aa4b1a --- /dev/null +++ b/hx_auto/src/main/resources/ftl/Action.tpl @@ -0,0 +1,79 @@ +package ${packageName}; + +import java.util.List; +import javax.annotation.Resource; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; + +import com.hx.common.BaseController; +import com.hx.mybatisTool.SqlSentence; +import ${DAOPackageName}.${entityName}Mapper; +import ${entityPackageName}.${entityName}; +import ${servicePackageName}.${entityName}Service; +import com.hx.resultTool.Result; +import com.hx.util.SimpleTool; +import net.sf.json.JSONObject; +import com.hx.phitab.common.AuthConstants; + +@RestController +@RequestMapping("${entityNameSmall}") +public class ${entityName}Controller extends BaseController { + + @Resource + private ${entityName}Service service; + + /**鍒楄〃*/ + @Authority(tag = AuthConstants.${entityName}.SEE) + @RequestMapping("/list") + public Result listData(Integer pageNum,Integer pageSize) { + //pageNum褰撳墠绗嚑椤� + //rowCount 鎷垮嚑鏉� + + //鍒嗛〉鎻掍欢 + PageHelper.startPage(pageNum==null?1:pageNum,pageSize==null?20:pageSize); + SqlSentence sqlSentence = new SqlSentence(); + List<${entityName}> ${entityNameSmall}s = service.selectList(sqlSentence); + PageInfo pageInfo = new PageInfo<${entityName}>(${entityNameSmall}s); + Map<String,Object> data = new HashMap<>(); + data.put("pageNum",pageInfo.getPageNum()); + data.put("pageSize",pageInfo.getPageSize()); + data.put("total",pageInfo.getTotal()); + data.put("isLastPage",pageInfo.isIsLastPage()); + data.put("list",pageInfo.getList()); + return Result.success(data); + } + + /**鏂板*/ + @Authority(tag = AuthConstants.${entityName}.ADD) + @RequestMapping("/add") + public Result addData(${entityName} ${entityNameSmall}) { + service.insert(${entityNameSmall}); + return Result.success(); + } + + /**鑾峰彇鏁版嵁*/ + @Authority(tag = AuthConstants.${entityName}.SEE) + @RequestMapping("/see") + public Result editeData(String id) { + ${entityName} ${entityNameSmall} = service.selectOneByKeyBlob(id); + return Result.success(${entityNameSmall}); + } + + /**淇敼鏁版嵁*/ + @Authority(tag = AuthConstants.${entityName}.EDIT) + @RequestMapping("/update") + public Result updateData(${entityName} ${entityNameSmall}) { + service.updateAll(${entityNameSmall}); + return Result.success(); + } + + /**鍒犻櫎鏁版嵁锛堝崟涓級*/ + @Authority(tag = AuthConstants.${entityName}.DELETE) + @RequestMapping("/delete/one") + public Result deleteData(String id) { + service.deleteOne(id); + return Result.success(); + } +} diff --git a/hx_auto/src/main/resources/ftl/Dao.tpl b/hx_auto/src/main/resources/ftl/Dao.tpl new file mode 100644 index 0000000..8ce5825 --- /dev/null +++ b/hx_auto/src/main/resources/ftl/Dao.tpl @@ -0,0 +1,37 @@ +package ${DAOPackageName}; + +import java.util.List; +import java.util.Map; +import com.hx.mybatisTool.SqlSentence; +import ${entityPackageName}.${entityName}; + +public interface ${entityName}Mapper { + /**鏂板锛岃繑鍥炰富閿�*/ + int insert(${entityName} ${entityNameSmall}); + /**鏂板锛岃繑鍥炰富閿�*/ + int insertById(${entityName} ${entityNameSmall}); + /**鏌ヨ鏉℃暟*/ + int selectCount(SqlSentence sqlSentence); + /**鏌ヨ鏉℃暟*/ + int selectCountSql(SqlSentence sqlSentence); + /**鏌ヨ鍒楄〃锛岃繑鍥炲疄浣撶被鐨凩ist*/ + List<${entityName}> selectList(SqlSentence sqlSentence); + /**鏌ヨ鍒楄〃锛岃繑鍥濵ap鐨凩ist*/ + List<Map<String,Object>> selectListMap(SqlSentence sqlSentence); + /**鏌ヨ锛岃繑鍥炲崟涓疄浣�*/ + ${entityName} selectOne(SqlSentence sqlSentence); + /**鏌ヨ锛岃繑鍥炲崟涓猰ap*/ + Map<String,Object> selectOneMap(SqlSentence sqlSentence); + /**鏌ヨ锛岃繑鍥炲疄浣撶被娌℃湁澶ф暟鎹殑*/ + ${entityName} selectOneByKey(Object object); + /**鏌ヨ锛岃繑鍥炲疄浣撶被鏈夊ぇ鏁版嵁鐨�*/ + ${entityName} selectOneByKeyBlob(Object object); + /**鏇存柊锛岃繑鍥炴洿鏂版暟閲�*/ + int updateWhere(SqlSentence sqlSentence); + /**鏇存柊锛岃繑鍥炴洿鏂版暟閲�*/ + int updateAll(${entityName} ${entityNameSmall}); + /**鍒犻櫎锛岃繑鍥炲垹闄ゆ暟閲�*/ + int deleteWhere(SqlSentence sqlSentence); + /**鍒犻櫎锛岃繑鍥炲垹闄ゆ暟閲�*/ + int deleteById(Object object); +} \ No newline at end of file diff --git a/hx_auto/src/main/resources/ftl/Mapper.tpl b/hx_auto/src/main/resources/ftl/Mapper.tpl new file mode 100644 index 0000000..e25e9d3 --- /dev/null +++ b/hx_auto/src/main/resources/ftl/Mapper.tpl @@ -0,0 +1,90 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<!DOCTYPE mapper +PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" +"http://mybatis.org/dtd/mybatis-3-mapper.dtd"> +<!-- namespace:璇apper.xml鏄犲皠鏂囦欢鐨� 鍞竴鏍囪瘑 --> +<mapper namespace="${DAOPackageName}.${entityName}Mapper"> + + <!-- 鏁翠釜瀹炰綋绫讳慨鏀癸紝琛ㄥ瓧娈�=瀹炰綋绫诲瓧娈�--> + <sql id="Update_Column_All"> + <trim prefixOverrides=","> + <#list fieldData.fields as item>,${item.tableName} = ${item.mybatisName}</#list> + </trim> + </sql> + + <!-- 鍚庣画閫氳繃 namespace.id--> + <!--parameterType:杈撳叆鍙傛暟鐨勭被鍨� + resultType锛氭煡璇㈣繑鍥炵粨鏋滃�肩殑绫诲瀷 锛岃繑鍥炵被鍨� --> + <insert id="insert" parameterType="${packageEntityName}.${entityName}"> + <selectKey keyProperty="id" resultType="String" order="BEFORE"> + select replace(uuid(),'-','') from dual + </selectKey> + insert into ${fieldData.tableName} (${fieldData.tableIdName}<#list fieldData.fields as item>,${item.tableName}</#list>) values (${fieldData.entityIdData}<#list fieldData.fields as item>,${item.mybatisName}</#list>) + </insert> + + <insert id="insertById" parameterType="${packageEntityName}.${entityName}"> + insert into ${fieldData.tableName} (${fieldData.tableIdName}<#list fieldData.fields as item>,${item.tableName}</#list>) values (${fieldData.entityIdData}<#list fieldData.fields as item>,${item.mybatisName}</#list>) + </insert> + + <select id="selectList" resultType="${packageEntityName}.${entityName}" parameterType="com.hx.mybatisTool.SqlSentence" > + ${sqlSentence} + </select> + + <select id="selectListMap" resultType="java.util.Map" parameterType="com.hx.mybatisTool.SqlSentence" > + ${sqlSentence} + </select> + + <select id="selectOne" resultType="${packageEntityName}.${entityName}" parameterType="com.hx.mybatisTool.SqlSentence" > + ${sqlSentence} + </select> + + <select id="selectOneMap" resultType="java.util.Map" parameterType="com.hx.mybatisTool.SqlSentence" > + ${sqlSentence} + </select> + + <select id="selectCount" resultType="int" parameterType="com.hx.mybatisTool.SqlSentence" > + select + COUNT(*) + from ${fieldData.tableName} + WHERE ${sqlSentence} + </select> + + <select id="selectCountSql" resultType="int" parameterType="com.hx.mybatisTool.SqlSentence" > + ${sqlSentence} + </select> + + <select id="selectOneByKey" resultType="${packageEntityName}.${entityName}" parameterType="java.lang.Object" > + select + ${fieldData.tableIdName}<#list fieldData.fields as item>,${item.tableName}</#list> + from ${fieldData.tableName} + WHERE ${fieldData.tableIdName} = ${fieldData.valueData} + </select> + + <select id="selectOneByKeyBlob" resultType="${packageEntityName}.${entityName}" parameterType="java.lang.Object" > + select + ${fieldData.tableIdName}<#list fieldData.fields as item>,${item.tableName}</#list> + from ${fieldData.tableName} + WHERE ${fieldData.tableIdName} = ${fieldData.valueData} + </select> + + <update id="updateWhere" parameterType="com.hx.mybatisTool.SqlSentence"> + update + ${fieldData.tableName} + SET ${sqlSentence} + </update> + + <update id="updateAll" parameterType="${packageEntityName}.${entityName}"> + update ${fieldData.tableName} + SET <include refid="Update_Column_All"/> + WHERE ${fieldData.tableIdName} = ${fieldData.entityIdData} + </update> + + <delete id="deleteWhere" parameterType="com.hx.mybatisTool.SqlSentence"> + delete from ${fieldData.tableName} WHERE ${sqlSentence} + </delete> + + <delete id="deleteById" parameterType="java.lang.Object"> + delete from ${fieldData.tableName} WHERE ${fieldData.tableIdName} = ${fieldData.valueData} + </delete> + ${customData} +</mapper> \ No newline at end of file diff --git a/hx_auto/src/main/resources/ftl/Service.tpl b/hx_auto/src/main/resources/ftl/Service.tpl new file mode 100644 index 0000000..46bb5a9 --- /dev/null +++ b/hx_auto/src/main/resources/ftl/Service.tpl @@ -0,0 +1,33 @@ +package ${servicePack}; + +import ${packageName}.${classNameUP}; +import com.hx.mybatisTool.SqlSentence; +import java.util.List; +import java.util.Map; + +public interface ${classNameUP}Service { + + int selectCount(SqlSentence sqlSentence); + + void insert(${classNameUP} ${className}); + + List<${classNameUP}> selectList(SqlSentence sqlSentence); + + List<Map<String,Object>> selectListMap(SqlSentence sqlSentence); + + ${classNameUP} selectOne(SqlSentence sqlSentence); + + Map<String,Object> selectOneMap(SqlSentence sqlSentence); + + ${classNameUP} selectOneByKey(Object object); + + ${classNameUP} selectOneByKeyBlob(Object object); + + void updateAll(${classNameUP} ${className}); + + void updateWhere(SqlSentence sqlSentence); + + void deleteOne(String delId); + + +} diff --git a/hx_auto/src/main/resources/ftl/ServiceImpl.tpl b/hx_auto/src/main/resources/ftl/ServiceImpl.tpl new file mode 100644 index 0000000..698808c --- /dev/null +++ b/hx_auto/src/main/resources/ftl/ServiceImpl.tpl @@ -0,0 +1,101 @@ +package ${serviceImpPack}; + +import javax.annotation.Resource; + +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.hx.exception.TipsException; +import ${daoPack}.${classNameUP}Mapper; +import ${packageName}.${classNameUP}; +import ${servicePack}.${classNameUP}Service; +import com.hx.mybatisTool.SqlSentence; +import java.util.List; +import java.util.Map; + +@Transactional +@Service +public class ${classNameUP}ServiceImpl implements ${classNameUP}Service { + + @Resource + private ${classNameUP}Mapper ${className}Mapper; + + /**鏌ヨ鍒楄〃*/ + @Override + public List<${classNameUP}> selectList(SqlSentence sqlSentence) { + return ${className}Mapper.selectList(sqlSentence); + } + + /**鏌ヨ鍒楄〃*/ + @Override + public List<Map<String,Object>> selectListMap(SqlSentence sqlSentence) { + return ${className}Mapper.selectListMap(sqlSentence); + } + + /**鏌ヨ鍗曚釜*/ + @Override + public ${classNameUP} selectOne(SqlSentence sqlSentence) { + return ${className}Mapper.selectOne(sqlSentence); + } + + /**鏌ヨ鍗曚釜*/ + @Override + public Map<String,Object> selectOneMap(SqlSentence sqlSentence) { + return ${className}Mapper.selectOneMap(sqlSentence); + } + + /**鏌ヨ鍗曚釜锛屽ぇ鏁版嵁涓嶆嬁鍙�*/ + @Override + public ${classNameUP} selectOneByKey(Object object) { + return ${className}Mapper.selectOneByKey(object); + } + + /**鏌ヨ鍗曚釜锛屽ぇ鏁版嵁鎷垮彇*/ + @Override + public ${classNameUP} selectOneByKeyBlob(Object object) { + return ${className}Mapper.selectOneByKeyBlob(object); + } + + /**鏂板*/ + @Override + public void insert(${classNameUP} ${className}) { + int count = ${className}Mapper.insert(${className}); + if(count != 1) { + throw new TipsException("鏂板澶辫触锛�"); + } + } + + /**淇敼*/ + @Override + public void updateAll(${classNameUP} ${className}) { + int count = ${className}Mapper.updateAll(${className}); + if(count!=1) { + throw new TipsException("淇濆瓨澶辫触锛�"); + } + } + + /**淇敼*/ + @Override + public void updateWhere(SqlSentence sqlSentence) { + int count = ${className}Mapper.updateWhere(sqlSentence); + if(count!=1) { + throw new TipsException("淇濆瓨澶辫触锛�"); + } + } + + /**鍒犻櫎涓�涓�*/ + @Override + public void deleteOne(String delId) { + int count = ${className}Mapper.deleteById(delId); + if(count!=1) { + throw new TipsException("鍒犻櫎澶辫触锛�"); + } + } + + /**鏌ヨ鏉℃暟*/ + @Override + public int selectCount(SqlSentence sqlSentence) { + int count = ${className}Mapper.selectCount(sqlSentence); + return count; + } +} diff --git a/hx_common/.gitignore b/hx_common/.gitignore new file mode 100644 index 0000000..141c53f --- /dev/null +++ b/hx_common/.gitignore @@ -0,0 +1,25 @@ +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +/target/ +/.idea \ No newline at end of file diff --git a/hx_common/pom.xml b/hx_common/pom.xml new file mode 100644 index 0000000..f0329da --- /dev/null +++ b/hx_common/pom.xml @@ -0,0 +1,327 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>com.hx.gitee</groupId> + <artifactId>hx-parent</artifactId> + <version>stander</version> + </parent> + + <artifactId>hx-common</artifactId> + <packaging>jar</packaging> + + <dependencies> + + <!--瀵硅薄涓嶺ML澶勭悊--> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + </dependency> + + <!-- <dependency> + <groupId>org.apache.poi</groupId> + <artifactId>poi-ooxml</artifactId> + <version>3.9</version> + <exclusions> + <exclusion> + <artifactId>dom4j</artifactId> + <groupId>dom4j</groupId> + </exclusion> + </exclusions> + </dependency>--> + + <!--鑵捐浜� cos--> + <dependency> + <groupId>com.qcloud</groupId> + <artifactId>cos_api</artifactId> + </dependency> + + <dependency> + <groupId>commons-fileupload</groupId> + <artifactId>commons-fileupload</artifactId> + </dependency> + + <!--鍙戦�侀偖浠�--> + <dependency> + <groupId>com.sun.mail</groupId> + <artifactId>javax.mail</artifactId> + </dependency> + + <dependency> + <groupId>org.apache.commons</groupId> + <artifactId>commons-csv</artifactId> + <version>1.6</version> + </dependency> + + <dependency> + <groupId>com.aliyun.oss</groupId> + <artifactId>aliyun-sdk-oss</artifactId> + </dependency> + + <dependency> + <groupId>com.huaweicloud</groupId> + <artifactId>esdk-obs-java</artifactId> + </dependency> + + <!-- https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15on --> + <dependency> + <groupId>org.bouncycastle</groupId> + <artifactId>bcprov-jdk15on</artifactId> + </dependency> + + <!--寰俊鏀粯鐢ㄥ埌鐨勫寘--> + <dependency> + <groupId>org.dom4j</groupId> + <artifactId>dom4j</artifactId> + </dependency> + <dependency> + <groupId>org.jdom</groupId> + <artifactId>jdom</artifactId> + </dependency> + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpcore</artifactId> + </dependency> + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpclient</artifactId> + </dependency> + + <dependency> + <groupId>cglib</groupId> + <artifactId>cglib</artifactId> + </dependency> + <!--<dependency> + <groupId>log4j</groupId> + <artifactId>log4j</artifactId> + </dependency>--> + + <!--鐢熸垚浜岀淮鐮佹敮鎸佸寘--> + <dependency> + <groupId>com.google.zxing</groupId> + <artifactId>core</artifactId> + </dependency> + <dependency> + <groupId>net.glxn</groupId> + <artifactId>qrgen</artifactId> + </dependency> + + <!-- 瀛楃涓插伐鍏风被jar:StringUtils --> + <dependency> + <groupId>org.apache.commons</groupId> + <artifactId>commons-lang3</artifactId> + </dependency> + <dependency> + <groupId>commons-io</groupId> + <artifactId>commons-io</artifactId> + </dependency> + <dependency> + <groupId>redis.clients</groupId> + <artifactId>jedis</artifactId> + </dependency> + + <dependency> + <groupId>com.auth0</groupId> + <artifactId>java-jwt</artifactId> + </dependency> + <dependency> + <groupId>io.jsonwebtoken</groupId> + <artifactId>jjwt</artifactId> + </dependency> + + <dependency> + <groupId>javax.servlet.jsp.jstl</groupId> + <artifactId>jstl-api</artifactId> + </dependency> + <dependency> + <groupId>javax.servlet</groupId> + <artifactId>jstl</artifactId> + </dependency> + + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-tomcat</artifactId> + <!--<scope>provided</scope>--> + </dependency> + + <!-- mybatis鑷姩鐢熸垚 --> + <dependency> + <groupId>com.gitee.sunchenbin.mybatis.actable</groupId> + <artifactId>mybatis-enhance-actable</artifactId> + </dependency> + + <!-- 妯℃澘鐢熸垚jar --> + <dependency> + <groupId>org.freemarker</groupId> + <artifactId>freemarker</artifactId> + </dependency> + + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-data-redis</artifactId> + <exclusions> + <exclusion> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter</artifactId> + </exclusion> + <exclusion> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-api</artifactId> + </exclusion> + <exclusion> + <groupId>org.slf4j</groupId> + <artifactId>jcl-over-slf4j</artifactId> + </exclusion> + </exclusions> + </dependency> + + <dependency> + <groupId>org.projectlombok</groupId> + <artifactId>lombok</artifactId> + </dependency> + + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-web</artifactId> + <exclusions> + <exclusion> + <groupId>org.hibernate</groupId> + <artifactId>hibernate-validator</artifactId> + </exclusion> + <exclusion> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-tomcat</artifactId> + </exclusion> + <exclusion> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-logging</artifactId> + </exclusion> + </exclusions> + </dependency> + <dependency> + <groupId>org.mybatis.spring.boot</groupId> + <artifactId>mybatis-spring-boot-starter</artifactId><exclusions> + <exclusion> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-logging</artifactId> + </exclusion> + </exclusions> + + </dependency> + <dependency> + <groupId>mysql</groupId> + <artifactId>mysql-connector-java</artifactId> + <scope>runtime</scope> + </dependency> + + <dependency> + <groupId>com.alibaba</groupId> + <artifactId>druid</artifactId> + </dependency> + + <dependency> + <groupId>com.alibaba</groupId> + <artifactId>fastjson</artifactId> + </dependency> + + <dependency> + <groupId>com.google.code.gson</groupId> + <artifactId>gson</artifactId> + </dependency> + + <dependency> + <groupId>net.sf.json-lib</groupId> + <artifactId>json-lib</artifactId> + <classifier>jdk15</classifier> + </dependency> + + <dependency> + <groupId>com.belerweb</groupId> + <artifactId>pinyin4j</artifactId> + </dependency> + + <dependency> + <groupId>net.sourceforge.jexcelapi</groupId> + <artifactId>jxl</artifactId> + </dependency> + + <dependency> + <groupId>commons-beanutils</groupId> + <artifactId>commons-beanutils</artifactId> + <exclusions> + <exclusion> + <artifactId>commons-logging</artifactId> + <groupId>commons-logging</groupId> + </exclusion> + </exclusions> + </dependency> + <dependency> + <groupId>commons-collections</groupId> + <artifactId>commons-collections</artifactId> + </dependency> + <dependency> + <groupId>commons-lang</groupId> + <artifactId>commons-lang</artifactId> + </dependency> + <dependency> + <groupId>net.sf.ezmorph</groupId> + <artifactId>ezmorph</artifactId> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + </dependency> + <dependency> + <groupId>com.github.pagehelper</groupId> + <artifactId>pagehelper</artifactId> + </dependency> + + <dependency> + <groupId>com.dtflys.forest</groupId> + <artifactId>spring-boot-starter-forest</artifactId> + <version>1.5.0-RC2</version> + </dependency> + + <!-- redis --> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-data-redis</artifactId> + </dependency> + + <!-- https://mvnrepository.com/artifact/com.monitorjbl/xlsx-streamer --> + <dependency> + <groupId>com.monitorjbl</groupId> + <artifactId>xlsx-streamer</artifactId> + </dependency> + + </dependencies> + + <build> + <finalName>hx-common</finalName> + <resources> + <resource> + <directory>src/main/java</directory> + <includes> + <include>**/*.properties</include> + <include>**/*.xml</include> + <include>**/*.tld</include> + <include>**/*.tpl</include> + </includes> + <filtering>false</filtering> + </resource> + <resource> + <directory>src/main/resources</directory> + <excludes> + <exclude>profile-active/**</exclude> + </excludes> + </resource> + <resource> + <directory>${runtime.env}</directory> + </resource> + </resources> + </build> + +</project> \ No newline at end of file diff --git a/hx_common/src/main/java/com/hx/annotation/Jurisdiction.java b/hx_common/src/main/java/com/hx/annotation/Jurisdiction.java new file mode 100644 index 0000000..764d680 --- /dev/null +++ b/hx_common/src/main/java/com/hx/annotation/Jurisdiction.java @@ -0,0 +1,25 @@ +package com.hx.annotation; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/**鏉冮檺娉ㄨВ + * @author chenjiahe + * @version 2019骞�09鏈�14鏃� 涓嬪崍6:13:37 + */ +//琛ㄧず娉ㄨВ鍔犲湪鎺ュ彛銆佺被銆佹灇涓剧瓑 +@Target(ElementType.METHOD) +//VM灏嗗湪杩愯鏈熶篃淇濈暀娉ㄩ噴锛屽洜姝ゅ彲浠ラ�氳繃鍙嶅皠鏈哄埗璇诲彇娉ㄨВ鐨勪俊鎭� +@Retention(RetentionPolicy.RUNTIME) +//灏嗘娉ㄨВ鍖呭惈鍦╦avadoc涓� +@Documented +//鍏佽瀛愮被缁ф壙鐖剁被涓殑娉ㄨВ +@Inherited +public @interface Jurisdiction { + /**鏉冮檺鍚�*/ + String privilege(); +} diff --git a/hx_common/src/main/java/com/hx/api/CorpMpSpaceApi.java b/hx_common/src/main/java/com/hx/api/CorpMpSpaceApi.java new file mode 100644 index 0000000..fa97f08 --- /dev/null +++ b/hx_common/src/main/java/com/hx/api/CorpMpSpaceApi.java @@ -0,0 +1,196 @@ +package com.hx.api; + +import com.alibaba.fastjson.JSONObject; +import com.dtflys.forest.annotation.DataVariable; +import com.dtflys.forest.annotation.JSONBody; +import com.dtflys.forest.annotation.Post; + +/** + * 浼佷笟寰俊寰洏鎺ュ彛API + * @Author: cmg + * @Date: 2023-7-13 11:08 + */ +public interface CorpMpSpaceApi { + + /** + * 澧炲姞绌洪棿 + * @param accessToken + * @param param + * @return + */ + @Post( + url = "https://qyapi.weixin.qq.com/cgi-bin/wedrive/space_create?access_token=${accessToken}", + headers = { + "Content-Type: application/json" + } + ) + JSONObject addSpace(@DataVariable("accessToken") String accessToken, @JSONBody String param); + + /** + * 閲嶅懡鍚嶇┖闂� + * @param accessToken + * @param param + * @return + */ + @Post( + url = "https://qyapi.weixin.qq.com/cgi-bin/wedrive/space_rename?access_token=${accessToken}", + headers = { + "Content-Type: application/json" + } + ) + JSONObject renameSpace(@DataVariable("accessToken") String accessToken, @JSONBody String param); + + /** + * 瑙f暎绌洪棿 + * @param accessToken + * @param param + * @return + */ + @Post( + url = "https://qyapi.weixin.qq.com/cgi-bin/wedrive/space_dismiss?access_token=${accessToken}", + headers = { + "Content-Type: application/json" + } + ) + JSONObject dismissSpace(@DataVariable("accessToken") String accessToken, @JSONBody String param); + + /** + * 绌洪棿瀹夊叏璁剧疆 + * @param accessToken + * @param param + * @return + */ + @Post( + url = "https://qyapi.weixin.qq.com/cgi-bin/wedrive/space_setting?access_token=${accessToken}", + headers = { + "Content-Type: application/json" + } + ) + JSONObject spaceSetting(@DataVariable("accessToken") String accessToken, @JSONBody String param); + + /** + * 鏂板缓鏂囦欢澶�/鏂囨。 + * @param accessToken + * @param param + * @return + */ + @Post( + url = "https://qyapi.weixin.qq.com/cgi-bin/wedrive/file_create?access_token=${accessToken}", + headers = { + "Content-Type: application/json" + } + ) + JSONObject createFile(@DataVariable("accessToken") String accessToken, @JSONBody String param); + + /** + * 鏂囦欢閲嶅懡鍚� + * @param accessToken + * @param param + * @return + */ + @Post( + url = "https://qyapi.weixin.qq.com/cgi-bin/wedrive/file_rename?access_token=${accessToken}", + headers = { + "Content-Type: application/json" + } + ) + JSONObject renameFile(@DataVariable("accessToken") String accessToken, @JSONBody String param); + + /** + * 绉婚櫎鏂囦欢 + * @param accessToken + * @param param + * @return + */ + @Post( + url = "https://qyapi.weixin.qq.com/cgi-bin/wedrive/file_delete?access_token=${accessToken}", + headers = { + "Content-Type: application/json" + } + ) + JSONObject deleteFile(@DataVariable("accessToken") String accessToken, @JSONBody String param); + + /** + * 鍒嗗潡涓婁紶鍒濆鍖� + * @param accessToken + * @param param + * @return + */ + @Post( + url = "https://qyapi.weixin.qq.com/cgi-bin/wedrive/file_upload_init?access_token=${accessToken}", + headers = { + "Content-Type: application/json" + } + ) + JSONObject fileUploadInit(@DataVariable("accessToken") String accessToken, @JSONBody String param); + + /** + * 鍒嗗潡涓婁紶鏂囦欢 + * @param accessToken + * @param param + * @return + */ + @Post( + url = "https://qyapi.weixin.qq.com/cgi-bin/wedrive/file_upload_part?access_token=${accessToken}", + headers = { + "Content-Type: application/json" + } + ) + JSONObject fileUploadPart(@DataVariable("accessToken") String accessToken, @JSONBody String param); + + /** + * 鍒嗗潡涓婁紶瀹屾垚 + * @param accessToken + * @param param + * @return + */ + @Post( + url = "https://qyapi.weixin.qq.com/cgi-bin/wedrive/file_upload_finish?access_token=${accessToken}", + headers = { + "Content-Type: application/json" + } + ) + JSONObject fileUploadFinish(@DataVariable("accessToken") String accessToken, @JSONBody String param); + + /** + * 涓婁紶鏂囦欢 + * @param accessToken + * @param param + * @return + */ + @Post( + url = "https://qyapi.weixin.qq.com/cgi-bin/wedrive/file_upload?access_token=${accessToken}", + headers = { + "Content-Type: application/json" + } + ) + JSONObject fileUpload(@DataVariable("accessToken") String accessToken, @JSONBody String param); + + /** + * 鍒犻櫎鏂囦欢 + * @param accessToken + * @param param + * @return + */ + @Post( + url = "https://qyapi.weixin.qq.com/cgi-bin/wedrive/file_delete?access_token=${accessToken}", + headers = { + "Content-Type: application/json" + } + ) + JSONObject fileDelete(@DataVariable("accessToken") String accessToken, @JSONBody String param); + + /** + * 鑾峰彇涓嬭浇璺緞 + * @param accessToken + * @param param + * @return + */ + @Post( + url = "https://qyapi.weixin.qq.com/cgi-bin/wedrive/file_download?access_token=${accessToken}", + headers = { + "Content-Type: application/json" + } + ) + JSONObject getDownloadUrl(@DataVariable("accessToken") String accessToken, @JSONBody String param); +} diff --git a/hx_common/src/main/java/com/hx/bean/annotations/MysqlAutoAes.java b/hx_common/src/main/java/com/hx/bean/annotations/MysqlAutoAes.java new file mode 100644 index 0000000..715c6e6 --- /dev/null +++ b/hx_common/src/main/java/com/hx/bean/annotations/MysqlAutoAes.java @@ -0,0 +1,25 @@ +package com.hx.bean.annotations; + +import com.hx.mybatis.aes.springbean.ConstantBean; +import com.hx.mybatis.aes.springbean.InitMysqlData; +import com.hx.mybatis.aes.springbean.MySqlInterceptor; +import com.hx.mybatis.aes.springbean.VariableAesKey; +import com.hx.security.request.RequestRestriction; +import org.springframework.context.annotation.Import; + +import java.lang.annotation.*; + +/**鑷姩鍔燤ysql鐨凙ES鍔犲瘑绋嬪簭 + *杩欓噷鐨処mport鐨勪袱涓被灏辨槸闇�瑕佸姞杞界殑bean锛岃繖鏍峰氨鍙互閫氳繃绠�鍗曠殑娣诲姞涓�涓敞瑙f潵鍔犺浇鑷繁鑷畾涔夌殑bean浜嗭紝鑰屼笖鍙� + *浠ユ槸寰堝涓紝鍙互鎵撳埌jar鍖呴噷闈㈤�氳繃Maven寮曞叆閮芥槸ok鐨勶紱 + * @author CJH + * @date 202-06-17 + */ +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@Documented +@Import({ConstantBean.class, InitMysqlData.class, MySqlInterceptor.class, VariableAesKey.class}) +public @interface MysqlAutoAes { + + +} \ No newline at end of file diff --git a/hx_common/src/main/java/com/hx/bean/annotations/RedisClient.java b/hx_common/src/main/java/com/hx/bean/annotations/RedisClient.java new file mode 100644 index 0000000..5020054 --- /dev/null +++ b/hx_common/src/main/java/com/hx/bean/annotations/RedisClient.java @@ -0,0 +1,26 @@ +package com.hx.bean.annotations; + +import com.hx.mybatis.aes.springbean.ConstantBean; +import com.hx.mybatis.aes.springbean.InitMysqlData; +import com.hx.mybatis.aes.springbean.MySqlInterceptor; +import com.hx.mybatis.aes.springbean.VariableAesKey; +import com.hx.redis.RedisConfig; +import com.hx.redis.RedisUtil; +import org.springframework.context.annotation.Import; + +import java.lang.annotation.*; + +/**浣跨敤redis閾炬帴 + *杩欓噷鐨処mport鐨勪袱涓被灏辨槸闇�瑕佸姞杞界殑bean锛岃繖鏍峰氨鍙互閫氳繃绠�鍗曠殑娣诲姞涓�涓敞瑙f潵鍔犺浇鑷繁鑷畾涔夌殑bean浜嗭紝鑰屼笖鍙� + *浠ユ槸寰堝涓紝鍙互鎵撳埌jar鍖呴噷闈㈤�氳繃Maven寮曞叆閮芥槸ok鐨勶紱 + * @author CJH + * @date 202-06-17 + */ +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@Documented +@Import({RedisConfig.class, RedisUtil.class}) +public @interface RedisClient { + + +} \ No newline at end of file diff --git a/hx_common/src/main/java/com/hx/bean/annotations/RequestSecurity.java b/hx_common/src/main/java/com/hx/bean/annotations/RequestSecurity.java new file mode 100644 index 0000000..97e1099 --- /dev/null +++ b/hx_common/src/main/java/com/hx/bean/annotations/RequestSecurity.java @@ -0,0 +1,21 @@ +package com.hx.bean.annotations; + +import com.hx.security.request.RequestRestriction; +import org.springframework.context.annotation.Import; + +import java.lang.annotation.*; + +/**璇锋眰瀹夊叏bean鍔犺浇 + *杩欓噷鐨処mport鐨勪袱涓被灏辨槸闇�瑕佸姞杞界殑bean锛岃繖鏍峰氨鍙互閫氳繃绠�鍗曠殑娣诲姞涓�涓敞瑙f潵鍔犺浇鑷繁鑷畾涔夌殑bean浜嗭紝鑰屼笖鍙� + *浠ユ槸寰堝涓紝鍙互鎵撳埌jar鍖呴噷闈㈤�氳繃Maven寮曞叆閮芥槸ok鐨勶紱 + * @author CJH + * @date 202-06-17 + */ +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@Documented +@Import({RequestRestriction.class}) +public @interface RequestSecurity { + + +} \ No newline at end of file diff --git a/hx_common/src/main/java/com/hx/common/BaseController.java b/hx_common/src/main/java/com/hx/common/BaseController.java new file mode 100644 index 0000000..a6ddd46 --- /dev/null +++ b/hx_common/src/main/java/com/hx/common/BaseController.java @@ -0,0 +1,88 @@ +package com.hx.common; + +import com.hx.common.service.CommonService; +import com.hx.exception.ParamException; +import com.hx.exception.ServiceException; +import org.springframework.beans.propertyeditors.CustomDateEditor; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.InitBinder; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import org.springframework.web.context.request.WebRequest; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; + + +/**鍏叡鍒濆鍖� + * @author ChenJiaHe + * @Date 2020-06-11 + */ + +public class BaseController { + + @Resource + protected CommonService commonService; + /*璇蜂笉瑕佸0鏄庡彉閲忥紝浼氬鑷翠笉瀹夊叏锛屽洜涓鸿繖涓槸鍗曞垪*/ + + //鍙渶瑕佸姞涓婁笅闈㈣繖娈靛嵆鍙紝娉ㄦ剰涓嶈兘蹇樿娉ㄨВ + @InitBinder + public void initBinder(WebDataBinder binder, WebRequest request) { + //杞崲鏃ユ湡 娉ㄦ剰杩欓噷鐨勮浆鍖栬鍜屼紶杩涙潵鐨勫瓧绗︿覆鐨勬牸寮忎竴鐩� 濡�2015-9-9 灏卞簲璇ヤ负yyyy-MM-dd + DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));// CustomDateEditor涓鸿嚜瀹氫箟鏃ユ湡缂栬緫鍣� + } + + public HttpServletRequest getRequest() { + //鑾峰彇鍙傛暟瀵硅薄 + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + return attributes.getRequest(); + } + + public HttpSession getSession() { + //鑾峰彇鍙傛暟瀵硅薄 + return getRequest() .getSession(); + } + + /** + * 鑾峰彇request閲屾煇涓睘鎬� + * @param attrName 灞炴�у悕绉� + * @return 瀵硅薄 + */ + public Object getRequestAttribute(String attrName) + { + return getRequest().getAttribute(attrName); + } + + /** + * 璁剧疆涓�涓猺equest灞炴�� + * @param attrName 灞炴�у悕绉� + * @param attrObject 灞炴�у�� + */ + public void setRequestAttribute(String attrName, Object attrObject) { + getRequest().setAttribute(attrName, attrObject); + } + + /** + * 鎶涘嚭鏈嶅姟寮傚父 + * @param msg 閿欒淇℃伅 + */ + public void throwServiceException(String msg) + { + throw new ServiceException(msg); + } + + /** + * 鎶涘嚭鍙傛暟寮傚父 + * @param msg 閿欒淇℃伅 + */ + public void throwParamException(String msg) + { + throw new ParamException(msg); + } + +} diff --git a/hx_common/src/main/java/com/hx/common/annotations/MysqlHexAes.java b/hx_common/src/main/java/com/hx/common/annotations/MysqlHexAes.java new file mode 100644 index 0000000..8e5d753 --- /dev/null +++ b/hx_common/src/main/java/com/hx/common/annotations/MysqlHexAes.java @@ -0,0 +1,24 @@ +package com.hx.common.annotations; + +import java.lang.annotation.*; + +/** + * 鎸囧畾mysql鐨凙ES鍔犲瘑瀛楁 + * @author CJH + */ +@Target({ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface MysqlHexAes { + /**绉橀挜-娌℃湁灏辨槸閰嶇疆鏂囦欢璁剧疆*/ + String aesKey() default ""; + /**鏁版嵁搴撴暟鎹垵濮嬪寲鐗堟湰*/ + String initVersion() default ""; + /**xml鐢熸垚鏌ヨ瑙e瘑*/ + boolean selectDec() default false; + /**xml鏇存柊鍔犲瘑*/ + boolean updateDec() default false; + /**xml鏂板鍔犲瘑*/ + boolean insertDec() default false; + +} \ No newline at end of file diff --git a/hx_common/src/main/java/com/hx/common/annotations/repeat/RequestRepeat.java b/hx_common/src/main/java/com/hx/common/annotations/repeat/RequestRepeat.java new file mode 100644 index 0000000..a43c68d --- /dev/null +++ b/hx_common/src/main/java/com/hx/common/annotations/repeat/RequestRepeat.java @@ -0,0 +1,17 @@ +package com.hx.common.annotations.repeat; + +import java.lang.annotation.*; + +/** + * 閲嶅鏍¢獙娉ㄨВ + * @author CJH + */ +@Target({ElementType.TYPE, ElementType.METHOD}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface RequestRepeat { + /**鏄惁閲嶅鏍¢獙锛岄粯璁rue*/ + boolean isRepeat() default true; + /**閲嶅闂撮殧鏃堕棿锛屾绉掞紝榛樿1000姣*/ + long millisecond() default 1000; +} \ No newline at end of file diff --git a/hx_common/src/main/java/com/hx/common/dao/CommonDao.java b/hx_common/src/main/java/com/hx/common/dao/CommonDao.java new file mode 100644 index 0000000..9333082 --- /dev/null +++ b/hx_common/src/main/java/com/hx/common/dao/CommonDao.java @@ -0,0 +1,127 @@ +package com.hx.common.dao; +import com.hx.mybatisTool.SqlSentence; + +import java.io.Serializable; +import java.util.List; +import java.util.Map; + + +/** + * dao閫氱敤鎺ュ彛 + * @author ChenJiaHe + * @Date 2020-10-14 + */ +public interface CommonDao { + + /**鏂板锛岃繑鍥炰富閿� + * @param mapperClass mapper绫� + * @param entity 瀹炰綋绫� + * @return 鏉℃暟 + */ + <T extends Serializable> int insert(Class<?> mapperClass, T entity); + + /**鏂板锛岃繑鍥炰富閿� + * @param mapperClass mapper绫� + * @param entity 瀹炰綋绫� + * @return 鏉℃暟 + */ + <T extends Serializable> int insertById(Class<?> mapperClass, T entity); + + /**鏌ヨ鏉℃暟 + * @param mapperClass mapper绫� + * @param sqlSentence 鏌ヨ鍙傛暟绫� + * @return 杩斿洖鏉℃暟 + */ + <T extends Serializable> int selectCount(Class<?> mapperClass, SqlSentence sqlSentence); + + /**鏌ヨ鏉℃暟 + * @param mapperClass mapper绫� + * @param sqlSentence 鏌ヨ鍙傛暟绫� + * @return 杩斿洖鏉℃暟 + */ + <T extends Serializable> int selectCountSql(Class<?> mapperClass, SqlSentence sqlSentence); + + /**鏌ヨ鍒楄〃锛岃繑鍥炲疄浣撶被鐨凩ist + * @param mapperClass mapper绫� + * @param sqlSentence 鏌ヨ鍙傛暟绫� + * @return 杩斿洖list + */ + <T extends Serializable> List<T> selectList(Class<?> mapperClass, SqlSentence sqlSentence); + + /**鏌ヨ鍒楄〃锛岃繑鍥濵ap鐨凩ist + * @param mapperClass mapper绫� + * @param sqlSentence 鏌ヨ鍙傛暟绫� + * @return Map鐨凩ist + */ + <T extends Serializable> List<Map<String,Object>> selectListMap(Class<?> mapperClass, SqlSentence sqlSentence); + + /**鏌ヨ锛岃繑鍥炲崟涓疄浣� + * @param mapperClass mapper绫� + * @param sqlSentence 鏌ヨ鍙傛暟绫� + * @return 杩斿洖瀹炰綋绫� + */ + <T extends Serializable> T selectOne(Class<?> mapperClass, SqlSentence sqlSentence); + + /**鏌ヨ锛岃繑鍥炲崟涓猰ap + * @param mapperClass mapper绫� + * @param sqlSentence 鏌ヨ鍙傛暟绫� + * @return 杩斿洖瀹炰綋绫� + */ + <T extends Serializable> Map<String,Object> selectOneMap(Class<?> mapperClass, SqlSentence sqlSentence); + + /**鏌ヨ锛岃繑鍥炲疄浣撶被娌℃湁澶ф暟鎹殑 + * @param mapperClass mapper绫� + * @param object 鏁版嵁鏍囪瘑key + * @return 杩斿洖瀹炰綋绫� + */ + <T extends Serializable> T selectOneByKey(Class<?> mapperClass, Object object); + + /**鏌ヨ锛岃繑鍥炲疄浣撶被鏈夊ぇ鏁版嵁鐨� + * @param mapperClass mapper绫� + * @param object 鏁版嵁鏍囪瘑key + * @return 杩斿洖瀹炰綋绫� + */ + <T extends Serializable> T selectOneByKeyBlob(Class<?> mapperClass, Object object); + + /**鏇存柊锛岃繑鍥炴洿鏂版暟閲� + * @param mapperClass mapper绫� + * @param sqlSentence 鏌ヨ鍙傛暟绫� + * @return 杩斿洖鏉℃暟 + */ + <T extends Serializable> int updateWhere(Class<?> mapperClass, SqlSentence sqlSentence); + + /**鏇存柊锛岃繑鍥炴洿鏂版暟閲� + * @param mapperClass mapper绫� + * @param entity 瀹炰綋绫� + * @return 杩斿洖鏉℃暟 + */ + <T extends Serializable> int updateAll(Class<?> mapperClass, T entity); + + /**鍒犻櫎锛岃繑鍥炲垹闄ゆ暟閲� + * @param mapperClass mapper绫� + * @param sqlSentence 鏌ヨ鍙傛暟绫� + * @return 杩斿洖鏉℃暟 + */ + <T extends Serializable> int deleteWhere(Class<?> mapperClass, SqlSentence sqlSentence); + + /**鍒犻櫎锛岃繑鍥炲垹闄ゆ暟閲� + * @param mapperClass mapper绫� + * @param object 鏁版嵁鏍囪瘑key + * @return 杩斿洖鏉℃暟 + */ + <T extends Serializable> int deleteById(Class<?> mapperClass, Object object); + + /**鏇存柊sql璇彞锛堝叏璇彞锛� + * @param sqlSentence 鏌ヨ鍙傛暟绫� + * @return 杩斿洖鏉℃暟 + */ + <T extends Serializable> int updateSentence( SqlSentence sqlSentence); + + /**鏌ヨ鏉℃暟璇彞锛堝叏璇彞锛� + * @param sqlSentence 鏌ヨ鍙傛暟绫� + * @return 杩斿洖鏉℃暟 + */ + <T extends Serializable> int selectCountSql( SqlSentence sqlSentence); + + +} \ No newline at end of file diff --git a/hx_common/src/main/java/com/hx/common/dao/mapper/CommonMapper.java b/hx_common/src/main/java/com/hx/common/dao/mapper/CommonMapper.java new file mode 100644 index 0000000..24205c8 --- /dev/null +++ b/hx_common/src/main/java/com/hx/common/dao/mapper/CommonMapper.java @@ -0,0 +1,20 @@ +package com.hx.common.dao.mapper; + +import com.hx.mybatisTool.SqlSentence; + + +import java.util.List; +import java.util.Map; + +public interface CommonMapper { + + /**鏇存柊锛岃繑鍥炴洿鏂版暟閲�*/ + int updateSentence(SqlSentence sqlSentence); + + /**鏌ヨ鍒楄〃锛岃繑鍥濵ap鐨凩ist*/ + List<Map<String,Object>> selectListMap(SqlSentence sqlSentence); + + /**鏌ヨ锛岃繑鍥炴潯鏁版暟閲�*/ + int selectCountSql(SqlSentence sqlSentence); + +} \ No newline at end of file diff --git a/hx_common/src/main/java/com/hx/common/service/CommonService.java b/hx_common/src/main/java/com/hx/common/service/CommonService.java new file mode 100644 index 0000000..81e1adb --- /dev/null +++ b/hx_common/src/main/java/com/hx/common/service/CommonService.java @@ -0,0 +1,127 @@ +package com.hx.common.service; +import com.hx.mybatisTool.SqlSentence; + +import java.io.Serializable; +import java.util.List; +import java.util.Map; + + +/** + * dao閫氱敤鎺ュ彛 + * @author ChenJiaHe + * @Date 2020-10-14 + */ +public interface CommonService { + + /**鏂板锛岃繑鍥炰富閿� + * @param mapperClass mapper绫� + * @param entity 瀹炰綋绫� + * @return 鏉℃暟 + */ + <T extends Serializable> int insert(Class<?> mapperClass, T entity); + + /**鏂板锛岃繑鍥炰富閿� + * @param mapperClass mapper绫� + * @param entity 瀹炰綋绫� + * @return 鏉℃暟 + */ + <T extends Serializable> int insertById(Class<?> mapperClass, T entity); + + /**鏌ヨ鏉℃暟 + * @param mapperClass mapper绫� + * @param sqlSentence 鏌ヨ鍙傛暟绫� + * @return 杩斿洖鏉℃暟 + */ + <T extends Serializable> int selectCount(Class<?> mapperClass, SqlSentence sqlSentence); + + /**鏌ヨ鏉℃暟 + * @param mapperClass mapper绫� + * @param sqlSentence 鏌ヨ鍙傛暟绫� + * @return 杩斿洖鏉℃暟 + */ + <T extends Serializable> int selectCountSql(Class<?> mapperClass, SqlSentence sqlSentence); + + + /**鏌ヨ鍒楄〃锛岃繑鍥炲疄浣撶被鐨凩ist + * @param mapperClass mapper绫� + * @param sqlSentence 鏌ヨ鍙傛暟绫� + * @return 杩斿洖list + */ + <T extends Serializable> List<T> selectList(Class<?> mapperClass, SqlSentence sqlSentence); + + /**鏌ヨ鍒楄〃锛岃繑鍥濵ap鐨凩ist + * @param mapperClass mapper绫� + * @param sqlSentence 鏌ヨ鍙傛暟绫� + * @return Map鐨凩ist + */ + <T extends Serializable> List<Map<String,Object>> selectListMap(Class<?> mapperClass, SqlSentence sqlSentence); + + /**鏌ヨ锛岃繑鍥炲崟涓疄浣� + * @param mapperClass mapper绫� + * @param sqlSentence 鏌ヨ鍙傛暟绫� + * @return 杩斿洖瀹炰綋绫� + */ + <T extends Serializable> T selectOne(Class<?> mapperClass, SqlSentence sqlSentence); + + /**鏌ヨ锛岃繑鍥炲崟涓猰ap + * @param mapperClass mapper绫� + * @param sqlSentence 鏌ヨ鍙傛暟绫� + * @return 杩斿洖瀹炰綋绫� + */ + <T extends Serializable> Map<String,Object> selectOneMap(Class<?> mapperClass, SqlSentence sqlSentence); + + /**鏌ヨ锛岃繑鍥炲疄浣撶被娌℃湁澶ф暟鎹殑 + * @param mapperClass mapper绫� + * @param object 鏁版嵁鏍囪瘑key + * @return 杩斿洖瀹炰綋绫� + */ + <T extends Serializable> T selectOneByKey(Class<?> mapperClass, Object object); + + /**鏌ヨ锛岃繑鍥炲疄浣撶被鏈夊ぇ鏁版嵁鐨� + * @param mapperClass mapper绫� + * @param object 鏁版嵁鏍囪瘑key + * @return 杩斿洖瀹炰綋绫� + */ + <T extends Serializable> T selectOneByKeyBlob(Class<?> mapperClass, Object object); + + /**鏇存柊锛岃繑鍥炴洿鏂版暟閲� + * @param mapperClass mapper绫� + * @param sqlSentence 鏌ヨ鍙傛暟绫� + * @return 杩斿洖鏉℃暟 + */ + <T extends Serializable> int updateWhere(Class<?> mapperClass, SqlSentence sqlSentence); + + /**鏇存柊锛岃繑鍥炴洿鏂版暟閲� + * @param mapperClass mapper绫� + * @param entity 瀹炰綋绫� + * @return 杩斿洖鏉℃暟 + */ + <T extends Serializable> int updateAll(Class<?> mapperClass, T entity); + + /**鍒犻櫎锛岃繑鍥炲垹闄ゆ暟閲� + * @param mapperClass mapper绫� + * @param sqlSentence 鏌ヨ鍙傛暟绫� + * @return 杩斿洖鏉℃暟 + */ + <T extends Serializable> int deleteWhere(Class<?> mapperClass, SqlSentence sqlSentence); + + /**鍒犻櫎锛岃繑鍥炲垹闄ゆ暟閲� + * @param mapperClass mapper绫� + * @param object 鏁版嵁鏍囪瘑key + * @return 杩斿洖鏉℃暟 + */ + <T extends Serializable> int deleteById(Class<?> mapperClass, Object object); + + /**鏇存柊sql璇彞锛堝叏璇彞锛� + * @param sqlSentence 鏌ヨ鍙傛暟绫� + * @return 杩斿洖鏉℃暟 + */ + <T extends Serializable> int updateSentence(SqlSentence sqlSentence); + + /**鏌ヨ鏉℃暟璇彞锛堝叏璇彞锛� + * @param sqlSentence 鏌ヨ鍙傛暟绫� + * @return 杩斿洖鏉℃暟 + */ + <T extends Serializable> int selectCountSql(SqlSentence sqlSentence); + +} \ No newline at end of file diff --git a/hx_common/src/main/java/com/hx/common/service/impl/CommonDaoImpl.java b/hx_common/src/main/java/com/hx/common/service/impl/CommonDaoImpl.java new file mode 100644 index 0000000..8ccd28d --- /dev/null +++ b/hx_common/src/main/java/com/hx/common/service/impl/CommonDaoImpl.java @@ -0,0 +1,123 @@ +package com.hx.common.service.impl; + +import com.hx.common.dao.CommonDao; +import com.hx.common.dao.mapper.CommonMapper; +import com.hx.mybatisTool.SqlSentence; +import org.apache.ibatis.session.SqlSessionFactory; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.io.Serializable; +import java.util.List; +import java.util.Map; + +/**褰撳墠鏄病鏈変簨鍔″鐞嗭紝鍒囧嬁鐩存帴浣跨敤*/ +@Service +public class CommonDaoImpl implements CommonDao { + + @Resource(name = "sqlSessionFactory") + protected SqlSessionFactory sqlSessionFactory; + + /**缁勬嫾XML鏂囦欢sql鐨刬d*/ + private <T> String getStatement(Class<T> clazz, String prefix){ + return clazz.getName()+"."+prefix; + } + + /**鎻掑叆*/ + @Override + public <T extends Serializable> int insert(Class<?> mapperClass,T entity) { + return sqlSessionFactory.openSession().insert(getStatement(mapperClass,"insert"),entity); + } + + @Override + public <T extends Serializable> int insertById(Class<?> mapperClass, T entity) { + return sqlSessionFactory.openSession().insert(getStatement(mapperClass,"insertById"),entity); + } + + /**鑾峰彇鏉℃暟 + * @return*/ + @Override + public <T extends Serializable> int selectCount(Class<?> mapperClass, SqlSentence sqlSentence) { + return sqlSessionFactory.openSession().selectOne(getStatement(mapperClass,"selectCount"),sqlSentence); + } + + /**鑾峰彇鏉℃暟 + * @return*/ + @Override + public <T extends Serializable> int selectCountSql(Class<?> mapperClass, SqlSentence sqlSentence) { + return sqlSessionFactory.openSession().selectOne(getStatement(mapperClass,"selectCountSql"),sqlSentence); + } + + /**鑾峰彇鍒楄〃*/ + @Override + public <T extends Serializable> List<T> selectList(Class<?> mapperClass, SqlSentence sqlSentence) { + return sqlSessionFactory.openSession().selectList(getStatement(mapperClass,"selectList"),sqlSentence); + } + + /**鑾峰彇鍒楄〃*/ + @Override + public <T extends Serializable> List<Map<String, Object>> selectListMap(Class<?> mapperClass, SqlSentence sqlSentence) { + return sqlSessionFactory.openSession().selectList(getStatement(mapperClass,"selectListMap"),sqlSentence); + } + + /**鑾峰彇鍗曟潯鏁版嵁*/ + @Override + public <T extends Serializable> T selectOne(Class<?> mapperClass, SqlSentence sqlSentence) { + return sqlSessionFactory.openSession().selectOne(getStatement(mapperClass,"selectOne"),sqlSentence); + } + + /**鑾峰彇鍗曟潯鏁版嵁*/ + @Override + public <T extends Serializable> Map<String, Object> selectOneMap(Class<?> mapperClass, SqlSentence sqlSentence) { + return sqlSessionFactory.openSession().selectOne(getStatement(mapperClass,"selectOneMap"),sqlSentence); + } + + /**鑾峰彇鍗曟潯鏁版嵁-涓嶅惈longText鐨勬暟鎹�*/ + @Override + public <T extends Serializable> T selectOneByKey(Class<?> mapperClass,Object object) { + return sqlSessionFactory.openSession().selectOne(getStatement(mapperClass,"selectOneByKey"),object); + } + + /**鑾峰彇鍗曟潯鏁版嵁-鍚玪ongText鐨勬暟鎹�*/ + @Override + public <T extends Serializable> T selectOneByKeyBlob(Class<?> mapperClass,Object object) { + return sqlSessionFactory.openSession().selectOne(getStatement(mapperClass,"selectOneByKeyBlob"),object); + } + + /**鏇存柊*/ + @Override + public <T extends Serializable> int updateWhere(Class<?> mapperClass,SqlSentence sqlSentence) { + return sqlSessionFactory.openSession().update(getStatement(mapperClass,"updateWhere"),sqlSentence); + } + + /**鍏ㄩ儴瀛楁鏇存柊*/ + @Override + public <T extends Serializable> int updateAll(Class<?> mapperClass,T entity) { + return sqlSessionFactory.openSession().update(getStatement(mapperClass,"updateAll"),entity); + } + + /**鍒犻櫎*/ + @Override + public <T extends Serializable> int deleteWhere(Class<?> mapperClass,SqlSentence sqlSentence) { + return sqlSessionFactory.openSession().delete(getStatement(mapperClass,"deleteWhere"),sqlSentence); + } + + /**鍒犻櫎*/ + @Override + public <T extends Serializable> int deleteById(Class<?> mapperClass,Object object) { + return sqlSessionFactory.openSession().delete(getStatement(mapperClass,"deleteById"),object); + } + + /**鏇存柊sql璇彞锛堝叏璇彞锛�*/ + @Override + public <T extends Serializable> int updateSentence(SqlSentence sqlSentence) { + return sqlSessionFactory.openSession().update(getStatement(CommonMapper.class,"updateSentence"),sqlSentence); + } + + /**鏌ヨ鏉℃暟锛堝叏璇彞锛�*/ + @Override + public <T extends Serializable> int selectCountSql(SqlSentence sqlSentence) { + return sqlSessionFactory.openSession().selectOne(getStatement(CommonMapper.class,"selectCountSql"),sqlSentence); + } + +} diff --git a/hx_common/src/main/java/com/hx/common/service/impl/CommonServiceImpl.java b/hx_common/src/main/java/com/hx/common/service/impl/CommonServiceImpl.java new file mode 100644 index 0000000..22108d6 --- /dev/null +++ b/hx_common/src/main/java/com/hx/common/service/impl/CommonServiceImpl.java @@ -0,0 +1,119 @@ +package com.hx.common.service.impl; + +import com.hx.common.dao.CommonDao; +import com.hx.common.service.CommonService; +import com.hx.mybatisTool.SqlSentence; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.annotation.Resource; +import java.io.Serializable; +import java.util.List; +import java.util.Map; + +/**褰撳墠鏄湁浜嬪姟澶勭悊*/ +@Transactional +@Service +public class CommonServiceImpl implements CommonService { + + @Resource + private CommonDao commonDao; + + /**鎻掑叆*/ + @Override + public <T extends Serializable> int insert(Class<?> mapperClass,T entity) { + return commonDao.insert(mapperClass,entity); + } + + @Override + public <T extends Serializable> int insertById(Class<?> mapperClass, T entity) { + return commonDao.insertById(mapperClass,entity); + } + + /**鑾峰彇鏉℃暟*/ + @Override + public <T extends Serializable> int selectCount(Class<?> mapperClass,SqlSentence sqlSentence) { + return commonDao.selectCount(mapperClass,sqlSentence); + } + + /**鑾峰彇鏉℃暟*/ + @Override + public <T extends Serializable> int selectCountSql(Class<?> mapperClass,SqlSentence sqlSentence) { + return commonDao.selectCountSql(mapperClass,sqlSentence); + } + + /**鑾峰彇鍒楄〃*/ + @Override + public <T extends Serializable> List<T> selectList(Class<?> mapperClass, SqlSentence sqlSentence) { + return commonDao.selectList(mapperClass,sqlSentence); + } + + /**鑾峰彇鍒楄〃*/ + @Override + public <T extends Serializable> List<Map<String, Object>> selectListMap(Class<?> mapperClass, SqlSentence sqlSentence) { + return commonDao.selectListMap(mapperClass,sqlSentence); + } + + /**鑾峰彇鍗曟潯鏁版嵁*/ + @Override + public <T extends Serializable> T selectOne(Class<?> mapperClass, SqlSentence sqlSentence) { + return commonDao.selectOne(mapperClass,sqlSentence); + } + + /**鑾峰彇鍗曟潯鏁版嵁*/ + @Override + public <T extends Serializable> Map<String, Object> selectOneMap(Class<?> mapperClass, SqlSentence sqlSentence) { + return commonDao.selectOneMap(mapperClass,sqlSentence); + } + + /**鑾峰彇鍗曟潯鏁版嵁-涓嶅惈longText鐨勬暟鎹�*/ + @Override + public <T extends Serializable> T selectOneByKey(Class<?> mapperClass,Object object) { + return commonDao.selectOneByKey(mapperClass,object); + } + + /**鑾峰彇鍗曟潯鏁版嵁-鍚玪ongText鐨勬暟鎹�*/ + @Override + public <T extends Serializable> T selectOneByKeyBlob(Class<?> mapperClass,Object object) { + return commonDao.selectOneByKeyBlob(mapperClass,object); + } + + /**鏇存柊*/ + @Override + public <T extends Serializable> int updateWhere(Class<?> mapperClass,SqlSentence sqlSentence) { + return commonDao.updateWhere(mapperClass,sqlSentence); + } + + /**鍏ㄩ儴瀛楁鏇存柊*/ + @Override + public <T extends Serializable> int updateAll(Class<?> mapperClass,T entity) { + return commonDao.updateAll(mapperClass,entity); + } + + /**鍒犻櫎*/ + @Override + public <T extends Serializable> int deleteWhere(Class<?> mapperClass,SqlSentence sqlSentence) { + return commonDao.deleteWhere(mapperClass,sqlSentence); + } + + /**鍒犻櫎*/ + @Override + public <T extends Serializable> int deleteById(Class<?> mapperClass,Object object) { + return commonDao.deleteById(mapperClass,object); + } + + + /**鏇存柊sql璇彞锛堝叏璇彞锛�*/ + @Override + public <T extends Serializable> int updateSentence(SqlSentence sqlSentence) { + return commonDao.updateSentence(sqlSentence); + } + + /**鏇存柊sql璇彞锛堝叏璇彞锛�*/ + @Override + public <T extends Serializable> int selectCountSql(SqlSentence sqlSentence) { + return commonDao.selectCountSql(sqlSentence); + } + + +} diff --git a/hx_common/src/main/java/com/hx/common/xml/CommonMapper.xml b/hx_common/src/main/java/com/hx/common/xml/CommonMapper.xml new file mode 100644 index 0000000..62c4dc1 --- /dev/null +++ b/hx_common/src/main/java/com/hx/common/xml/CommonMapper.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<!DOCTYPE mapper +PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" +"http://mybatis.org/dtd/mybatis-3-mapper.dtd"> +<!-- namespace:璇apper.xml鏄犲皠鏂囦欢鐨� 鍞竴鏍囪瘑 --> +<mapper namespace="com.hx.common.dao.mapper.CommonMapper"> + <update id="updateSentence" parameterType="com.hx.mybatisTool.SqlSentence" > + ${sqlSentence} + </update> + + <select id="selectListMap" resultType="java.util.Map" parameterType="com.hx.mybatisTool.SqlSentence" > + ${sqlSentence} + </select> + + <select id="selectCountSql" resultType="int" parameterType="com.hx.mybatisTool.SqlSentence" > + ${sqlSentence} + </select> + +</mapper> \ No newline at end of file diff --git a/hx_common/src/main/java/com/hx/corp/entity/CorpPayRequest.java b/hx_common/src/main/java/com/hx/corp/entity/CorpPayRequest.java new file mode 100644 index 0000000..de57762 --- /dev/null +++ b/hx_common/src/main/java/com/hx/corp/entity/CorpPayRequest.java @@ -0,0 +1,135 @@ +package com.hx.corp.entity; + +import java.util.UUID; + +/**浼佷笟浠樻璇锋眰鍙傛暟瀹炰綋 + * + */ +public class CorpPayRequest { + + /*锛圷锛夊晢鎴疯处鍙穉ppid锛岀敵璇峰晢鎴峰彿鐨刟ppid鎴栧晢鎴峰彿缁戝畾鐨刟ppid*/ + private String mch_appid; + /*(Y)鍟嗘埛鍙�*/ + private String mchid; + /*(N)璁惧鍙�*/ + private String device_info; + /*(Y)闅忔満瀛楃涓�*/ + private String nonce_str = UUID.randomUUID().toString().substring(0, 30); + /*(Y)闅忕鍚�*/ + private String sign; + /*(Y)鍟嗘埛璁㈠崟鍙�*/ + private String partner_trade_no; + /*(Y)鐢ㄦ埛openid*/ + private String openid; + /*(Y)鏍¢獙鐢ㄦ埛濮撳悕閫夐」锛孨O_CHECK锛氫笉鏍¢獙鐪熷疄濮撳悕 锛汧ORCE_CHECK锛氬己鏍¢獙鐪熷疄濮撳悕*/ + private String check_name = "NO_CHECK"; + /*(O)鏀舵鐢ㄦ埛濮撳悕,濡傛灉check_name璁剧疆涓篎ORCE_CHECK锛屽垯蹇呭~鐢ㄦ埛鐪熷疄濮撳悕*/ + private String re_user_name; + /*(Y)閲戦*/ + private Integer amount; + /*(Y)浼佷笟浠樻澶囨敞*/ + private String desc; + /*(N)Ip鍦板潃锛岃IP鍚屽湪鍟嗘埛骞冲彴璁剧疆鐨処P鐧藉悕鍗曚腑鐨処P娌℃湁鍏宠仈锛岃IP鍙紶鐢ㄦ埛绔垨鑰呮湇鍔$鐨処P*/ + private String spbill_create_ip = "8.8.8.8"; + + public CorpPayRequest() { + } + + //////////////////////////////////////////////////////// + + public String getMch_appid() { + return mch_appid; + } + + public void setMch_appid(String mch_appid) { + this.mch_appid = mch_appid; + } + + public String getMchid() { + return mchid; + } + + public void setMchid(String mchid) { + this.mchid = mchid; + } + + public String getDevice_info() { + return device_info; + } + + public void setDevice_info(String device_info) { + this.device_info = device_info; + } + + public String getSign() { + return sign; + } + + public void setSign(String sign) { + this.sign = sign; + } + + public String getPartner_trade_no() { + return partner_trade_no; + } + + public void setPartner_trade_no(String partner_trade_no) { + this.partner_trade_no = partner_trade_no; + } + + public String getOpenid() { + return openid; + } + + public void setOpenid(String openid) { + this.openid = openid; + } + + public String getCheck_name() { + return check_name; + } + + public void setCheck_name(String check_name) { + this.check_name = check_name; + } + + public String getRe_user_name() { + return re_user_name; + } + + public void setRe_user_name(String re_user_name) { + this.re_user_name = re_user_name; + } + + public Integer getAmount() { + return amount; + } + + public void setAmount(Integer amount) { + this.amount = amount; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public String getSpbill_create_ip() { + return spbill_create_ip; + } + + public void setSpbill_create_ip(String spbill_create_ip) { + this.spbill_create_ip = spbill_create_ip; + } + + public String getNonce_str() { + return nonce_str; + } + + public void setNonce_str(String nonce_str) { + this.nonce_str = nonce_str; + } +} diff --git a/hx_common/src/main/java/com/hx/corp/entity/CorpPayResponse.java b/hx_common/src/main/java/com/hx/corp/entity/CorpPayResponse.java new file mode 100644 index 0000000..46d5ecf --- /dev/null +++ b/hx_common/src/main/java/com/hx/corp/entity/CorpPayResponse.java @@ -0,0 +1,157 @@ +package com.hx.corp.entity; + +/**浼佷笟浠樻杩斿洖鍙傛暟瀹炰綋 + * + */ +public class CorpPayResponse { + + /*(Y)涓氬姟缁撴灉锛孲UCCESS/FAIL锛屾敞鎰忥細褰撶姸鎬佷负FAIL鏃讹紝瀛樺湪涓氬姟缁撴灉鏈槑纭殑鎯呭喌銆傚鏋滅姸鎬佷负FAIL锛岃鍔″繀鍏虫敞閿欒浠g爜锛坋rr_code瀛楁锛夛紝閫氳繃鏌ヨ鎺ュ彛纭姝ゆ浠樻鐨勭粨鏋�*/ + private String result_code = "FAIL"; + /*锛圷锛夎繑鍥炵姸鎬佺爜,SUCCESS/FAIL锛屾瀛楁鏄�氫俊鏍囪瘑锛岄潪浜ゆ槗鏍囪瘑锛屼氦鏄撴槸鍚︽垚鍔熼渶瑕佹煡鐪媟esult_code鏉ュ垽鏂�*/ + private String return_code = "FAIL"; + /*(Y) 杩斿洖淇℃伅 */ + private String return_msg; + /*锛圷锛夐敊璇唬鐮�*/ + private String err_code; + /*(Y)閿欒浠g爜鎻忚堪*/ + private String err_code_des; + /*(Y)鍟嗘埛appid*/ + private String mch_appid; + /*(Y)鍟嗘埛鍙�*/ + private String mchid; + /*(N)璁惧鍙�*/ + private String device_info; + /*(Y)闅忔満瀛楃涓�*/ + private String nonce_str; + + //浠ヤ笅瀛楁鍦╮eturn_code 鍜宺esult_code閮戒负SUCCESS鐨勬椂鍊欐湁杩斿洖 + /*(O)鍟嗘埛璁㈠崟鍙�*/ + private String partner_trade_no; + /*(O)鍟嗘埛璁㈠崟鍙�*/ + private String payment_no; + /*(O)浠樻鎴愬姛鏃堕棿*/ + private String payment_time; + + + public CorpPayResponse() { + } + + public static final String CODE_SUC = "SUCCESS"; + public static final String CODE_FAIL = "FAIL"; + + //////////////////////////////////////////////////////// + + public String getMch_appid() { + return mch_appid; + } + + public void setMch_appid(String mch_appid) { + this.mch_appid = mch_appid; + } + + public String getMchid() { + return mchid; + } + + public void setMchid(String mchid) { + this.mchid = mchid; + } + + public String getDevice_info() { + return device_info; + } + + public void setDevice_info(String device_info) { + this.device_info = device_info; + } + + public String getResult_code() { + return result_code; + } + + public void setResult_code(String result_code) { + this.result_code = result_code; + } + + public String getErr_code() { + return err_code; + } + + public void setErr_code(String err_code) { + this.err_code = err_code; + } + + public String getErr_code_des() { + return err_code_des; + } + + public void setErr_code_des(String err_code_des) { + this.err_code_des = err_code_des; + } + + public String getNonce_str() { + return nonce_str; + } + + public void setNonce_str(String nonce_str) { + this.nonce_str = nonce_str; + } + + public String getPartner_trade_no() { + return partner_trade_no; + } + + public void setPartner_trade_no(String partner_trade_no) { + this.partner_trade_no = partner_trade_no; + } + + public String getPayment_no() { + return payment_no; + } + + public void setPayment_no(String payment_no) { + this.payment_no = payment_no; + } + + public String getPayment_time() { + return payment_time; + } + + public void setPayment_time(String payment_time) { + this.payment_time = payment_time; + } + + public String getReturn_code() { + return return_code; + } + + public void setReturn_code(String return_code) { + this.return_code = return_code; + } + + public String getReturn_msg() { + return return_msg; + } + + public void setReturn_msg(String return_msg) { + this.return_msg = return_msg; + } + + @Override + public String toString() { + return "CorpPayResponse{" + + "result_code='" + result_code + '\'' + + ", return_code='" + return_code + '\'' + + ", return_msg='" + return_msg + '\'' + + ", err_code='" + err_code + '\'' + + ", err_code_des='" + err_code_des + '\'' + + ", mch_appid='" + mch_appid + '\'' + + ", mchid='" + mchid + '\'' + + ", device_info='" + device_info + '\'' + + ", nonce_str='" + nonce_str + '\'' + + ", partner_trade_no='" + partner_trade_no + '\'' + + ", payment_no='" + payment_no + '\'' + + ", payment_time='" + payment_time + '\'' + + '}'; + } +} diff --git a/hx_common/src/main/java/com/hx/corp/util/WxCorpPayUtil.java b/hx_common/src/main/java/com/hx/corp/util/WxCorpPayUtil.java new file mode 100644 index 0000000..7ddf66e --- /dev/null +++ b/hx_common/src/main/java/com/hx/corp/util/WxCorpPayUtil.java @@ -0,0 +1,613 @@ +package com.hx.corp.util; + +import com.alibaba.fastjson.JSON; +import com.hx.util.corp.entity.AppLetInfo; +import com.hx.corp.entity.CorpPayRequest; +import com.hx.corp.entity.CorpPayResponse; +import com.hx.exception.ServiceException; +import com.hx.mp.util.*; +import com.hx.util.HttpMethodUtil; +import com.hx.util.SimpleTool; +import com.hx.util.StringUtils; +import net.sf.json.JSONObject; +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.ssl.SSLContexts; +import org.apache.http.util.EntityUtils; +import org.dom4j.Document; +import org.dom4j.Element; +import org.dom4j.io.SAXReader; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.net.ssl.SSLContext; +import javax.servlet.http.HttpServletRequest; +import java.io.File; +import java.io.FileInputStream; +import java.security.KeyStore; +import java.util.*; + + +/** 浼佷笟寰俊鏀粯/閫�娆� + * @author ChenJiaHe + */ +public class WxCorpPayUtil { + + //log4j鏃ュ織 + private static Logger logger = LoggerFactory.getLogger(WxCorpPayUtil.class.getName()); + + // 閫�娆炬帴鍙h繛鎺� + private static final String REFUND_URL = "https://api.mch.weixin.qq.com/secapi/pay/refund"; + /**鏌ヨ璁㈠崟閾炬帴*/ + @SuppressWarnings("unused") + private static final String QUERY_URL = "https://api.mch.weixin.qq.com/pay/orderquery"; + /**鍚屾剰涓嬪崟閾炬帴*/ + private static final String FIRST_ORDER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder"; + + // 浼佷笟浠樻 + private static final String CORP_PAY_URL = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers"; + + + /** 浼佷笟浠樻 + * @param corpPayRequest 璇锋眰瀵硅薄 + * @param mchKey 鍟嗘埛鍙风閽� + * @param certPath 鏀粯璇佷功 + * @return CorpPayResponse + * @throws Exception + */ + public static CorpPayResponse qdCorpPay(CorpPayRequest corpPayRequest, String mchKey, String certPath) + throws Exception { + + CorpPayResponse corpPayResponse = new CorpPayResponse(); + + SortedMap<Object, Object> parameters = new TreeMap<Object, Object>(); + parameters.put("mch_appid", corpPayRequest.getMch_appid()); + parameters.put("mchid", corpPayRequest.getMchid()); + parameters.put("partner_trade_no", corpPayRequest.getPartner_trade_no()); + //parameters.put("nonce_str", UUID.randomUUID().toString().substring(0, 30)); + parameters.put("nonce_str", corpPayRequest.getNonce_str()); + parameters.put("openid", corpPayRequest.getOpenid()); + parameters.put("check_name", corpPayRequest.getCheck_name()); + parameters.put("amount", corpPayRequest.getAmount().toString()); + parameters.put("spbill_create_ip", corpPayRequest.getSpbill_create_ip()); + parameters.put("desc", corpPayRequest.getDesc()); + + corpPayRequest.setSign(WXSignUtils.createSign("UTF-8", parameters, mchKey)); + parameters.put("sign", corpPayRequest.getSign()); + String xmlInfo = HttpXmlUtils.transferXml(parameters); + try { + CloseableHttpResponse response = HttpUtil.Post(CORP_PAY_URL, xmlInfo, true, certPath, corpPayRequest.getMchid()); + String transfersXml = EntityUtils.toString(response.getEntity(), "utf-8"); + + //Map<String, String> transferMap = HttpXmlUtils.parseRefundXml(transfersXml); + + Map<String,Object> transferMap = XMLUtil.doXMLParse(transfersXml); + + // 灏� Map 杞崲涓� 瀹炰綋绫� + corpPayResponse = JSON.parseObject(JSON.toJSONString(transferMap),CorpPayResponse.class); + } catch (Exception e) { + logger.error("浼佷笟浠樻鎺ュ彛鎶ラ敊",e); + } + return corpPayResponse; + } + + + /**缁熶竴鏀粯 + * @param request 鏂规硶鑾峰彇 + * @param appId 灏忕▼搴忓彿 + * @param partner 鍟嗘埛鍙� + * @param key 绉橀挜 + * @param notifyUrl 鍥炶皟閾炬帴 + * @param out_trade_no 璁㈠崟鍙� + * @param body 鍟嗗搧鎻忚堪 + * @param total_fee 鏀粯閲戦 + * @param openid 鐢ㄦ埛openId + * @param attach 闄勫甫鏁版嵁鍖� + * @param notifyUrl 鍥炶皟閫氱煡鍦板潃 + * @param trade_type 浜ゆ槗绫诲瀷 + * @return JSON status = "SUC"涓烘垚鍔� + */ + public static JSONObject unifiedPay(HttpServletRequest request,String appId,String partner,String key,String notifyUrl,String out_trade_no, String body, String total_fee, String openid, + String attach,String trade_type) throws Exception { + + if (!SimpleTool.checkNotNull(notifyUrl)) { + throw new ServiceException("鏀粯鍔熻兘鏁呴殰锛�"); + } + + // 鍒涘缓鏌ヨ璇锋眰瀵硅薄 + RequestHandler reqHandler = new RequestHandler(null, null); + // 閫氫俊瀵硅薄 + TenpayHttpClient httpClient = new TenpayHttpClient(); + // 搴旂瓟瀵硅薄 + ClientResponseHandler resHandler = new ClientResponseHandler(); + + // ----------------------------- + // 璁剧疆璇锋眰鍙傛暟 + // ----------------------------- + // reqHandler.init(); + reqHandler.setKey(key); + reqHandler.setGateUrl(FIRST_ORDER_URL);// 璇锋眰URL + + // ----------------------------- + // 璁剧疆鎺ュ彛鍙傛暟(sign鍚庡彴鑷姩鐢熸垚) + // ----------------------------- + reqHandler.setParameter("appid", appId); // 鍏紬鍙�/灏忕▼搴� + reqHandler.setParameter("mch_id", partner); // 鍟嗘埛鍙� + reqHandler.setParameter("nonce_str", SimpleTool.getUUIDName().substring(0, 30));// 闅忔満涔辩爜 + reqHandler.setParameter("body", body);// 鍟嗗搧鎻忚堪 + reqHandler.setParameter("out_trade_no", out_trade_no);// 鍟嗘埛璁㈠崟鍙� + reqHandler.setParameter("total_fee", total_fee);// 鎬婚噾棰� + reqHandler.setParameter("spbill_create_ip", "8.8.8.8");// 缁堢IP + reqHandler.setParameter("notify_url",notifyUrl);// 閫氱煡鍦板潃 + reqHandler.setParameter("trade_type", trade_type);// 浜ゆ槗绫诲瀷 + // JSAPI锛孨ATIVE锛孉PP + reqHandler.setParameter("openid", openid);// openId + reqHandler.setParameter("attach", attach);// 闄勫甫鏁版嵁鍖� + + // ----------------------------- + // 璁剧疆閫氫俊鍙傛暟 + // ----------------------------- + // 璁剧疆璇锋眰杩斿洖鐨勭瓑寰呮椂闂� + httpClient.setTimeOut(5); + + // 璁剧疆ca璇佷功 + // httpClient.setCaInfo(new File(CA_PATH)); + + // 璁剧疆涓汉(鍟嗘埛)璇佷功 + // httpClient.setCertInfo(new File(CERT_PATH), CERT_PWD); + + // 璁剧疆鍙戦�佺被鍨婸OST + httpClient.setMethod("POST"); + + // 璁剧疆璇锋眰鍐呭(鐢熸垚sign) + String requestUrl = reqHandler.getRequestURL();// 缁勬嫾https://www.baidu.com?a=x&b=xx + + httpClient.setReqContent(requestUrl);// https://www.baidu.com?a=x&b=xx + String rescontent = "null"; + + httpClient.setRequestHandler(reqHandler);// 鎶婂鐞嗗璞★紝鍍忔槸鍙傛暟鍚勭涓滆タ閮借缃繘鍘绘柟渚胯幏鍙�(quan) + + // 杩斿洖鍑哄幓鐨勫璞�(鐘舵�侊紝閿欒鍘熷洜锛岃鎿嶄綔鐩稿叧淇℃伅(鍙傛暟,杩斿洖鍊�)) + JSONObject returnObj = new JSONObject(); + + // 鍚庡彴璋冪敤 + if (httpClient.call()) { + System.out.println("缁熶竴涓嬪崟,鎴愬姛cll浜�::"); + + // 璁剧疆缁撴灉鍙傛暟 + rescontent = httpClient.getResContent(); + System.out.println("缁熶竴涓嬪崟杩斿洖缁撴灉:" + rescontent); + resHandler.setContent(rescontent);// 瑙f瀽xml + resHandler.setKey(key); + + // 鑾峰彇杩斿洖鍙傛暟 + String return_code = resHandler.getParameter("return_code"); + String return_msg = resHandler.getParameter("return_msg"); + + // 鍒ゆ柇绛惧悕鍙婄粨鏋� + if (resHandler.isTenpaySign() && "SUCCESS".equals(return_code)) { + String prepay_id = resHandler.getParameter("prepay_id");// 棰勬敮浠樹氦鏄撲細璇濇爣璇� + String code_url = resHandler.getParameter("code_url");// 浜岀淮鐮侀摼鎺� + + String result_code = resHandler.getParameter("result_code");// 涓氬姟缁撴灉 + String appid = resHandler.getParameter("appid");// 鍏紬璐﹀彿ID + String mch_id = resHandler.getParameter("mch_id");// 鍟嗘埛鍙� + String nonce_str = resHandler.getParameter("nonce_str");// 闅忔満鐮� + String sign = resHandler.getParameter("sign");// 绛惧悕 + + if (result_code.equals("SUCCESS")) { + returnObj.put("status", "suc"); + returnObj.put("sign", sign); + returnObj.put("nonce_str", nonce_str); + returnObj.put("mch_id", mch_id); + returnObj.put("appid", appid); + returnObj.put("prepay_id", prepay_id); + returnObj.put("code_url", code_url); + returnObj.put("out_trade_no", out_trade_no); + } else { + String errMsg = "[ERROR]result_code:" + resHandler.getParameter("result_code") + " err_code:" + + resHandler.getParameter("err_code") + "err_code_des:" + + resHandler.getParameter("err_code_des"); + + // 閿欒鏃讹紝杩斿洖缁撴灉鏈鍚嶏紝璁板綍retcode銆乺etmsg鐪嬪け璐ヨ鎯呫�� + returnObj.put("status", "ERROR-C"); + returnObj.put("errMsg", errMsg); + } + } else { + String errMsg = "return_code:" + return_code + "err_code:" + resHandler.getParameter("err_code") + + " return_msg:" + return_msg; + // 閿欒鏃讹紝杩斿洖缁撴灉鏈鍚嶏紝璁板綍retcode銆乺etmsg鐪嬪け璐ヨ鎯呫�� + returnObj.put("status", "ERROR-B"); + returnObj.put("errMsg", errMsg); + } + } else { + // 鏈夊彲鑳藉洜涓虹綉缁滃師鍥狅紝璇锋眰宸茬粡澶勭悊锛屼絾鏈敹鍒板簲绛斻�� + returnObj.put("status", "ERROR-A"); + returnObj.put("errMsg", httpClient.getResponseCode() + ":" + httpClient.getErrInfo()); + } + + // 鑾峰彇debug淇℃伅,寤鸿鎶婅姹傘�佸簲绛斿唴瀹广�乨ebug淇℃伅锛岄�氫俊杩斿洖鐮佸啓鍏ユ棩蹇楋紝鏂逛究瀹氫綅闂 + String detail = "http res:" + httpClient.getResponseCode() + "," + httpClient.getErrInfo() + ";" + "req url:" + + requestUrl + ";" + ";" + "req debug:" + reqHandler.getDebugInfo() + ";" + "res content:" + rescontent + + ";" + "res debug:" + resHandler.getDebugInfo() + ";"; + + returnObj.put("detail", detail); + + + return returnObj; + } + + /**缁熶竴鏀粯锛堝垎璐︼級 + * @param request 鏂规硶鑾峰彇 + * @param appId 灏忕▼搴忓彿 + * @param partner 鍟嗘埛鍙� + * @param key 绉橀挜 + * @param notifyUrl 鍥炶皟閾炬帴 + * @param out_trade_no 璁㈠崟鍙� + * @param body 鍟嗗搧鎻忚堪 + * @param total_fee 鏀粯閲戦 + * @param openid 鐢ㄦ埛openId + * @param attach 闄勫甫鏁版嵁鍖� + * @param notifyUrl 鍥炶皟閫氱煡鍦板潃 + * @param trade_type 浜ゆ槗绫诲瀷 + * @param profit_sharing 鏄惁鍒嗚处锛歂涓嶏紝Y鏄� + * @return JSON status = "SUC"涓烘垚鍔� + */ + public static JSONObject unifiedPay(HttpServletRequest request,String appId,String partner,String key,String notifyUrl,String out_trade_no, String body, String total_fee, String openid, + String attach,String trade_type,String profit_sharing) throws Exception { + + if (!SimpleTool.checkNotNull(notifyUrl)) { + throw new ServiceException("鏀粯鍔熻兘鏁呴殰锛�"); + } + + // 鍒涘缓鏌ヨ璇锋眰瀵硅薄 + RequestHandler reqHandler = new RequestHandler(null, null); + // 閫氫俊瀵硅薄 + TenpayHttpClient httpClient = new TenpayHttpClient(); + // 搴旂瓟瀵硅薄 + ClientResponseHandler resHandler = new ClientResponseHandler(); + + // ----------------------------- + // 璁剧疆璇锋眰鍙傛暟 + // ----------------------------- + // reqHandler.init(); + reqHandler.setKey(key); + reqHandler.setGateUrl(FIRST_ORDER_URL);// 璇锋眰URL + + // ----------------------------- + // 璁剧疆鎺ュ彛鍙傛暟(sign鍚庡彴鑷姩鐢熸垚) + // ----------------------------- + + reqHandler.setParameter("appid", appId); // 鍏紬鍙�/灏忕▼搴� + reqHandler.setParameter("mch_id", partner); // 鍟嗘埛鍙� + reqHandler.setParameter("nonce_str", SimpleTool.getUUIDName().substring(0, 30));// 闅忔満涔辩爜 + reqHandler.setParameter("body", body);// 鍟嗗搧鎻忚堪 + reqHandler.setParameter("out_trade_no", out_trade_no);// 鍟嗘埛璁㈠崟鍙� + reqHandler.setParameter("total_fee", total_fee);// 鎬婚噾棰� + reqHandler.setParameter("spbill_create_ip", "8.8.8.8");// 缁堢IP + reqHandler.setParameter("notify_url",notifyUrl);// 閫氱煡鍦板潃 + reqHandler.setParameter("trade_type", trade_type);// 浜ゆ槗绫诲瀷 + //JSAPI锛孨ATIVE锛孉PP + reqHandler.setParameter("openid", openid);// openId + reqHandler.setParameter("attach", attach);// 闄勫甫鏁版嵁鍖� + reqHandler.setParameter("profit_sharing", profit_sharing);// 闄勫甫鏁版嵁鍖� + + // ----------------------------- + // 璁剧疆閫氫俊鍙傛暟 + // ----------------------------- + // 璁剧疆璇锋眰杩斿洖鐨勭瓑寰呮椂闂� + httpClient.setTimeOut(5); + + // 璁剧疆ca璇佷功 + // httpClient.setCaInfo(new File(CA_PATH)); + + // 璁剧疆涓汉(鍟嗘埛)璇佷功 + // httpClient.setCertInfo(new File(CERT_PATH), CERT_PWD); + + // 璁剧疆鍙戦�佺被鍨婸OST + httpClient.setMethod("POST"); + + // 璁剧疆璇锋眰鍐呭(鐢熸垚sign) + String requestUrl = reqHandler.getRequestURL();// 缁勬嫾https://www.baidu.com?a=x&b=xx + + httpClient.setReqContent(requestUrl);// https://www.baidu.com?a=x&b=xx + String rescontent = "null"; + + httpClient.setRequestHandler(reqHandler);// 鎶婂鐞嗗璞★紝鍍忔槸鍙傛暟鍚勭涓滆タ閮借缃繘鍘绘柟渚胯幏鍙�(quan) + + // 杩斿洖鍑哄幓鐨勫璞�(鐘舵�侊紝閿欒鍘熷洜锛岃鎿嶄綔鐩稿叧淇℃伅(鍙傛暟,杩斿洖鍊�)) + JSONObject returnObj = new JSONObject(); + + // 鍚庡彴璋冪敤 + if (httpClient.call()) { + System.out.println("缁熶竴涓嬪崟,鎴愬姛cll浜�::"); + + // 璁剧疆缁撴灉鍙傛暟 + rescontent = httpClient.getResContent(); + System.out.println("缁熶竴涓嬪崟杩斿洖缁撴灉:" + rescontent); + resHandler.setContent(rescontent);// 瑙f瀽xml + resHandler.setKey(key); + + // 鑾峰彇杩斿洖鍙傛暟 + String return_code = resHandler.getParameter("return_code"); + String return_msg = resHandler.getParameter("return_msg"); + + // 鍒ゆ柇绛惧悕鍙婄粨鏋� + if (resHandler.isTenpaySign() && "SUCCESS".equals(return_code)) { + String prepay_id = resHandler.getParameter("prepay_id");// 棰勬敮浠樹氦鏄撲細璇濇爣璇� + String code_url = resHandler.getParameter("code_url");// 浜岀淮鐮侀摼鎺� + + String result_code = resHandler.getParameter("result_code");// 涓氬姟缁撴灉 + String appid = resHandler.getParameter("appid");// 鍏紬璐﹀彿ID + String mch_id = resHandler.getParameter("mch_id");// 鍟嗘埛鍙� + String nonce_str = resHandler.getParameter("nonce_str");// 闅忔満鐮� + String sign = resHandler.getParameter("sign");// 绛惧悕 + + if (result_code.equals("SUCCESS")) { + returnObj.put("status", "suc"); + returnObj.put("sign", sign); + returnObj.put("nonce_str", nonce_str); + returnObj.put("mch_id", mch_id); + returnObj.put("appid", appid); + returnObj.put("prepay_id", prepay_id); + returnObj.put("code_url", code_url); + returnObj.put("out_trade_no", out_trade_no); + } else { + String errMsg = "[ERROR]result_code:" + resHandler.getParameter("result_code") + " err_code:" + + resHandler.getParameter("err_code") + "err_code_des:" + + resHandler.getParameter("err_code_des"); + + // 閿欒鏃讹紝杩斿洖缁撴灉鏈鍚嶏紝璁板綍retcode銆乺etmsg鐪嬪け璐ヨ鎯呫�� + returnObj.put("status", "ERROR-C"); + returnObj.put("errMsg", errMsg); + } + } else { + String errMsg = "return_code:" + return_code + "err_code:" + resHandler.getParameter("err_code") + + " return_msg:" + return_msg; + // 閿欒鏃讹紝杩斿洖缁撴灉鏈鍚嶏紝璁板綍retcode銆乺etmsg鐪嬪け璐ヨ鎯呫�� + returnObj.put("status", "ERROR-B"); + returnObj.put("errMsg", errMsg); + } + } else { + // 鏈夊彲鑳藉洜涓虹綉缁滃師鍥狅紝璇锋眰宸茬粡澶勭悊锛屼絾鏈敹鍒板簲绛斻�� + returnObj.put("status", "ERROR-A"); + returnObj.put("errMsg", httpClient.getResponseCode() + ":" + httpClient.getErrInfo()); + } + + // 鑾峰彇debug淇℃伅,寤鸿鎶婅姹傘�佸簲绛斿唴瀹广�乨ebug淇℃伅锛岄�氫俊杩斿洖鐮佸啓鍏ユ棩蹇楋紝鏂逛究瀹氫綅闂 + String detail = "http res:" + httpClient.getResponseCode() + "," + httpClient.getErrInfo() + ";" + "req url:" + + requestUrl + ";" + ";" + "req debug:" + reqHandler.getDebugInfo() + ";" + "res content:" + rescontent + + ";" + "res debug:" + resHandler.getDebugInfo() + ";"; + + returnObj.put("detail", detail); + + + return returnObj; + } + + /**澶勭悊淇℃伅 + */ + public static JSONObject paymentData(JSONObject payObj,String key){ + JSONObject wxObj = new JSONObject(); + /**缁熶竴涓嬪崟*/ + String payStatus = payObj.getString("status"); + if (payStatus.equals("suc")) { + // JSONObject payObj = po.getJSONObject("inf"); + String appId = payObj.getString("appid"); + String nonceStr = payObj.getString("nonce_str"); + String prepay_id = payObj.getString("prepay_id"); + // JSAPI璋冪敤鏀粯杩斿洖鐨勬暟鎹� + String timeStamp = SimpleTool.getTenTime(new Date()).toString(); + String signType = "MD5"; + String packagef = "prepay_id=" + prepay_id; + RequestHandler reqHandler = new RequestHandler(null, null); + reqHandler.setParameter("appId", appId); + reqHandler.setParameter("nonceStr", nonceStr); + reqHandler.setParameter("timeStamp", timeStamp); + reqHandler.setParameter("package", packagef); + reqHandler.setParameter("signType", signType); + reqHandler.setKey(key); + String paySign = reqHandler.createSign();// 鐢熸垚绛惧悕 + wxObj.put("orderNo", payObj.getString("out_trade_no")); + wxObj.put("paySign", paySign); + wxObj.put("appId", appId); + wxObj.put("nonceStr", nonceStr); + wxObj.put("package", packagef); + wxObj.put("timeStamp", timeStamp); + } else { + throw new RuntimeException(payObj.toString()); + } + return wxObj; + } + + /** + * 閫�娆� + * @param appId 灏忕▼搴�/鍏紬鍙� appId + * @param partner 鍟嗘埛鍙� + * @param key 鍟嗘埛鍙风閽� + * @param certPath 涓汉鍟嗘埛璇佷功 + * @param out_trade_no 鍟嗘埛璁㈠崟鍙� + * @param transaction_id 璐粯閫氳鍗曞彿锛堝井淇¤鍗曞彿锛� + * @param out_refund_no 鍟嗘埛閫�鍗曞彿 + * @param total_fee 璁㈠崟鎬婚(鍗曚綅:鍒�) + * @param refund_fee 閫�娆鹃噾棰�(鍗曚綅:鍒�) + * @return JSON status="SUCCESS"(鎴愬姛) (鐘舵�侊紝閿欒鍘熷洜锛岃鎿嶄綔鐩稿叧淇℃伅(鍙傛暟,杩斿洖鍊�)) + */ + public static JSONObject refund(String appId,String partner,String key,String certPath,String out_trade_no, String transaction_id, String out_refund_no, String total_fee, + String refund_fee) { + try{ + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + FileInputStream instream = new FileInputStream(new File(certPath)); + try { + keyStore.load(instream,partner.toCharArray()); + }finally { + instream.close(); + } + // Trust own CA and all self-signed certs + SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore,partner.toCharArray()).build(); + // Allow TLSv1 protocol only + SSLConnectionSocketFactory sslsf; + sslsf = new SSLConnectionSocketFactory( + sslcontext, new String[] { "TLSv1" }, null, + SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + CloseableHttpClient httpclient = HttpClients.custom() + .setSSLSocketFactory(sslsf).build(); + HttpPost httppost = new HttpPost(REFUND_URL); + String xml = wxPayRefundData(appId, partner, key, out_trade_no, transaction_id, out_refund_no, total_fee, refund_fee); + try { + StringEntity se = new StringEntity(xml); + httppost.setEntity(se); + + CloseableHttpResponse responseEntry = httpclient.execute(httppost); + try { + HttpEntity entity = responseEntry.getEntity(); + if (entity != null) { + + SAXReader saxReader = new SAXReader(); + Document document = saxReader.read(entity.getContent()); + Element rootElt = document.getRootElement(); + String returnCode = rootElt.elementText("return_code"); + JSONObject result = new JSONObject(); + + if(returnCode.equals("SUCCESS")){ + String resultCode = rootElt.elementText("result_code"); + if(resultCode.equals("SUCCESS")) { + result.put("weixinPayUrl", rootElt.elementText("code_url")); + result.put("prepayId", rootElt.elementText("prepay_id")); + result.put("msg", "success"); + + String refund_id = rootElt.elementText("refund_id");//寰俊閫�娆惧崟鍙� + String r_out_refund_no = rootElt.elementText("out_refund_no"); + String errMsg = "鍟嗘埛鍙�" + r_out_refund_no + "鐨勯��娆炬祦姘村彿鏄細" + refund_id; + result.put("status", "SUCCESS"); + result.put("errMsg", errMsg); + result.put("refund_id", refund_id); + }else{ + String errMsg = "[ERROR]result_code:" + rootElt.elementText("result_code")+ + " err_code:" + rootElt.elementText("err_code"); + + //閿欒鏃讹紝杩斿洖缁撴灉鏈鍚嶏紝璁板綍retcode銆乺etmsg鐪嬪け璐ヨ鎯呫�� + result.put("errMsg", errMsg); + result.put("status","false"); + result.put("msg",rootElt.elementText("err_code_des")); + } + }else{ + String errMsg = "[ERROR]return_code:" + rootElt.elementText("return_code"); + + //閿欒鏃讹紝杩斿洖缁撴灉鏈鍚嶏紝璁板綍retcode銆乺etmsg鐪嬪け璐ヨ鎯呫�� + result.put("errMsg", errMsg); + result.put("status","false"); + result.put("msg",rootElt.elementText("return_msg")); + } + return result; + } + EntityUtils.consume(entity); + } + finally { + responseEntry.close(); + } + } + finally { + httpclient.close(); + } + return null; + }catch(Exception e){ + e.printStackTrace(); + JSONObject result = new JSONObject(); + result.put("status","error"); + result.put("msg",e.getMessage()); + return result; + } + } + + /** 灏佽鍙傛暟鏁版嵁 + * @param appId 灏忕▼搴�/鍏紬鍙� appId + * @param partner 鍟嗘埛鍙� + * @param key 鍟嗘埛鍙风閽� + * @param out_trade_no 鍟嗘埛璁㈠崟鍙� + * @param transaction_id 璐粯閫氳鍗曞彿锛堝井淇¤鍗曞彿锛� + * @param out_refund_no 鍟嗘埛閫�鍗曞彿 + * @param total_fee 璁㈠崟鎬婚(鍗曚綅:鍒�) + * @param refund_fee 閫�娆鹃噾棰�(鍗曚綅:鍒�) + * @return + */ + public static String wxPayRefundData(String appId,String partner,String key,String out_trade_no, String transaction_id,String out_refund_no,String total_fee,String refund_fee) { + StringBuffer xml = new StringBuffer(); + String data = null; + try { + String nonceStr = SimpleTool.getUUIDName().substring(0,30); + xml.append("</xml>"); + SortedMap<String,String> parameters = new TreeMap<String,String>(); + parameters.put("appid",appId); + parameters.put("mch_id",partner); + parameters.put("nonce_str", nonceStr); + if(!StringUtils.isEmpty(out_trade_no)) { + parameters.put("out_trade_no", out_trade_no); + } + if(!StringUtils.isEmpty(transaction_id)) { + parameters.put("transaction_id", transaction_id); + } + parameters.put("out_refund_no", out_refund_no); + parameters.put("fee_type", "CNY"); + parameters.put("total_fee", total_fee);//鎬婚噾棰� + parameters.put("refund_fee", refund_fee);//閫�娆鹃噾棰� + parameters.put("op_user_id",partner); + parameters.put("sign", createSign(parameters,key)); + + data =SortedMaptoXml(parameters); + } catch (Exception e) { + System.err.println(e.getMessage()); + return null; + } + return data; + } + + /** + * 鍒涘缓md5鎽樿,瑙勫垯鏄�:鎸夊弬鏁板悕绉癮-z鎺掑簭,閬囧埌绌哄�肩殑鍙傛暟涓嶅弬鍔犵鍚嶃�� + */ + public static String createSign(SortedMap<String, String> packageParams, String AppKey) { + StringBuffer sb; + sb = new StringBuffer(); + Set es = packageParams.entrySet(); + Iterator it = es.iterator(); + while (it.hasNext()) { + Map.Entry entry = (Map.Entry) it.next(); + String k = (String) entry.getKey(); + String v = (String) entry.getValue(); + if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) { + sb.append(k + "=" + v + "&"); + } + } + sb.append("key=" + AppKey); + String sign = MD5Util.MD5Encode(sb.toString(), "UTF-8").toUpperCase(); + return sign; + } + + /** + * @Author: HONGLINCHEN + * @Description:璇锋眰鍊艰浆鎹负xml鏍煎紡 SortedMap杞瑇ml + * @param params + * @Date: 2017-9-7 17:18 + */ + private static String SortedMaptoXml(SortedMap<String,String> params) { + StringBuilder sb = new StringBuilder(); + Set es = params.entrySet(); + Iterator it = es.iterator(); + sb.append("<xml>\n"); + while(it.hasNext()) { + Map.Entry entry = (Map.Entry)it.next(); + String k = (String)entry.getKey(); + Object v = entry.getValue(); + sb.append("<"+k+">"); + sb.append(v); + sb.append("</"+k+">\n"); + } + sb.append("</xml>"); + return sb.toString(); + } +} diff --git a/hx_common/src/main/java/com/hx/encryption/PTConstant.java b/hx_common/src/main/java/com/hx/encryption/PTConstant.java new file mode 100644 index 0000000..9394fd2 --- /dev/null +++ b/hx_common/src/main/java/com/hx/encryption/PTConstant.java @@ -0,0 +1,34 @@ +package com.hx.encryption; + +/** + * 鎺ュ彛瑙e瘑杩斿洖缁撴灉閰嶇疆 + * @author wangrenhuang + * @Data 2020-06-09 + */ +public class PTConstant { + + public static String PT_SIGN_EEMPLY = "绛惧悕涓虹┖锛�"; + public static String PT_TIMELS_EMPLY = "鏃堕棿涓虹┖锛�"; + public static String PT_SIGN_ERROR = "绛惧悕閿欒"; + public static String PT_ORER_TIME = "鎺ュ彛瓒呮椂"; + + + private boolean success; + private String errCode; + + + /*************************************************************************/ + + public boolean isSuccess() { + return success; + } + public void setSuccess(boolean success) { + this.success = success; + } + public String getErrCode() { + return errCode; + } + public void setErrCode(String errCode) { + this.errCode = errCode; + } +} diff --git a/hx_common/src/main/java/com/hx/encryption/PTEncryptionUtil.java b/hx_common/src/main/java/com/hx/encryption/PTEncryptionUtil.java new file mode 100644 index 0000000..8d15e1f --- /dev/null +++ b/hx_common/src/main/java/com/hx/encryption/PTEncryptionUtil.java @@ -0,0 +1,76 @@ +package com.hx.encryption; + +import com.hx.util.DateUtil; +import com.hx.util.MD5Util; +import com.hx.util.StringUtils; + +import java.util.Calendar; +import java.util.Date; + +/* + * @Description: his鍔╂墜璋冪敤 phitab 璁㈠崟鍔犲瘑宸ュ叿 + * @Author: wangrenhuang + * @Date: 2022/2/15-11:20 + */ +public class PTEncryptionUtil { + + + /* + * 鏃ユ湡鍔犲瘑 + * date 瑕佸姞瀵嗙殑鏃ユ湡 + * */ + public static String encryption(Date date){ + Calendar cal=Calendar.getInstance(); + cal.setTime(date); + StringBuffer data = new StringBuffer(); + data.append(cal.get(Calendar.DATE)); + data.append(cal.get(Calendar.MONTH)); + data.append(cal.get(Calendar.YEAR)); + data.append(cal.get(Calendar.SECOND)); + data.append(cal.get(Calendar.MINUTE)); + data.append(cal.get(Calendar.HOUR_OF_DAY)); + + return com.hx.mp.util.MD5Util.MD5Encode(data.toString(),""); + } + + /** + * + * @param data 绛惧悕 + * @param date 鏃堕棿 + * @param time 鏈夋晥鏃堕棿 绉� + * @return + */ + public static PTConstant decode(String data,Date date,Integer time){ + PTConstant ptConstant = new PTConstant(); + ptConstant.setSuccess(true); + if (StringUtils.isEmpty(data)){ + ptConstant.setSuccess(false); + ptConstant.setErrCode(PTConstant.PT_SIGN_EEMPLY); + return ptConstant; + } + if (null == date){ + ptConstant.setSuccess(false); + ptConstant.setErrCode(PTConstant.PT_TIMELS_EMPLY); + return ptConstant; + } + + if(!encryption(date).equals(data)){ + ptConstant.setSuccess(false); + ptConstant.setErrCode(PTConstant.PT_SIGN_ERROR); + return ptConstant; + } + if(time == null){ + ptConstant.setSuccess(true); + return ptConstant; + } + //鏈夋晥鏃堕棿鍒ゆ柇 + if (DateUtil.calLastedTime(date) > time){ + ptConstant.setSuccess(false); + ptConstant.setErrCode(PTConstant.PT_ORER_TIME); + return ptConstant; + } + + return ptConstant; + } + +} diff --git a/hx_common/src/main/java/com/hx/exception/LoginException.java b/hx_common/src/main/java/com/hx/exception/LoginException.java new file mode 100644 index 0000000..c5e6e18 --- /dev/null +++ b/hx_common/src/main/java/com/hx/exception/LoginException.java @@ -0,0 +1,35 @@ +package com.hx.exception; + +/** + * 鐧诲綍鎻愮ず寮傚父 + * @author ChenJiaHe + * @Date 2020-11-17 + */ +public class LoginException extends RuntimeException { + + private Integer code; + + public LoginException(String message) { + super(message); + } + + public LoginException(String message, Integer code) { + super(message); + this.code = code; + } + + public LoginException(String message, Throwable cause, Integer code) { + super(message, cause); + this.code = code; + } + + public LoginException(Throwable cause, Integer code) { + super(cause); + this.code = code; + } + + //@Override + public int getCode() { + return this.code; + } +} diff --git a/hx_common/src/main/java/com/hx/exception/ParamException.java b/hx_common/src/main/java/com/hx/exception/ParamException.java new file mode 100644 index 0000000..1aa3f39 --- /dev/null +++ b/hx_common/src/main/java/com/hx/exception/ParamException.java @@ -0,0 +1,12 @@ +package com.hx.exception; + +/** 鍙傛暟寮傚父 + * @author ChenJiaHe + * @Date 2020-06-19 + */ +public class ParamException extends RuntimeException { + + public ParamException(String message) { + super(message); + } +} diff --git a/hx_common/src/main/java/com/hx/exception/ServiceException.java b/hx_common/src/main/java/com/hx/exception/ServiceException.java new file mode 100644 index 0000000..eeeb4e8 --- /dev/null +++ b/hx_common/src/main/java/com/hx/exception/ServiceException.java @@ -0,0 +1,37 @@ +package com.hx.exception; + +/** 鍒ゆ柇寮傚父/涓氬姟寮傚父 + * @author ChenJiaHe + * @Date 2020-06-19 + */ +public class ServiceException extends RuntimeException { + + private Integer code; + + public ServiceException(String message) { + super(message); + } + + public ServiceException(String message, Integer code) { + super(message); + this.code = code; + } + + public ServiceException(String message, Throwable cause, Integer code) { + super(message, cause); + this.code = code; + } + + public ServiceException(Throwable cause, Integer code) { + super(cause); + this.code = code; + } + + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } +} diff --git a/hx_common/src/main/java/com/hx/exception/TipsException.java b/hx_common/src/main/java/com/hx/exception/TipsException.java new file mode 100644 index 0000000..b9a9b64 --- /dev/null +++ b/hx_common/src/main/java/com/hx/exception/TipsException.java @@ -0,0 +1,38 @@ +package com.hx.exception; + +/** + * 鍓嶇鎻愮ず寮傚父 + * @author ChenJiaHe + * @Date 2020-06-19 + */ +public class TipsException extends RuntimeException { + + private Integer code; + + public TipsException(String message) { + super(message); + } + + public TipsException(String message, Integer code) { + super(message); + this.code = code; + } + + public TipsException(String message, Throwable cause, Integer code) { + super(message, cause); + this.code = code; + } + + public TipsException(Throwable cause, Integer code) { + super(cause); + this.code = code; + } + + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } +} diff --git a/hx_common/src/main/java/com/hx/mp/util/CertUtil.java b/hx_common/src/main/java/com/hx/mp/util/CertUtil.java new file mode 100644 index 0000000..2483d1c --- /dev/null +++ b/hx_common/src/main/java/com/hx/mp/util/CertUtil.java @@ -0,0 +1,31 @@ +package com.hx.mp.util; + +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLContexts; + +import javax.net.ssl.SSLContext; +import java.io.File; +import java.io.FileInputStream; +import java.security.KeyStore; + +@SuppressWarnings("deprecation") +public class CertUtil { + /** + * 鍔犺浇璇佷功 + */ + public static SSLConnectionSocketFactory initCert(String certPath, String mchId) throws Exception { + FileInputStream instream = null; + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + instream = new FileInputStream(new File(certPath)); + keyStore.load(instream, mchId.toCharArray()); + + if (null != instream) { + instream.close(); + } + + SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore,mchId.toCharArray()).build(); + SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1"}, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); + + return sslsf; + } +} diff --git a/hx_common/src/main/java/com/hx/mp/util/ClientResponseHandler.java b/hx_common/src/main/java/com/hx/mp/util/ClientResponseHandler.java new file mode 100644 index 0000000..0d03f4a --- /dev/null +++ b/hx_common/src/main/java/com/hx/mp/util/ClientResponseHandler.java @@ -0,0 +1,228 @@ +package com.hx.mp.util; + +import org.jdom.JDOMException; + +import java.io.IOException; +import java.util.*; + +/** + * 锟斤拷台应锟斤拷锟斤拷<br/> + * ========================================================================<br/> + * api说锟斤拷锟斤拷<br/> + * getKey()/setKey(),锟斤拷取/锟斤拷锟斤拷锟斤拷钥<br/> + * getContent() / setContent(), 锟斤拷取/锟斤拷锟斤拷原始锟斤拷锟斤拷<br/> + * getParameter()/setParameter(),锟斤拷取/锟斤拷锟矫诧拷锟斤拷值<br/> + * getAllParameters(),锟斤拷取锟斤拷锟叫诧拷锟斤拷<br/> + * isTenpaySign(),锟角凤拷聘锟酵ㄇ╋拷锟�,true:锟斤拷 false:锟斤拷<br/> + * getDebugInfo(),锟斤拷取debug锟斤拷息<br/> + * + * ========================================================================<br/> + * + */ +public class ClientResponseHandler { + + /** 应锟斤拷原始锟斤拷锟斤拷 */ + private String content; + + /** 应锟斤拷牟锟斤拷锟� */ + @SuppressWarnings("rawtypes") + private SortedMap parameters; + + /** debug锟斤拷息 */ + private String debugInfo; + + /** 锟斤拷钥 */ + private String key; + + /** 锟街凤拷 */ + private String charset; + + /*@SuppressWarnings("rawtypes") + public ClientResponseHandler() { + this.content = ""; + this.parameters = new TreeMap(); + this.debugInfo = ""; + this.key = ""; + this.charset = "UTF-8"; + }*/ + + public ClientResponseHandler() { + this.content = ""; + this.parameters = new TreeMap(); + this.debugInfo = ""; + this.key = ""; + this.charset = "UTF-8"; + } + + public String getContent() { + return content; + } + + public void setContent(String content) throws Exception { + this.content = content; + + this.doParse(); + } + + /** + * 锟斤拷取锟斤拷锟斤拷值 + * + * @param parameter + * 锟斤拷锟斤拷锟斤拷锟� + * @return String + */ + public String getParameter(String parameter) { + String s = (String) this.parameters.get(parameter); + return (null == s) ? "" : s; + } + + /** + * 锟斤拷锟矫诧拷锟斤拷值 + * + * @param parameter + * 锟斤拷锟斤拷锟斤拷锟� + * @param parameterValue + * 锟斤拷锟斤拷值 + */ + @SuppressWarnings("unchecked") + public void setParameter(String parameter, String parameterValue) { + String v = ""; + if (null != parameterValue) { + v = parameterValue.trim(); + } + this.parameters.put(parameter, v); + } + + /** + * 锟斤拷锟斤拷锟斤拷锟叫的诧拷锟斤拷 + * + * @return SortedMap + */ + @SuppressWarnings("rawtypes") + public SortedMap getAllParameters() { + return this.parameters; + } + + public String getDebugInfo() { + return debugInfo; + } + + /** + * 锟斤拷取锟斤拷钥 + */ + public String getKey() { + return key; + } + + /** + * 锟斤拷锟斤拷锟斤拷钥 + */ + public void setKey(String key) { + this.key = key; + } + + public String getCharset() { + return this.charset; + } + + public void setCharset(String charset) { + this.charset = charset; + } + + /** + * 锟角凤拷聘锟酵ㄇ╋拷锟�,锟斤拷锟斤拷锟斤拷:锟斤拷锟斤拷锟斤拷锟斤拷锟絘-z锟斤拷锟斤拷,锟斤拷锟斤拷锟斤拷值锟侥诧拷锟斤拷渭锟角╋拷锟� + * + * @return boolean + */ + @SuppressWarnings("rawtypes") + public boolean isTenpaySign() { + StringBuffer sb = new StringBuffer(); + Set es = this.parameters.entrySet(); + Iterator it = es.iterator(); + while (it.hasNext()) { + Map.Entry entry = (Map.Entry) it.next(); + String k = (String) entry.getKey(); + String v = (String) entry.getValue(); + if (!"sign".equals(k) && null != v && !"".equals(v)) { + sb.append(k + "=" + v + "&"); + } + } + + sb.append("key=" + this.getKey()); + + System.out.println("杩斿洖鐨勫弬鏁�:" + sb); + // 锟斤拷锟秸� + String sign = MD5Util.MD5Encode(sb.toString(), this.charset) + .toUpperCase(); + + String tenpaySign = this.getParameter("sign").toUpperCase(); + + // debug锟斤拷息 + this.setDebugInfo(sb.toString() + " => sign:" + sign + " tenpaySign:" + + tenpaySign); + + Boolean b = tenpaySign.equals(sign); + + System.out.println("楠岃瘉杩斿洖鏉ョ殑鏁版嵁鏄惁寰俊杩斿洖鐨�:" + b); + + return b; + } + + /** + * 锟角凤拷聘锟酵ㄇ╋拷锟� + * + * @param signParameterArray + * 签锟斤拷牟锟斤拷锟斤拷锟斤拷锟� + * @return boolean + */ + protected boolean isTenpaySign(String signParameterArray[]) { + + StringBuffer signPars = new StringBuffer(); + for (int index = 0; index < signParameterArray.length; index++) { + String k = signParameterArray[index]; + String v = this.getParameter(k); + if (null != v && !"".equals(v)) { + signPars.append(k + "=" + v + "&"); + } + } + + signPars.append("key=" + this.getKey()); + + // 锟斤拷锟秸� + String sign = MD5Util.MD5Encode(signPars.toString(), this.charset) + .toLowerCase(); + + String tenpaySign = this.getParameter("sign").toLowerCase(); + + // debug锟斤拷息 + this.setDebugInfo(signPars.toString() + " => sign:" + sign + + " tenpaySign:" + tenpaySign); + + return tenpaySign.equals(sign); + } + + protected void setDebugInfo(String debugInfo) { + this.debugInfo = debugInfo; + } + + /** + * 锟斤拷锟斤拷XML锟斤拷锟斤拷 + */ + @SuppressWarnings("rawtypes") + protected void doParse() throws JDOMException, IOException, JDOMException { + String xmlContent = this.getContent(); + + // 锟斤拷锟斤拷xml,锟矫碉拷map + Map m = XMLUtil.doXMLParse(xmlContent); + + // 锟斤拷锟矫诧拷锟斤拷 + Iterator it = m.keySet().iterator(); + while (it.hasNext()) { + String k = (String) it.next(); + String v = (String) m.get(k); + this.setParameter(k, v); + } + + } + +} diff --git a/hx_common/src/main/java/com/hx/mp/util/CorpMpClientUtil.java b/hx_common/src/main/java/com/hx/mp/util/CorpMpClientUtil.java new file mode 100644 index 0000000..98c888b --- /dev/null +++ b/hx_common/src/main/java/com/hx/mp/util/CorpMpClientUtil.java @@ -0,0 +1,510 @@ +package com.hx.mp.util; + +import com.hx.util.StringUtils; +import com.hz.util.http.HttpHzUtil; +import com.hz.util.http.dto.HttpHzResponse; +import net.sf.json.JSONArray; +import net.sf.json.JSONException; +import net.sf.json.JSONObject; +import org.apache.commons.io.IOUtils; + +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.List; + +/** + * 浼佷笟寰俊瀹㈡埛宸ュ叿 + */ +public class CorpMpClientUtil { + + /** + * 鐢熸垚鑱旂郴鎴戞寜閽弬鏁扮殑閾炬帴锛堢敓鎴恈onfig_id锛� + */ + public static final String CREATE_CONTACT_ID_URL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_contact_way?access_token="; + /** + * 鑾峰彇浼佷笟瀹㈡埛璇︽儏閾炬帴 + */ + public static final String GET_CLIENT_DETAIL_URL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get"; + /** + * 鑾峰彇鑾峰彇浼佷笟鏍囩搴撻摼鎺� + */ + public static final String GET_CORP_TAG_LIST = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_corp_tag_list?access_token="; + /** + * 娣诲姞瀹㈡埛鑱旂郴浜烘爣绛� + */ + public static final String ADD_TAG = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_corp_tag?access_token="; + /** + * 缂栬緫浼佷笟瀹㈡埛鏍囩 + */ + public static final String EDIT_TAG = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/edit_corp_tag?access_token="; + /** + * 鍒犻櫎瀹㈡埛鑱旂郴浜烘爣绛� + */ + public static final String DEL_TAG = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/del_corp_tag?access_token="; + /** + * 瀹㈡埛鍏宠仈浼佷笟寰俊鐨勬爣绛緐rl + */ + public static final String RELATION_TAG = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/mark_tag?access_token="; + + /** + * 鑾峰彇鍛樺伐瀹㈡埛鍒楄〃url + */ + public static final String EXTERNAL_CONTACT_LIST = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/list"; + + /** + * 鍒涘缓鑾峰閾炬帴url + */ + public static final String CUSTOMER_ACQUISITION_CREATE_LINK = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/customer_acquisition/create_link?access_token="; + + /** + * 鑾峰彇鑾峰瀹㈡埛鍒楄〃 + */ + public static final String CUSTOMER_ACQUISITION_CUSTOMER_LIST = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/customer_acquisition/customer?access_token="; + + /** + * 鑾峰彇閰嶇疆杩囧鎴风兢绠$悊鐨勫鎴风兢鍒楄〃 + */ + public static final String GROUP_CHAT_LIST = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/list?access_token="; + + + /** + * 閫氳繃瀹㈡埛缇D锛岃幏鍙栬鎯呫�傚寘鎷兢鍚嶃�佺兢鎴愬憳鍒楄〃銆佺兢鎴愬憳鍏ョ兢鏃堕棿銆佸叆缇ゆ柟寮忋�傦紙瀹㈡埛缇ゆ槸鐢卞叿鏈夊鎴风兢浣跨敤鏉冮檺鐨勬垚鍛樺垱寤虹殑澶栭儴缇わ級 + */ + public static final String GROUP_CHAT_DETAIL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/get?access_token="; + + /** + * 浼佷笟寰俊鍙戦�佹櫘閫氶偖浠� + */ + public static final String GROUP_SENT_EMAIL = "https://qyapi.weixin.qq.com/cgi-bin/exmail/app/compose_send?access_token="; + + /** + * 瀹㈡埛缇ゃ�屽姞鍏ョ兢鑱娿�嶆煡鐪� + */ + public static final String GROUP_JOIN_WAY_SEE = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/get_join_way?access_token="; + /** + * 瀹㈡埛缇ゃ�屽姞鍏ョ兢鑱娿�嶆柊澧� + * 浼佷笟鍙皟鐢ㄦ鎺ュ彛鏉ョ敓鎴愬苟閰嶇疆銆屽姞鍏ョ兢鑱娿�嶇殑浜岀淮鐮佹垨鑰呭皬绋嬪簭鎸夐挳 + * 瀹㈡埛閫氳繃鎵弿浜岀淮鐮佹垨鐐瑰嚮灏忕▼搴忎笂鐨勬寜閽紝鍗冲彲鍔犲叆鐗瑰畾鐨勫鎴风兢 + */ + public static final String GROUP_JOIN_WAY_ADD = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/add_join_way?access_token="; + /** + * 瀹㈡埛缇ゃ�屽姞鍏ョ兢鑱娿�嶄慨鏀� + */ + public static final String GROUP_JOIN_WAY_EDIT = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/update_join_way?access_token="; + /** + * 瀹㈡埛缇ゃ�屽姞鍏ョ兢鑱娿�嶅垹闄� + */ + public static final String GROUP_JOIN_WAY_EDL= "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/del_join_way?access_token="; + + + /** + * 鐢熸垚浼佷笟鎴愬憳鑱旂郴鎴戠殑id-鍗曚汉 + * + * @param accessToken 浼佷笟鐨刟ccessToken + * @param userId 浼佷笟鎴愬憳鐨剈serId + * @param state 浼佷笟鑷畾涔夌殑state鍙傛暟锛岀敤浜庡尯鍒嗕笉鍚岀殑娣诲姞娓犻亾锛屽湪璋冪敤鈥滆幏鍙栧閮ㄨ仈绯讳汉璇︽儏鈥濇椂浼氳繑鍥炶鍙傛暟鍊硷紝涓嶈秴杩�30涓瓧绗� + * @param remark 鑱旂郴鏂瑰紡鐨勫娉ㄤ俊鎭紝鐢ㄤ簬鍔╄锛屼笉瓒呰繃30涓瓧绗� + * @return 杩斿洖 + */ + public static JSONObject createContactId(String accessToken, String userId, String state, String remark) { + + String configId = null; + JSONObject data = new JSONObject(); + data.put("type", 1); + data.put("scene", 1); + data.put("state", state); + data.put("remark", remark); + JSONArray userIds = new JSONArray(); + userIds.add(userId); + data.put("user", userIds); + + //璇锋眰锛岃繑鍥炴牸寮� + /*{ + "errcode": 0, + "errmsg": "ok", + "config_id":"42b34949e138eb6e027c123cba77fAAA"銆�銆� + }*/ + + return HttpURLUtil(CREATE_CONTACT_ID_URL + accessToken, data.toString()); + } + + /** + * 鑾峰彇瀹㈡埛鍒楄〃 + * @param accessToken 浼佷笟鐨刟ccessToken + * @param userId 浼佷笟鎴愬憳鐨剈serId + * @return 杩斿洖 + */ + public static JSONObject getExternalContactList(String accessToken, String userId) { + return HttpURLUtil(EXTERNAL_CONTACT_LIST + "?access_token=" + accessToken + "&userid=" + userId, null); + } + + /** + * 鑾峰彇浼佷笟瀹㈡埛璇︽儏淇℃伅 + * + * @param accessToken 浼佷笟鐨刟ccessToken + * @param externalUserId 澶栭儴浜哄憳鐨剈serId + * @return 杩斿洖 + */ + public static JSONObject getClientData(String accessToken, String externalUserId) { + return HttpURLUtil(GET_CLIENT_DETAIL_URL + "?access_token=" + accessToken + "&external_userid=" + externalUserId, null); + } + + /** + * 浼佷笟鍙�氳繃姝ゆ帴鍙h幏鍙栦紒涓氬鎴锋爣绛捐鎯� + * + * @param accessToken 浼佷笟鐨刟ccessToken + * @param tagId 鏍囩id + * @param groupId 鏍囩缁刬d + * @return 杩斿洖 + */ + public static JSONObject getCorpTagList(String accessToken, JSONArray tagId, JSONArray groupId) { + JSONObject data = new JSONObject(); + data.put("tag_id", tagId); + data.put("group_id", groupId); + return HttpURLUtil(GET_CORP_TAG_LIST + accessToken, data.toString()); + } + + /** + * 娣诲姞瀹㈡埛鑱旂郴浜烘爣绛撅紝 + * 濡傛灉瑕佸悜鎸囧畾鐨勬爣绛剧粍涓嬫坊鍔犳爣绛撅紝闇�瑕佸~鍐檊roup_id鍙傛暟锛涘鏋滆鍒涘缓涓�涓叏鏂扮殑鏍囩缁勪互鍙婃爣绛撅紝 + * 鍒欓渶瑕侀�氳繃group_name鍙傛暟鎸囧畾鏂版爣绛剧粍鍚嶇О锛屽鏋滃~鍐欑殑groupname宸茬粡瀛樺湪锛屽垯浼氬湪姝ゆ爣绛剧粍涓嬫柊寤烘爣绛� + * + * @param accessToken 浼佷笟鐨刟ccessToken + * @param groupId 缁刬d锛堢粍鍚嶇О鍜岀粍id蹇呭~涓�涓級 + * @param groupName 缁勫悕绉� 缁勫悕绉板拰缁刬d蹇呭~涓�涓級 + * @param groupOrder 缁勬帓搴忥紝涓嶅~榛樿浼佷笟寰俊鐢熸垚瑙勫垯 + * @param tagArray 鏁扮粍锛屾牸寮忥細[{ "name": "TAG_NAME_1", "order": 1 }] + * @return 杩斿洖 + */ + public static JSONObject addTable(String accessToken, String groupId, String groupName, String groupOrder, JSONArray tagArray) { + JSONObject data = new JSONObject(); + data.put("group_id", groupId); + data.put("group_name", groupName); + data.put("order", groupOrder); + data.put("tag", tagArray); + return HttpURLUtil(ADD_TAG + accessToken, data.toString()); + } + + /** + * 缂栬緫浼佷笟瀹㈡埛鏍囩锛� + * 娉ㄦ剰:淇敼鍚庣殑鏍囩缁勪笉鑳藉拰宸叉湁鐨勬爣绛剧粍閲嶅悕锛屾爣绛句篃涓嶈兘鍜屽悓涓�鏍囩缁勪笅鐨勫叾浠栨爣绛鹃噸鍚嶃�� + * + * @param accessToken 浼佷笟鐨刟ccessToken + * @param id 鏍囩鎴栨爣绛剧粍鐨刬d + * @param name 鏂扮殑鏍囩鎴栨爣绛剧粍鍚嶇О锛屾渶闀夸负30涓瓧绗� + * @param order 鏍囩/鏍囩缁勭殑娆″簭鍊笺�俹rder鍊煎ぇ鐨勬帓搴忛潬鍓嶃�傛湁鏁堢殑鍊艰寖鍥存槸[0, 2^32) + * @return 杩斿洖 + */ + public static JSONObject editTable(String accessToken, String id, String name, String order) { + JSONObject data = new JSONObject(); + data.put("id", id); + data.put("name", name); + data.put("order", order); + return HttpURLUtil(EDIT_TAG + accessToken, data.toString()); + } + + /** + * 鍒犻櫎瀹㈡埛鑱旂郴浜烘爣绛� + * groupArr鍜宼agArr涓嶅彲鍚屾椂涓虹┖銆� + * 濡傛灉涓�涓爣绛剧粍涓嬫墍鏈夌殑鏍囩鍧囪鍒犻櫎锛屽垯鏍囩缁勪細琚嚜鍔ㄥ垹闄ゃ�� + * + * @param accessToken 浼佷笟鐨刟ccessToken + * @param groupArr 缁刬d鏁扮粍 + * @param tagArr 鏍囩id鏁扮粍 + * @return 杩斿洖 + */ + public static JSONObject delTable(String accessToken, JSONArray groupArr, JSONArray tagArr) { + JSONObject data = new JSONObject(); + data.put("tag_id", tagArr); + data.put("group_id", groupArr); + return HttpURLUtil(DEL_TAG + accessToken, data.toString()); + } + + /** + * 瀹㈡埛鍏宠仈浼佷笟寰俊鐨勬爣绛� + * 娉ㄦ剰锛氳纭繚external_userid鏄痷serid鐨勫閮ㄨ仈绯讳汉銆� + * add_tag鍜宺emove_tag涓嶅彲鍚屾椂涓虹┖銆� + * + * @param accessToken 浼佷笟鐨刟ccessToken + * @param userId 浼佷笟鎴愬憳鐨剈serid + * @param externalUserId 澶栭儴鑱旂郴浜虹殑id + * @param addTag 鏂板鐨勬爣绛緄d锛堜紒涓氭爣绛剧殑id锛夋暟缁� + * @param removeTag 鍒犻櫎鐨勬爣绛緄d锛堜紒涓氭爣绛剧殑id锛夋暟缁� + * @return 杩斿洖 + */ + public static JSONObject relationTag(String accessToken, String userId, String externalUserId, JSONArray addTag, JSONArray removeTag) { + JSONObject data = new JSONObject(); + data.put("userid", userId); + data.put("external_userid", externalUserId); + data.put("add_tag", addTag); + data.put("remove_tag", removeTag); + return HttpURLUtil(RELATION_TAG + accessToken, data.toString()); + } + + /** + * 璇锋眰http鍗忚 鑾峰彇淇℃伅宸ュ叿 + **/ + public static JSONObject HttpURLUtil(String url, String data) { + HttpURLConnection con = null; + URL u = null; + String wxMsgXml = null; + JSONObject obj = null; + try { + u = new URL(url); + con = (HttpURLConnection) u.openConnection(); + con.setRequestMethod("POST"); + con.setDoOutput(true); + con.setDoInput(true); + con.setUseCaches(false); + con.setReadTimeout(5000); + con.setRequestProperty("Charset", "UTF-8"); + con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); + + if (data != null) { + OutputStream os = con.getOutputStream(); + os.write(data.getBytes("utf-8")); + } + + if (con.getResponseCode() != 200) + throw new RuntimeException("璇锋眰url澶辫触"); + // 璇诲彇杩斿洖鍐呭 + wxMsgXml = IOUtils.toString(con.getInputStream(), "utf-8"); + obj = JSONObject.fromObject(wxMsgXml); + // //System.out.println("HttpURLUtil:"+wxMsgXml); + } catch (Exception e) { + e.printStackTrace(); + obj = new JSONObject(); + try { + obj.put("status", 1); + obj.put("errMsg", e.getMessage()); + } catch (JSONException e1) { + e1.printStackTrace(); + } + } finally { + if (con != null) { + con.disconnect(); + } + } + return obj; + } + + /**鐢熸垚浼佷笟鎴愬憳鑱旂郴鎴戠殑id-鍗曚汉 + * @param accessToken 浼佷笟鐨刟ccessToken + * @param userId 浼佷笟鎴愬憳鐨剈serId + * @param scene 鍦烘櫙锛�1-鍦ㄥ皬绋嬪簭涓仈绯伙紝2-閫氳繃浜岀淮鐮佽仈绯� + * @param state 浼佷笟鑷畾涔夌殑state鍙傛暟锛岀敤浜庡尯鍒嗕笉鍚岀殑娣诲姞娓犻亾锛屽湪璋冪敤鈥滆幏鍙栧閮ㄨ仈绯讳汉璇︽儏鈥濇椂浼氳繑鍥炶鍙傛暟鍊硷紝涓嶈秴杩�30涓瓧绗� + * @param remark 鑱旂郴鏂瑰紡鐨勫娉ㄤ俊鎭紝鐢ㄤ簬鍔╄锛屼笉瓒呰繃30涓瓧绗� + * @return 杩斿洖 + */ + public static JSONObject createContactId(String accessToken,String userId,int scene,String state,String remark){ + String configId = null; + JSONObject data = new JSONObject(); + data.put("type",1); + data.put("scene",scene); + data.put("state",state); + data.put("remark",remark); + JSONArray userIds = new JSONArray(); + userIds.add(userId); + data.put("user",userIds); + + //璇锋眰锛岃繑鍥炴牸寮� + /*{ + "errcode": 0, + "errmsg": "ok", + "config_id":"42b34949e138eb6e027c123cba77fAAA"銆�銆� + }*/ + + return HttpURLUtil(CREATE_CONTACT_ID_URL+accessToken,data.toString()); + } + + /** + * 鍒涘缓鑾峰閾炬帴 + * + * @param accessToken 浼佷笟鐨刟ccessToken + * @param linkName 閾炬帴鍚嶇О + * @param userList 鍛樺伐鐢ㄦ埛userId + * @return 杩斿洖 + */ + public static JSONObject createCustomerAcquisitionLink(String accessToken, String linkName, JSONArray userList) { + JSONObject data = new JSONObject(); + data.put("link_name", linkName); + JSONObject subData = new JSONObject(); + subData.accumulate("user_list", userList); + data.put("range", subData); + /** 杩斿洖鏁版嵁 + * { + * "link_id":"LINK_ID", + * "link_name":"鑾峰閾炬帴1鍙�", + * "range": + * { + * "user_list":["zhangsan","lisi"], + * "department_list":[2,3] + * }, + * "skip_verify":true + * } + */ + return HttpURLUtil(CUSTOMER_ACQUISITION_CREATE_LINK + accessToken, data.toString()); + } + + /** + * 鑾峰彇鑾峰瀹㈡埛鍒楄〃 + * + * @param accessToken 浼佷笟鐨刟ccessToken + * @param linkId 閾炬帴id + * @param cursor 鍒嗛〉娓告爣 + * @return 杩斿洖 + */ + public static JSONObject getCustomerAcquisitionCustomerList(String accessToken, String linkId, String cursor) { + JSONObject data = new JSONObject(); + data.put("link_id", linkId); + data.put("limit", 1000); + // 鍒嗛〉娓告爣 + if (!StringUtils.isEmpty(cursor)) { + data.put("cursor", cursor); + } + /** 杩斿洖鏁版嵁 + * { + * "errcode": 0, + * "errmsg": "ok", + * "customer_list": + * [ + * { + * "external_userid":"woAJ2GCAAAXtWyujaWJHDDGi0mACAAA", + * "userid":"zhangsan", + * "chat_status":0, + * "state":"CHANNEL_A" + * } + * ], + * "next_cursor":"CURSOR" + * } + */ + return HttpURLUtil(CUSTOMER_ACQUISITION_CUSTOMER_LIST + accessToken, data.toString()); + } + + + /** + * 璇ユ帴鍙g敤浜庤幏鍙栭厤缃繃瀹㈡埛缇ょ鐞嗙殑瀹㈡埛缇ゅ垪琛ㄣ�� + * + * @param accessToken 浼佷笟鐨刟ccessToken + * @param statusFilter 瀹㈡埛缇よ窡杩涚姸鎬佽繃婊ゃ��0 - 鎵�鏈夊垪琛�(鍗充笉杩囨护) 1 - 绂昏亴寰呯户鎵� 2 - 绂昏亴缁ф壙涓� 3 - 绂昏亴缁ф壙瀹屾垚 + * @param userIdList 缇や富杩囨护 濡傛灉涓嶅~锛岃〃绀鸿幏鍙栧簲鐢ㄥ彲瑙佽寖鍥村唴鍏ㄩ儴缇や富鐨勬暟鎹彲瑙佽寖鍥翠汉鏁拌秴杩�1000浜猴紝涓轰簡闃叉鏁版嵁鍖呰繃澶э紝浼氭姤閿� 81017 鐢ㄦ埛ID鍒楄〃銆傛渶澶�100涓� + * @param cursor 鍒嗛〉涓嬫爣 + * @param limit 鍒楄〃 + * @return 杩斿洖 + */ + public static HttpHzResponse getGroupChatList(String accessToken, Integer statusFilter, List<String> userIdList, String cursor, Integer limit) { + JSONObject bodyData = new JSONObject(); + bodyData.put("status_filter", statusFilter); + //鍒嗛〉涓嬫爣 + if (StringUtils.noNull(cursor)) { + bodyData.put("cursor", cursor); + } + //榛樿100鏉� + if (limit == null) { + limit = 100; + } + bodyData.put("limit", limit); + //杩囨护 + if (userIdList != null && userIdList.size() > 0) { + JSONObject filter = new JSONObject(); + filter.put("userid_list", userIdList); + bodyData.put("owner_filter", filter); + } + return HttpHzUtil.HttpURLUtilJson(GROUP_CHAT_LIST + accessToken, bodyData.toString(), null, null, "GET", null); + } + + /** + * 閫氳繃瀹㈡埛缇D锛岃幏鍙栬鎯呫�傚寘鎷兢鍚嶃�佺兢鎴愬憳鍒楄〃銆佺兢鎴愬憳鍏ョ兢鏃堕棿銆佸叆缇ゆ柟寮忋�傦紙瀹㈡埛缇ゆ槸鐢卞叿鏈夊鎴风兢浣跨敤鏉冮檺鐨勬垚鍛樺垱寤虹殑澶栭儴缇わ級 + * + * @param chatId 瀹㈡埛缇D + * @param needName 鏄惁闇�瑕佽繑鍥炵兢鎴愬憳鐨勫悕瀛�0-涓嶈繑鍥烇紱1-杩斿洖 + */ + public static HttpHzResponse getGroupChatDetail(String accessToken, String chatId, Integer needName) { + JSONObject bodyData = new JSONObject(); + bodyData.put("chat_id", chatId); + if (needName == null) { + needName = 0; + } + bodyData.put("need_name", needName); + return HttpHzUtil.HttpURLUtilJson(GROUP_CHAT_DETAIL + accessToken, bodyData.toString(), null, null, "GET", null); + } + + /** + * 浼佷笟寰俊鍙戦�佹櫘閫氶偖浠� + * 鎺ュ彛鍦板潃: https://developer.work.weixin.qq.com/document/path/97445 + * @param bodyData 鍙傛暟 + */ + public static JSONObject sentEmail(String accessToken, JSONObject bodyData) { + return HttpURLUtil(GROUP_SENT_EMAIL + accessToken, bodyData.toString()); + } + + /** + * 瀹㈡埛缇ゃ�屽姞鍏ョ兢鑱娿�嶆煡鐪嬭鎯� + * @param config_id 鑱旂郴鏂瑰紡閰嶇疆ID + * */ + public static HttpHzResponse groupJoinSee(String accessToken, String config_id) { + JSONObject bodyData = new JSONObject(); + bodyData.put("config_id", config_id); + return HttpHzUtil.HttpURLUtilJson(GROUP_JOIN_WAY_SEE + accessToken, bodyData.toString(), null, null, "POST", null); + } + + /** + * 瀹㈡埛缇ゃ�屽姞鍏ョ兢鑱娿�嶆柊澧� + * @param scene 鍦烘櫙銆�1 - 缇ょ殑灏忕▼搴忔彃浠�, 2 - 缇ょ殑浜岀淮鐮佹彃浠� + * @param remark 鑱旂郴鏂瑰紡鐨勫娉ㄤ俊鎭紝鐢ㄤ簬鍔╄锛岃秴杩�30涓瓧绗﹀皢琚埅鏂� + * @param auto_create_room 褰撶兢婊′簡鍚庯紝鏄惁鑷姩鏂板缓缇ゃ��0-鍚︼紱1-鏄�� 榛樿涓�1 + * @param room_base_name 鑷姩寤虹兢鐨勭兢鍚嶅墠缂�锛屽綋auto_create_room涓�1鏃舵湁鏁堛�傛渶闀�40涓猽tf8瀛楃 + * @param room_base_id 鑷姩寤虹兢鐨勭兢璧峰搴忓彿锛屽綋auto_create_room涓�1鏃舵湁鏁� + * @param chat_id_list 浣跨敤璇ラ厤缃殑瀹㈡埛缇D鍒楄〃锛屾渶澶氭敮鎸�5涓� + * */ + public static HttpHzResponse groupJoinAdd(String accessToken, Integer scene, String remark + ,Integer auto_create_room,String room_base_name,Integer room_base_id,List<String> chat_id_list,String state) { + JSONObject bodyData = new JSONObject(); + bodyData.put("scene", scene); + bodyData.put("remark", remark); + bodyData.put("auto_create_room", auto_create_room); + bodyData.put("room_base_name", room_base_name); + bodyData.put("room_base_id", room_base_id); + bodyData.put("chat_id_list", chat_id_list); + bodyData.put("state", state); + return HttpHzUtil.HttpURLUtilJson(GROUP_JOIN_WAY_ADD + accessToken, bodyData.toString(), null, null, "POST", null); + } + + /** + * 瀹㈡埛缇ゃ�屽姞鍏ョ兢鑱娿�嶄慨鏀� + * @param config_id 鑱旂郴鏂瑰紡閰嶇疆ID + * @param scene 鍦烘櫙銆�1 - 缇ょ殑灏忕▼搴忔彃浠�, 2 - 缇ょ殑浜岀淮鐮佹彃浠� + * @param remark 鑱旂郴鏂瑰紡鐨勫娉ㄤ俊鎭紝鐢ㄤ簬鍔╄锛岃秴杩�30涓瓧绗﹀皢琚埅鏂� + * @param auto_create_room 褰撶兢婊′簡鍚庯紝鏄惁鑷姩鏂板缓缇ゃ��0-鍚︼紱1-鏄�� 榛樿涓�1 + * @param room_base_name 鑷姩寤虹兢鐨勭兢鍚嶅墠缂�锛屽綋auto_create_room涓�1鏃舵湁鏁堛�傛渶闀�40涓猽tf8瀛楃 + * @param room_base_id 鑷姩寤虹兢鐨勭兢璧峰搴忓彿锛屽綋auto_create_room涓�1鏃舵湁鏁� + * @param chat_id_list 浣跨敤璇ラ厤缃殑瀹㈡埛缇D鍒楄〃锛屾渶澶氭敮鎸�5涓� + * */ + public static HttpHzResponse groupJoinEdit(String accessToken,String config_id, Integer scene, String remark + ,Integer auto_create_room,String room_base_name,Integer room_base_id,List<String> chat_id_list,String state) { + JSONObject bodyData = new JSONObject(); + bodyData.put("config_id", config_id); + bodyData.put("scene", scene); + bodyData.put("remark", remark); + bodyData.put("auto_create_room", auto_create_room); + bodyData.put("room_base_name", room_base_name); + bodyData.put("room_base_id", room_base_id); + bodyData.put("chat_id_list", chat_id_list); + bodyData.put("state", state); + return HttpHzUtil.HttpURLUtilJson(GROUP_JOIN_WAY_EDIT + accessToken, bodyData.toString(), null, null, "POST", null); + } + + /** + * 瀹㈡埛缇ゃ�屽姞鍏ョ兢鑱娿�嶅垹闄� + * @param config_id 鑱旂郴鏂瑰紡閰嶇疆ID + * */ + public static HttpHzResponse groupJoinDel(String accessToken, String config_id) { + JSONObject bodyData = new JSONObject(); + bodyData.put("config_id", config_id); + return HttpHzUtil.HttpURLUtilJson(GROUP_JOIN_WAY_EDL + accessToken, bodyData.toString(), null, null, "POST", null); + } + + + +} diff --git a/hx_common/src/main/java/com/hx/mp/util/CorpMpSpaceUtil.java b/hx_common/src/main/java/com/hx/mp/util/CorpMpSpaceUtil.java new file mode 100644 index 0000000..22bb5c9 --- /dev/null +++ b/hx_common/src/main/java/com/hx/mp/util/CorpMpSpaceUtil.java @@ -0,0 +1,238 @@ +package com.hx.mp.util; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.hx.api.CorpMpSpaceApi; +import java.util.List; + +/** + * 浼佷笟寰俊寰洏鎺ュ彛API + * @Author: cmg + * @Date: 2023-7-13 11:08 + */ +public class CorpMpSpaceUtil { + + /** + * 澧炲姞绌洪棿 + * @param corpMpSpaceApi + * @param accessToken + * @param name 绌洪棿鍚嶇О + * @param depId 閮ㄩ棬id + * @param adminId 绠$悊鍛樼殑浼佷笟寰俊id + * @return + */ + public static JSONObject addSpace(CorpMpSpaceApi corpMpSpaceApi, String accessToken, String name, Integer depId, String adminId) + { + JSONObject obj = new JSONObject(); + obj.put("space_name", name); + JSONArray arr = new JSONArray(); + + //璁剧疆閮ㄩ棬鐨勫彲涓嬭浇鏉冮檺 + JSONObject temp = new JSONObject(); + temp.put("type", 2); + temp.put("departmentid", depId); + temp.put("auth", 1); + arr.add(temp); + + //璁剧疆绠$悊鍛� + temp = new JSONObject(); + temp.put("type", 1); + temp.put("userid", adminId); + temp.put("auth", 7); + arr.add(temp); + + obj.put("auth_info", arr); + + return corpMpSpaceApi.addSpace(accessToken, obj.toJSONString()); + } + + /** + * 绌洪棿閲嶅懡鍚� + * @param corpMpSpaceApi + * @param accessToken + * @param spaceId + * @param name + * @return + */ + public static JSONObject editSpaceName(CorpMpSpaceApi corpMpSpaceApi, String accessToken, String spaceId, String name) + { + JSONObject obj = new JSONObject(); + obj.put("space_name", name); + obj.put("spaceid", spaceId); + + return corpMpSpaceApi.renameSpace(accessToken, obj.toJSONString()); + } + + /** + * 绌洪棿璁剧疆 + * @param corpMpSpaceApi + * @param accessToken + * @param spaceId + * @param enableConfidentialMode + * @return + */ + public static JSONObject spaceSetting(CorpMpSpaceApi corpMpSpaceApi, String accessToken, String spaceId, boolean enableConfidentialMode) + { + JSONObject obj = new JSONObject(); + obj.put("spaceid", spaceId); + obj.put("enable_confidential_mode", enableConfidentialMode); + + return corpMpSpaceApi.spaceSetting(accessToken, obj.toJSONString()); + } + + /** + * 鍒涘缓鏂囦欢澶� + * @param corpMpSpaceApi + * @param accessToken + * @param spaceId 绌洪棿id + * @param fatherId 涓婄骇鐩綍id,濡傛灉鏄┖闂翠笅绗竴绾э紝鍒欐槸绌洪棿id + * @param fileName 鏂囦欢澶瑰悕绉� + * @return + */ + public static JSONObject createDir(CorpMpSpaceApi corpMpSpaceApi, String accessToken, String spaceId, String fatherId, String fileName) + { + JSONObject param = new JSONObject(); + param.put("spaceid", spaceId); + param.put("fatherid", fatherId); + param.put("file_type", 1); + param.put("file_name", fileName); + + + return corpMpSpaceApi.createFile(accessToken, param.toJSONString()); + } + + /** + * 鏂囦欢/鏂囦欢澶归噸鍛藉悕 + * @param corpMpSpaceApi + * @param accessToken + * @param fileId + * @param fileName + * @return + */ + public static JSONObject editDirName(CorpMpSpaceApi corpMpSpaceApi, String accessToken, String fileId, String fileName) + { + JSONObject param = new JSONObject(); + param.put("fileid", fileId); + param.put("new_name", fileName); + + return corpMpSpaceApi.renameFile(accessToken, param.toJSONString()); + } + + /** + * 绉婚櫎鏂囦欢澶� + * @param corpMpSpaceApi + * @param accessToken + * @param fileId + * @return + */ + public static JSONObject deleteDir(CorpMpSpaceApi corpMpSpaceApi, String accessToken, String fileId) + { + JSONObject param = new JSONObject(); + + JSONArray arr = new JSONArray(); + arr.add(fileId); + + param.put("fileid", arr); + + return corpMpSpaceApi.deleteFile(accessToken, param.toJSONString()); + } + + /** + * 浼�10M浠ュ唴鏂囦欢 + * @param corpMpSpaceApi + * @param accessToken + * @param name + * @param fileBase64Content + * @param spaceId + * @param fatherId + * @return + */ + public static JSONObject uploadFile(CorpMpSpaceApi corpMpSpaceApi, String accessToken, String name, String fileBase64Content, String spaceId, String fatherId) { + JSONObject param = new JSONObject(); + param.put("spaceid", spaceId); + param.put("fatherid", fatherId); + param.put("file_name", name); + param.put("file_base64_content", fileBase64Content); + + return corpMpSpaceApi.fileUpload(accessToken, param.toJSONString()); + } + + /** + * 鍒嗗潡涓婁紶鏂囦欢-鍒濆鍖� + * @param corpMpSpaceApi + * @param accessToken + * @param spaceId + * @param fatherId + * @param selectTicket + * @param fileName + * @param size + * @param skipPushCard + * @param blockSha + * @return + */ + public static JSONObject uploadBigFileInit(CorpMpSpaceApi corpMpSpaceApi, String accessToken, String spaceId, String fatherId, + String selectTicket, String fileName, Long size, boolean skipPushCard, List<String> blockSha) { + JSONObject param = new JSONObject(); + param.put("spaceid", spaceId); + param.put("fatherid", fatherId); + param.put("selected_ticket", selectTicket); + param.put("file_name", fileName); + param.put("size", size); + param.put("skip_push_card", skipPushCard); + + JSONArray arr = new JSONArray(); + for(String sha : blockSha) + { + arr.add(sha); + } + param.put("block_sha", arr); + + return corpMpSpaceApi.fileUploadInit(accessToken, param.toJSONString()); + } + + /** + * 鍒嗗潡涓婁紶鏂囦欢-閮ㄥ垎涓婁紶 + * @param corpMpSpaceApi + * @param accessToken + * @param uploadKey + * @param index + * @param fileBase64Content + * @return + */ + public static JSONObject uploadBigFilePart(CorpMpSpaceApi corpMpSpaceApi, String accessToken, String uploadKey, int index, String fileBase64Content) { + JSONObject param = new JSONObject(); + param.put("upload_key", uploadKey); + param.put("index", index); + param.put("file_base64_content", fileBase64Content); + + return corpMpSpaceApi.fileUploadPart(accessToken, param.toJSONString()); + } + + /** + * 鍒嗗潡涓婁紶鏂囦欢-涓婁紶瀹屾垚 + * @param corpMpSpaceApi + * @param accessToken + * @param uploadKey + * @return + */ + public static JSONObject uploadBigFileFin(CorpMpSpaceApi corpMpSpaceApi, String accessToken, String uploadKey) { + JSONObject param = new JSONObject(); + param.put("upload_key", uploadKey); + + return corpMpSpaceApi.fileUploadFinish(accessToken, param.toJSONString()); + } + + /** + * 鑾峰彇涓嬭浇璺緞 + * @param corpMpSpaceApi + * @param accessToken + * @param fileId + * @return + */ + public static JSONObject getDownloadUrl(CorpMpSpaceApi corpMpSpaceApi, String accessToken, String fileId){ + JSONObject param = new JSONObject(); + param.put("fileid", fileId); + + return corpMpSpaceApi.getDownloadUrl(accessToken, param.toJSONString()); + } +} diff --git a/hx_common/src/main/java/com/hx/mp/util/CorpMpUtil.java b/hx_common/src/main/java/com/hx/mp/util/CorpMpUtil.java new file mode 100644 index 0000000..8dd010b --- /dev/null +++ b/hx_common/src/main/java/com/hx/mp/util/CorpMpUtil.java @@ -0,0 +1,347 @@ +package com.hx.mp.util; + +import com.hx.util.corp.entity.AppLetInfo; +import com.hx.exception.TipsException; +import com.hx.util.HttpMethodUtil; +import com.hx.util.StringUtils; +import net.sf.json.JSONException; +import net.sf.json.JSONObject; +import org.apache.commons.io.IOUtils; + +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.text.MessageFormat; +import java.util.HashMap; +import java.util.Map; + +/** + * 浼佷笟寰俊宸ュ叿绫� + */ +public class CorpMpUtil { + + /**閾炬帴-鑾峰彇搴旂敤accessToken*/ + public static final String URL_GET_ACCESS_TOKEN = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}"; + /**閾炬帴-鑾峰彇session淇℃伅*/ + public static final String URL_CODE_2_SESSION = "https://qyapi.weixin.qq.com/cgi-bin/miniprogram/jscode2session?access_token={0}&js_code={1}&grant_type=authorization_code"; + /**閾炬帴-娣诲姞鏍囩*/ + public static final String URL_ADD_LABEL = "https://qyapi.weixin.qq.com/cgi-bin/tag/create?access_token={0}"; + /**閾炬帴-娣诲姞閮ㄩ棬*/ + public static final String URL_ADD_DEPARTMENT = "https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token={0}"; + /**閾炬帴-淇敼閮ㄩ棬*/ + public static final String URL_UPDATE_DEPARTMENT = "https://qyapi.weixin.qq.com/cgi-bin/department/update?access_token={0}"; + /**閾炬帴-鍒犻櫎閮ㄩ棬*/ + public static final String URL_DELETE_DEPARTMENT = "https://qyapi.weixin.qq.com/cgi-bin/department/delete?access_token={0}&id={1}"; + /**閾炬帴-娣诲姞鎴愬憳*/ + public static final String URL_ADD_USER = "https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token={0}"; + /**閾炬帴-鏇存柊鎴愬憳*/ + public static final String URL_UPDATE_USER = "https://qyapi.weixin.qq.com/cgi-bin/user/update?access_token={0}"; + /**閾炬帴-鍒犻櫎鎴愬憳*/ + public static final String URL_DELETE_USER = "https://qyapi.weixin.qq.com/cgi-bin/user/delete?access_token={0}&userid={1}"; + /**閾炬帴-鎴愬憳璇︽儏*/ + public static final String URL_INFO_USER = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token={0}&userid={1}"; + /**鍙戦�佹秷鎭�*/ + public static final String URL_MESSAGE_SEND = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="; + + + /** + * 娣诲姞宸ヤ綔浜哄憳 + * @param at 璁块棶at + * @param userId 鐢ㄦ埛id + * @param name 鍚嶇О + * @param depId 閮ㄩ棬id + * @param position 鑱屼綅 + * @param tel 鐢佃瘽 + * @param email 閭 + * @return 杩斿洖 + */ + public static int addUser(String at, String userId, String name, int depId + , String position,String tel,String email) { + + if(StringUtils.isEmpty(tel)&&StringUtils.isEmpty(email)){ + throw new TipsException("娣诲姞浼佷笟寰俊鎵嬫満鍙峰拰閭涓嶈兘閮戒负绌猴紒"); + } + + JSONObject obj = new JSONObject(); + obj.put("userid", userId); + obj.put("name", name); + obj.put("department", depId); + obj.put("position", position); + obj.put("mobile", tel); + obj.put("email", email); + obj = HttpURLUtil(MessageFormat.format(URL_ADD_USER, at), obj.toString()); + if(obj != null) { + return obj.optInt("errcode", -1); + } + return -1; + } + + /** + * 娣诲姞宸ヤ綔浜哄憳 + * @param at 璁块棶at + * @param userId 鐢ㄦ埛id + * @param name 鍚嶇О + * @param depId 閮ㄩ棬id + * @param position 鑱屼綅 + * @param tel 鐢佃瘽 + * @param email 閭 + * @return 杩斿洖 + */ + public static JSONObject addUserObj(String at, String userId, String name, int depId + , String position,String tel,String email) { + + if(StringUtils.isEmpty(tel)&&StringUtils.isEmpty(email)){ + throw new TipsException("娣诲姞浼佷笟寰俊鎵嬫満鍙峰拰閭涓嶈兘閮戒负绌猴紒"); + } + + JSONObject obj = new JSONObject(); + obj.put("userid", userId); + obj.put("name", name); + obj.put("department", depId); + obj.put("position", position); + obj.put("mobile", tel); + obj.put("email", email); + obj = HttpURLUtil(MessageFormat.format(URL_ADD_USER, at), obj.toString()); + + if(obj == null){ + obj = new JSONObject(); + } + + return obj; + + } + + /** + * 鏇存柊宸ヤ綔浜哄憳 + * @param at 璁块棶at + * @param userId 鐢ㄦ埛id + * @param name 鍚嶇О + * @param depId 閮ㄩ棬id + * @param position 鑱屼綅 + * @param tel 鐢佃瘽 + * @param email 閭 + * @return 杩斿洖 + */ + public static int updateUser(String at, String userId, String name, int depId + , String position,String tel,String email) { + JSONObject obj = new JSONObject(); + obj.put("userid", userId); + obj.put("name", name); + obj.put("department", depId); + obj.put("position", position); + obj.put("mobile", tel); + obj.put("email", email); + + obj = HttpURLUtil(MessageFormat.format(URL_UPDATE_USER, at), obj.toString()); + if(obj != null && obj.optInt("errcode", -1) == 0) { + return obj.optInt("errcode", -1); + } + + return -1; + } + + /** + * 鍒犻櫎宸ヤ綔浜哄憳 + * @param at 璁块棶at + * @param userId 浼佷笟鐢ㄦ埛id + * @return 杩斿洖 + */ + public static int deleteUser(String at, String userId) { + JSONObject obj = new JSONObject(); + obj.put("userid", userId); + + obj = HttpURLUtil(MessageFormat.format(URL_DELETE_USER, at,userId), obj.toString()); + if(obj != null) { + return obj.optInt("errcode", -1); + } + return -1; + } + + /** + * 宸ヤ綔浜哄憳鍒ゆ柇鏄惁瀛樺湪浼佷笟寰俊 + * @param at 璁块棶at + * @param userId 鐢ㄦ埛id + * @return 杩斿洖 + */ + public static int infoUser(String at, String userId) { + JSONObject obj = new JSONObject(); + obj.put("userid", userId); + + obj = HttpURLUtil(MessageFormat.format(URL_INFO_USER, at,userId), obj.toString()); + + if(obj != null) { + return obj.optInt("errcode", -1); + } + return -1; + } + + /** + * 鑾峰彇浼佷笟鐢ㄦ埛淇℃伅 + * @param at 璁块棶at + * @param userId 鐢ㄦ埛id + * @return 杩斿洖 + */ + public static JSONObject userData(String at, String userId) { + JSONObject obj = new JSONObject(); + obj.put("userid", userId); + + return obj = HttpURLUtil(MessageFormat.format(URL_INFO_USER, at,userId), obj.toString()); + } + + + /** + * 娣诲姞閮ㄩ棬 + * @param name 閮ㄩ棬鍚嶇О + * @return id + */ + public static int addDepartment(String at, String name, int parentId) { + JSONObject obj = new JSONObject(); + obj.put("name", name); + obj.put("parentid", parentId); + + obj = HttpURLUtil(MessageFormat.format(URL_ADD_DEPARTMENT, at), obj.toString()); + + if(obj != null && obj.optInt("errcode", -1) == 0) { + return obj.optInt("id", -1); + } + return -1; + } + + /** + * 鏇存柊閮ㄩ棬 + * @param name 閮ㄩ棬鍚嶇О + * @param deaprtId 閮ㄩ棬id + * @param parentid 鐖剁被閮ㄩ棬id锛屽彲浠ヤ负绌� + * @return 鐘舵�侊紝0鎴愬姛 + */ + public static int updateDepartment(String at, String name, int deaprtId,int parentid) { + JSONObject obj = new JSONObject(); + obj.put("name", name); + obj.put("id", deaprtId); + obj.put("parentid", parentid); + + obj = HttpURLUtil(MessageFormat.format(URL_UPDATE_DEPARTMENT, at), obj.toString()); + return obj.optInt("errcode", -1); + } + + /**鍒犻櫎閮ㄩ棬 + * 鍒犻櫎鐨勯儴闂ㄤ笉鑳芥槸鏍归儴闂ㄤ笖娌℃湁鎴愬憳 + * @param deaprtId 閮ㄩ棬id + * @return 鐘舵�侊紝0鎴愬姛 + */ + public static int deleteDepartment(String at,int deaprtId) { + JSONObject obj = new JSONObject(); + obj.put("id", deaprtId); + + obj = HttpURLUtil(MessageFormat.format(URL_DELETE_DEPARTMENT,at,deaprtId), obj.toString()); + System.out.println("鍒犻櫎閮ㄩ棬:"+obj.toString()); + return obj.optInt("errcode", -1); + } + + /**鍙戦�佷紒涓氬簲鐢ㄦ秷鎭� + * @param accessToken 浼佷笟accessToken + * @param data 鍙戦�佹暟鎹粨鏋� + * @return + */ + public static JSONObject messageSend(String accessToken,String data){ + return HttpURLUtil(URL_MESSAGE_SEND+accessToken,data); + } + + /**娣诲姞鐢ㄦ埛鏍囩锛屾爣绛惧悕绉颁笉鑳介噸澶� + * @param at 璁块棶at + * @param label 鏍囩鍚嶇О + * @return 杩斿洖 -1澶辫触,0鎴愬姛锛�1宸插瓨鍦� + */ + public static int addLabel(String at, String label) { + String url = MessageFormat.format(URL_ADD_LABEL, at); + JSONObject obj = new JSONObject(); + obj.put("tagname", label); + obj = HttpURLUtil(url, obj.toString()); + System.out.println("obj....:"+obj.toString()); + if(obj != null ) { + int errcode = obj.optInt("errcode", -1); + if( errcode== 0){ + //涓婁紶鎴愬姛 + return obj.optInt("tagid", -1); + }if(errcode == 40071){ + //鏍囩宸茬粡瀛樺湪 + return 1; + } + } + return -1; + } + + + /** + * 鑾峰彇搴旂敤accessToken + * @param corpId 浼佷笟id + * @param appSecret 搴旂敤瀵嗛挜 + * @return + * @throws Exception + */ + public static JSONObject getApplicationAccessToken(String corpId, String appSecret) { + String url = MessageFormat.format(URL_GET_ACCESS_TOKEN, corpId, appSecret); + JSONObject obj = HttpURLUtil(url, null); + return obj; + } + + /** + * 浣跨敤涓存椂鐧诲綍鍑瘉code鑾峰彇 session_key銆佺敤鎴穟serId浠ュ強鐢ㄦ埛鎵�鍦ㄤ紒涓氱殑corpId绛変俊鎭� + * @param accessToken 璁块棶token + * @param code 涓存椂code + * @return + */ + public static JSONObject code2Session(String accessToken, String code) { + String url = MessageFormat.format(URL_CODE_2_SESSION, accessToken, code); + JSONObject obj = HttpURLUtil(url, null); + return obj; + } + + + + /** 璇锋眰http鍗忚 鑾峰彇淇℃伅宸ュ叿 **/ + public static JSONObject HttpURLUtil(String url, String data) { + HttpURLConnection con = null; + URL u = null; + String wxMsgXml = null; + JSONObject obj = null; + try { + u = new URL(url); + con = (HttpURLConnection) u.openConnection(); + con.setRequestMethod("POST"); + con.setDoOutput(true); + con.setDoInput(true); + con.setUseCaches(false); + con.setReadTimeout(5000); + con.setRequestProperty("Charset", "UTF-8"); + con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); + + if (data != null) { + OutputStream os = con.getOutputStream(); + os.write(data.getBytes("utf-8")); + } + + if (con.getResponseCode() != 200) + throw new RuntimeException("璇锋眰url澶辫触"); + // 璇诲彇杩斿洖鍐呭 + wxMsgXml = IOUtils.toString(con.getInputStream(), "utf-8"); + obj = JSONObject.fromObject(wxMsgXml); + // //System.out.println("HttpURLUtil:"+wxMsgXml); + } catch (Exception e) { + e.printStackTrace(); + obj = new JSONObject(); + try { + obj.put("status", 1); + obj.put("errMsg", e.getMessage()); + } catch (JSONException e1) { + e1.printStackTrace(); + } + } finally { + if (con != null) { + con.disconnect(); + } + } + return obj; + } + +} diff --git a/hx_common/src/main/java/com/hx/mp/util/CorpWXPayQrUtil.java b/hx_common/src/main/java/com/hx/mp/util/CorpWXPayQrUtil.java new file mode 100644 index 0000000..65010c7 --- /dev/null +++ b/hx_common/src/main/java/com/hx/mp/util/CorpWXPayQrUtil.java @@ -0,0 +1,73 @@ +package com.hx.mp.util; + +import com.hx.exception.ServiceException; +import com.hx.util.HttpUtil; +import com.hx.util.SimpleTool; +import com.hx.util.StringUtils; +import net.sf.json.JSONObject; +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.ssl.SSLContexts; +import org.apache.http.util.EntityUtils; +import org.dom4j.Document; +import org.dom4j.Element; +import org.dom4j.io.SAXReader; + +import javax.net.ssl.SSLContext; +import javax.servlet.http.HttpServletRequest; +import java.io.File; +import java.io.FileInputStream; +import java.security.KeyStore; +import java.util.*; + + +/** 鏈嶅姟鍟嗗晢鎴種ative锛堜簩缁寸爜鎵爜鏀粯锛� + * @author ChenJiaHe + */ +public class CorpWXPayQrUtil { + + + /**鏈嶅姟鍟�-鑾峰彇浜岀淮鐮佹敮浠樻暟鎹�*/ + private static final String PAY_NATIVE_URL = "https://api.mch.weixin.qq.com/v3/pay/partner/transactions/native"; + + /**鑾峰彇鏀粯浜岀淮鐮佹暟鎹� + * @param sp_appid 鏈嶅姟鍟嗙敵璇风殑鍏紬鍙穉ppid + * @param sp_mchid 鏈嶅姟鍟嗘埛鍙� + * @param sub_appid 瀛愬晢鎴风敵璇风殑鍏紬鍙穉ppid 涓嶅繀濉� + * @param sub_mchid 瀛愬晢鎴风殑鍟嗘埛鍙� + * @param description 鍟嗗搧鎻忚堪 + * @param out_trade_no 鍟嗘埛绯荤粺鍐呴儴璁㈠崟鍙� + * @param amount 閲戦锛堝垎锛� + * @param notify_url 鍥炶皟鍦板潃 + * @return + * @throws Exception + */ + public static JSONObject nativeQr(String sp_appid , String sp_mchid , String sub_appid + , String sub_mchid , String description , String out_trade_no , Integer amount + ,String notify_url ) + throws Exception { + + JSONObject parameters = new JSONObject(); + parameters.put("sp_appid", sp_appid); + parameters.put("sp_mchid", sp_mchid); + parameters.put("sub_appid", sub_appid); + parameters.put("sub_mchid", sub_mchid); + parameters.put("description", description); + parameters.put("out_trade_no", out_trade_no); + parameters.put("notify_url", notify_url); + + JSONObject amountObj = new JSONObject(); + amountObj.put("total",amount); + amountObj.put("currency","CNY"); + parameters.put("amount", amountObj); + + JSONObject returnObj = HttpUtil.HttpURLUtilJson(PAY_NATIVE_URL,parameters.toString()); + + return returnObj; + } +} diff --git a/hx_common/src/main/java/com/hx/mp/util/HttpClientUtil.java b/hx_common/src/main/java/com/hx/mp/util/HttpClientUtil.java new file mode 100644 index 0000000..5f99f59 --- /dev/null +++ b/hx_common/src/main/java/com/hx/mp/util/HttpClientUtil.java @@ -0,0 +1,340 @@ +package com.hx.mp.util; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.security.KeyManagementException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.security.UnrecoverableKeyException; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.util.HashMap; +import java.util.Map; + +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManagerFactory; + +/** + * Http锟酵伙拷锟剿癸拷锟斤拷锟斤拷<br/> + * 锟斤拷锟斤拷锟节诧拷锟斤拷锟斤拷锟洁,锟诫不要锟斤拷锟解部锟斤拷锟矫★拷 + * @author miklchen + * + */ +public class HttpClientUtil { + + public static final String SunX509 = "SunX509"; + public static final String JKS = "JKS"; + public static final String PKCS12 = "PKCS12"; + public static final String TLS = "TLS"; + + /** + * get HttpURLConnection + * @param strUrl url锟斤拷址 + * @return HttpURLConnection + * @throws IOException + */ + public static HttpURLConnection getHttpURLConnection(String strUrl) + throws IOException { + URL url = new URL(strUrl); + HttpURLConnection httpURLConnection = (HttpURLConnection) url + .openConnection(); + return httpURLConnection; + } + + /** + * get HttpsURLConnection + * @param strUrl url锟斤拷址 + * @return HttpsURLConnection + * @throws IOException + */ + public static HttpsURLConnection getHttpsURLConnection(String strUrl) + throws IOException { + URL url = new URL(strUrl); + HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url + .openConnection(); + return httpsURLConnection; + } + + /** + * 锟斤拷取锟斤拷锟斤拷锟窖拷锟斤拷锟絬rl + * @param strUrl + * @return String + */ + public static String getURL(String strUrl) { + + if(null != strUrl) { + int indexOf = strUrl.indexOf("?"); + if(-1 != indexOf) { + return strUrl.substring(0, indexOf); + } + + return strUrl; + } + + return strUrl; + + } + + /** + * 锟斤拷取锟斤拷询锟斤拷 + * @param strUrl + * @return String + */ + public static String getQueryString(String strUrl) { + + if(null != strUrl) { + int indexOf = strUrl.indexOf("?"); + if(-1 != indexOf) { + return strUrl.substring(indexOf+1, strUrl.length()); + } + + return ""; + } + + return strUrl; + } + + /** + * 锟斤拷询锟街凤拷转锟斤拷锟斤拷Map<br/> + * name1=key1&name2=key2&... + * @param queryString + * @return + */ + @SuppressWarnings("rawtypes") + public static Map queryString2Map(String queryString) { + if(null == queryString || "".equals(queryString)) { + return null; + } + + Map m = new HashMap(); + String[] strArray = queryString.split("&"); + for(int index = 0; index < strArray.length; index++) { + String pair = strArray[index]; + HttpClientUtil.putMapByPair(pair, m); + } + + return m; + + } + + /** + * 锟窖硷拷值锟斤拷锟斤拷锟組ap<br/> + * pair:name=value + * @param pair name=value + * @param m + */ + @SuppressWarnings({ "unchecked", "rawtypes" }) + public static void putMapByPair(String pair, Map m) { + + if(null == pair || "".equals(pair)) { + return; + } + + int indexOf = pair.indexOf("="); + if(-1 != indexOf) { + String k = pair.substring(0, indexOf); + String v = pair.substring(indexOf+1, pair.length()); + if(null != k && !"".equals(k)) { + m.put(k, v); + } + } else { + m.put(pair, ""); + } + } + + /** + * BufferedReader转锟斤拷锟斤拷String<br/> + * 注锟斤拷:锟斤拷锟截憋拷锟斤拷要锟斤拷锟叫达拷锟斤拷 + * @param reader + * @return String + * @throws IOException + */ + public static String bufferedReader2String(BufferedReader reader) throws IOException { + StringBuffer buf = new StringBuffer(); + String line = null; + while( (line = reader.readLine()) != null) { + buf.append(line); + buf.append("\r\n"); + } + + return buf.toString(); + } + + /** + * 锟斤拷锟斤拷锟斤拷锟�<br/> + * 注锟斤拷:锟斤拷锟截憋拷锟斤拷要锟斤拷锟叫达拷锟斤拷 + * @param out + * @param data + * @param len + * @throws IOException + */ + public static void doOutput(OutputStream out, byte[] data, int len) + throws IOException { + int dataLen = data.length; + int off = 0; + while (off < data.length) { + if (len >= dataLen) { + out.write(data, off, dataLen); + off += dataLen; + } else { + out.write(data, off, len); + off += len; + dataLen -= len; + } + + // 刷锟铰伙拷锟斤拷锟斤拷 + out.flush(); + } + + } + + /** + * 锟斤拷取SSLContext + * @param trustFile + * @param trustPasswd + * @param keyFile + * @param keyPasswd + * @return + * @throws NoSuchAlgorithmException + * @throws KeyStoreException + * @throws IOException + * @throws CertificateException + * @throws UnrecoverableKeyException + * @throws KeyManagementException + */ + public static SSLContext getSSLContext( + FileInputStream trustFileInputStream, String trustPasswd, + FileInputStream keyFileInputStream, String keyPasswd) + throws NoSuchAlgorithmException, KeyStoreException, + CertificateException, IOException, UnrecoverableKeyException, + KeyManagementException { + + // ca + TrustManagerFactory tmf = TrustManagerFactory.getInstance(HttpClientUtil.SunX509); + KeyStore trustKeyStore = KeyStore.getInstance(HttpClientUtil.JKS); + trustKeyStore.load(trustFileInputStream, HttpClientUtil + .str2CharArray(trustPasswd)); + tmf.init(trustKeyStore); + + final char[] kp = HttpClientUtil.str2CharArray(keyPasswd); + KeyManagerFactory kmf = KeyManagerFactory.getInstance(HttpClientUtil.SunX509); + KeyStore ks = KeyStore.getInstance(HttpClientUtil.PKCS12); + ks.load(keyFileInputStream, kp); + kmf.init(ks, kp); + + SecureRandom rand = new SecureRandom(); + SSLContext ctx = SSLContext.getInstance(HttpClientUtil.TLS); + ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), rand); + + return ctx; + } + + /** + * 锟斤拷取CA证锟斤拷锟斤拷息 + * @param cafile CA证锟斤拷锟侥硷拷 + * @return Certificate + * @throws CertificateException + * @throws IOException + */ + public static Certificate getCertificate(File cafile) + throws CertificateException, IOException { + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + FileInputStream in = new FileInputStream(cafile); + Certificate cert = cf.generateCertificate(in); + in.close(); + return cert; + } + + /** + * 锟街凤拷转锟斤拷锟斤拷char锟斤拷锟斤拷 + * @param str + * @return char[] + */ + public static char[] str2CharArray(String str) { + if(null == str) return null; + + return str.toCharArray(); + } + + /** + * 锟芥储ca证锟斤拷锟絁KS锟斤拷式 + * @param cert + * @param alias + * @param password + * @param out + * @throws KeyStoreException + * @throws NoSuchAlgorithmException + * @throws CertificateException + * @throws IOException + */ + public static void storeCACert(Certificate cert, String alias, + String password, OutputStream out) throws KeyStoreException, + NoSuchAlgorithmException, CertificateException, IOException { + KeyStore ks = KeyStore.getInstance("JKS"); + + ks.load(null, null); + + ks.setCertificateEntry(alias, cert); + + // store keystore + ks.store(out, HttpClientUtil.str2CharArray(password)); + + } + + public static InputStream String2Inputstream(String str) { + return new ByteArrayInputStream(str.getBytes()); + } + + /** + * InputStream转锟斤拷锟斤拷Byte + * 注锟斤拷:锟斤拷锟截憋拷锟斤拷要锟斤拷锟叫达拷锟斤拷 + * @param in + * @return byte + * @throws Exception + */ + public static byte[] InputStreamTOByte(InputStream in) throws IOException{ + + int BUFFER_SIZE = 4096; + ByteArrayOutputStream outStream = new ByteArrayOutputStream(); + byte[] data = new byte[BUFFER_SIZE]; + int count = -1; + + while((count = in.read(data,0,BUFFER_SIZE)) != -1) + outStream.write(data, 0, count); + + data = null; + byte[] outByte = outStream.toByteArray(); + outStream.close(); + + return outByte; + } + + /** + * InputStream转锟斤拷锟斤拷String + * 注锟斤拷:锟斤拷锟截憋拷锟斤拷要锟斤拷锟叫达拷锟斤拷 + * @param in + * @param encoding 锟斤拷锟斤拷 + * @return String + * @throws Exception + */ + public static String InputStreamTOString(InputStream in,String encoding) throws IOException{ + + return new String(InputStreamTOByte(in),encoding); + + } + + +} diff --git a/hx_common/src/main/java/com/hx/mp/util/HttpUtil.java b/hx_common/src/main/java/com/hx/mp/util/HttpUtil.java new file mode 100644 index 0000000..7ccb979 --- /dev/null +++ b/hx_common/src/main/java/com/hx/mp/util/HttpUtil.java @@ -0,0 +1,31 @@ +package com.hx.mp.util; + +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.HttpClients; + +public class HttpUtil { + /** + * 鍙戦�乸ost璇锋眰 + * + * @param url + * 璇锋眰鍦板潃 + * @param outputEntity + * 鍙戦�佸唴瀹� + * @param isLoadCert + * 鏄惁鍔犺浇璇佷功 + */ + public static CloseableHttpResponse Post(String url, String outputEntity, boolean isLoadCert, String certPath, String mchId) throws Exception { + HttpPost httpPost = new HttpPost(url); + // 寰楁寚鏄庝娇鐢║TF-8缂栫爜锛屽惁鍒欏埌API鏈嶅姟鍣╔ML鐨勪腑鏂囦笉鑳借鎴愬姛璇嗗埆 + httpPost.addHeader("Content-Type", "text/xml"); + httpPost.setEntity(new StringEntity(outputEntity, "UTF-8")); + if (isLoadCert) { + // 鍔犺浇鍚湁璇佷功鐨刪ttp璇锋眰 + return HttpClients.custom().setSSLSocketFactory(CertUtil.initCert(certPath, mchId)).build().execute(httpPost); + } else { + return HttpClients.custom().build().execute(httpPost); + } + } +} \ No newline at end of file diff --git a/hx_common/src/main/java/com/hx/mp/util/HttpXmlUtils.java b/hx_common/src/main/java/com/hx/mp/util/HttpXmlUtils.java new file mode 100644 index 0000000..ac31380 --- /dev/null +++ b/hx_common/src/main/java/com/hx/mp/util/HttpXmlUtils.java @@ -0,0 +1,63 @@ +package com.hx.mp.util; + +import org.dom4j.Document; +import org.dom4j.DocumentHelper; +import org.dom4j.Element; +import org.jdom.JDOMException; +import org.jdom.input.SAXBuilder; +import org.xml.sax.InputSource; + +import java.io.IOException; +import java.io.StringReader; +import java.util.*; + +public class HttpXmlUtils { + + @SuppressWarnings("rawtypes") + public static String transferXml(SortedMap<Object, Object> parameters) { + + Document document = DocumentHelper.createDocument(); + Element root = document.addElement("xml"); + + Set es = parameters.entrySet(); + Iterator it = es.iterator(); + while (it.hasNext()) { + Map.Entry entry = (Map.Entry) it.next(); + String k = (String) entry.getKey(); + String v = (String) entry.getValue(); + + Element ToUserName = root.addElement(k); + ToUserName.addText(v); + } + + String queryString = document.asXML();// 杞负String + + queryString = queryString.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "").trim(); + + // System.out.println("浼佷笟绔粯娆惧弬鏁帮細"+queryString); + return queryString; + } + + @SuppressWarnings("unchecked") + public static Map<String, String> parseRefundXml(String refundXml) throws JDOMException, IOException { + + StringReader read = new StringReader(refundXml); + // 鍒涘缓鏂扮殑杈撳叆婧怱AX 瑙f瀽鍣ㄥ皢浣跨敤 InputSource 瀵硅薄鏉ョ‘瀹氬浣曡鍙� XML 杈撳叆 + InputSource source = new InputSource(read); + // 鍒涘缓涓�涓柊鐨凷AXBuilder + SAXBuilder sb = new SAXBuilder(); + // 閫氳繃杈撳叆婧愭瀯閫犱竴涓狣ocument + Document doc; + doc = (Document) sb.build(source); + Element root = doc.getRootElement();// 鎸囧悜鏍硅妭鐐� + List<Element> list = root.elements(); + Map<String, String> refundOrderMap = new HashMap<String, String>(); + if (list != null && list.size() > 0) { + for (Element element : list) { + refundOrderMap.put(element.getName(), element.getText()); + } + return refundOrderMap; + } + return null; + } +} diff --git a/hx_common/src/main/java/com/hx/mp/util/MD5Util.java b/hx_common/src/main/java/com/hx/mp/util/MD5Util.java new file mode 100644 index 0000000..08e76a4 --- /dev/null +++ b/hx_common/src/main/java/com/hx/mp/util/MD5Util.java @@ -0,0 +1,43 @@ +package com.hx.mp.util; + +import java.security.MessageDigest; + +public class MD5Util { + + private static String byteArrayToHexString(byte b[]) { + StringBuffer resultSb = new StringBuffer(); + for (int i = 0; i < b.length; i++) + resultSb.append(byteToHexString(b[i])); + + return resultSb.toString(); + } + + private static String byteToHexString(byte b) { + int n = b; + if (n < 0) + n += 256; + int d1 = n / 16; + int d2 = n % 16; + return hexDigits[d1] + hexDigits[d2]; + } + + public static String MD5Encode(String origin, String charsetname) { + String resultString = null; + try { + resultString = new String(origin); + MessageDigest md = MessageDigest.getInstance("MD5"); + if (charsetname == null || "".equals(charsetname)) + resultString = byteArrayToHexString(md.digest(resultString + .getBytes())); + else + resultString = byteArrayToHexString(md.digest(resultString + .getBytes(charsetname))); + } catch (Exception exception) { + } + return resultString; + } + + private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5", + "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; + +} diff --git a/hx_common/src/main/java/com/hx/mp/util/MPWeixinBaseUtil.java b/hx_common/src/main/java/com/hx/mp/util/MPWeixinBaseUtil.java new file mode 100644 index 0000000..90fe3d4 --- /dev/null +++ b/hx_common/src/main/java/com/hx/mp/util/MPWeixinBaseUtil.java @@ -0,0 +1,842 @@ +package com.hx.mp.util; + +import com.hx.util.OSSUtil; +import com.hx.util.SimpleTool; +import com.hx.util.StringUtils; +import com.hz.util.http.HttpHzUtil; +import com.hz.util.http.dto.HttpHzResponse; +import net.sf.json.JSONException; +import net.sf.json.JSONObject; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; +import org.springframework.stereotype.Component; + +import java.io.*; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.text.MessageFormat; +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * 寰俊鑾峰彇鏉冮檺鍩烘湰宸ュ叿绫� + * @author ChenJiaHe + * @Date 2020-07-14 + */ +@Component +public class MPWeixinBaseUtil { + + // 绫诲瀷 + private static final String GRANT_TYPE = "client_credential"; + + /**鑾峰彇access_token閾炬帴*/ + private static final String GETACCESS_TOKENURL = "https://api.weixin.qq.com/cgi-bin/token?grant_type="; + /**閫氳繃code鑾峰彇灏忕▼搴忎俊鎭摼鎺�*/ + private static final String JSCODE2SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session?"; + /**鍙戦�佽闃呮秷鎭�氱煡閾炬帴*/ + private static final String SEND_SUBSCRIBE_MESSAGE = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="; + /**鐢熸垚灏忕▼搴忎簩缁寸爜鍦板潃锛堟柟褰級*/ + public static final String MAKE_TWOCODE_SQUARE_URL = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token="; + /**鐢熸垚灏忕▼搴忎簩缁寸爜鍦板潃锛堝渾褰級*/ + public static final String MAKE_TWOCODE_ROUND_URL = "https://api.weixin.qq.com/wxa/getwxacode?access_token={0}"; + /**鐢熸垚鏃犻檺浜岀淮鐮�*/ + public static final String URL_UNLIMIT_SQUARE = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={0}"; + /**鑾峰彇灏忕▼搴忚闃呬釜浜烘ā鏉垮垪琛�*/ + private static final String GET_APP_TEMPLATE = "https://api.weixin.qq.com/wxaapi/newtmpl/gettemplate?access_token="; + /**鑾峰彇鍏紬鍙锋ā鏉垮垪琛�*/ + private static final String GET_GZH_TEMPLATE = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token="; + ////////////////////////////////////////////////// + + /** (灏忕▼搴�)閫氳繃code鎹㈠彇缃戦〉鎺堟潈access_token/濡傛灉鏄痵nsapi_base妯″紡鐨勬巿鏉冿紝杩欓噷灏卞彲浠ユ嬁鍒皁penId浜� ***/ + public static JSONObject getJscode2session(String appid,String secret,String code) { + + return HttpURLUtil(JSCODE2SESSION_URL+"appid="+appid+"&secret="+secret + +"&grant_type=authorization_code&js_code=" + code,null); + } + + /**鍙戦�佽闃呮秷鎭�氱煡**/ + public static JSONObject sendSubscribeMessage(String data,String accessToken){ + return HttpURLUtil(SEND_SUBSCRIBE_MESSAGE+accessToken,data); + } + + /** 鑾峰彇access_token */ + public static JSONObject getAccessToken(String appid,String secret) throws Exception { + String access_token; + // 閫氳繃WX鎺ュ彛鑾峰彇access_token + JSONObject obj = getApplication_Access_tokenForUrl(appid,secret); + return obj; + } + + /** 浠巜eixin鎺ュ彛鑾峰彇Access_token **/ + public static JSONObject getApplication_Access_tokenForUrl(String appid,String secret) { + return HttpURLUtil(GETACCESS_TOKENURL+GRANT_TYPE +"&appid="+appid +"&secret="+secret,null); + } + + /**鐢熸垚鏃犻檺浜岀淮鐮侊紝骞朵笂浼犲埌OSS*/ + public static String createUnlimitQrCode(String at, String scene, String page, int width, boolean autoColor, + JSONObject lineColor, boolean isHyaline, String fileName, String keyId, + String keySecret, String endPoint, String bucket) + { + String imgUrl = null; + InputStream in = null; + HttpURLConnection conn = null; + + try { + //鐢熸垚鍙戦�佹暟鎹� + JSONObject obj = new JSONObject(); + obj.put("scene", scene); + obj.put("width", width); + obj.put("page", page); + obj.put("auto_color", autoColor); + obj.put("line_color", lineColor); + obj.put("is_hyaline", isHyaline); + + // 鍒涘缓url璧勬簮 + URL url = new URL(StringUtils.format(URL_UNLIMIT_SQUARE, at)); + // 寤虹珛http杩炴帴 + conn = (HttpURLConnection) url.openConnection(); + // 璁剧疆鍏佽杈撳嚭 + conn.setDoOutput(true); + conn.setDoInput(true); + // 璁剧疆涓嶇敤缂撳瓨 + conn.setUseCaches(false); + // 璁剧疆浼犻�掓柟寮� + conn.setRequestMethod("POST"); + // 璁剧疆缁存寔闀胯繛鎺� + conn.setRequestProperty("Connection", "Keep-Alive"); + // 璁剧疆鏂囦欢瀛楃闆�: + conn.setRequestProperty("Charset", "UTF-8"); + // 璁剧疆鏂囦欢绫诲瀷: + conn.setRequestProperty("contentType", "application/json"); + // 寮�濮嬭繛鎺ヨ姹� + conn.connect(); + OutputStream out = conn.getOutputStream(); + // 鍐欏叆璇锋眰鐨勫瓧绗︿覆 + out.write((obj.toString()).getBytes()); + out.flush(); + out.close(); + + // 璇锋眰杩斿洖鐨勭姸鎬� + if (conn.getResponseCode() == 200) { + // 璇锋眰杩斿洖鐨勬暟鎹� + in = conn.getInputStream(); + imgUrl = OSSUtil.uploadImg(fileName, in, keyId, keySecret, endPoint, bucket); + conn.disconnect(); + conn = null; + } + + if (in != null) { + in.close(); + in = null; + } + + if (conn != null) { + conn.disconnect(); + conn = null; + } + }catch (Exception e) + { + e.printStackTrace(); + + if (in != null) { + try { + in.close(); + }catch (Exception ep) + { + ep.printStackTrace(); + } + in = null; + } + + if (conn != null) { + conn.disconnect(); + conn = null; + } + } + + return imgUrl; + } + + /**鐢熸垚鏈夐檺浜岀淮鐮�,杩斿洖涓存椂鏂� + * @param at 寰俊token + * @param page 璺宠浆閾炬帴 + * @param width 瀹藉害 + * @param autoColor 榛樿false + * @param lineColor 榛樿null + * @param isHyaline 榛樿false + * @return + */ + public static File createLimitedQrCode(String at, String page, int width, boolean autoColor, + JSONObject lineColor, boolean isHyaline) { + String imgUrl = null; + InputStream in = null; + HttpURLConnection conn = null; + + //鍒涘缓涓存椂鏂囦欢 + File file = null; + try { + file = File.createTempFile("temp", ".jpg"); + //鐢熸垚鍙戦�佹暟鎹� + JSONObject obj = new JSONObject(); + obj.put("width", width); + obj.put("path", page); + obj.put("auto_color", autoColor); + obj.put("line_color", lineColor); + obj.put("is_hyaline", isHyaline); + + // 鍒涘缓url璧勬簮 + URL url = new URL(StringUtils.format(MAKE_TWOCODE_ROUND_URL, at)); + // 寤虹珛http杩炴帴 + conn = (HttpURLConnection) url.openConnection(); + // 璁剧疆鍏佽杈撳嚭 + conn.setDoOutput(true); + conn.setDoInput(true); + // 璁剧疆涓嶇敤缂撳瓨 + conn.setUseCaches(false); + // 璁剧疆浼犻�掓柟寮� + conn.setRequestMethod("POST"); + // 璁剧疆缁存寔闀胯繛鎺� + conn.setRequestProperty("Connection", "Keep-Alive"); + // 璁剧疆鏂囦欢瀛楃闆�: + conn.setRequestProperty("Charset", "UTF-8"); + // 璁剧疆鏂囦欢绫诲瀷: + conn.setRequestProperty("contentType", "application/json"); + // 寮�濮嬭繛鎺ヨ姹� + conn.connect(); + OutputStream out = conn.getOutputStream(); + // 鍐欏叆璇锋眰鐨勫瓧绗︿覆 + out.write((obj.toString()).getBytes()); + out.flush(); + out.close(); + + // 璇锋眰杩斿洖鐨勭姸鎬� + if (conn.getResponseCode() == 200) { + // 璇锋眰杩斿洖鐨勬暟鎹� + in = conn.getInputStream(); + //杈撳叆鍒颁复鏃舵枃浠� + /*OutputStream os = new FileOutputStream(file); + int bytesRead = 0; + byte[] buffer = new byte[8192]; + while ((bytesRead = in.read(buffer, 0, 8192)) != -1) { + os.write(buffer, 0, bytesRead); + }*/ + FileUtils.copyInputStreamToFile(in, file); + + conn.disconnect(); + conn = null; + } + + if (in != null) { + in.close(); + in = null; + } + + if (conn != null) { + conn.disconnect(); + conn = null; + } + }catch (Exception e) { + e.printStackTrace(); + if (in != null) { + try { + in.close(); + }catch (Exception ep) { + ep.printStackTrace(); + } + in = null; + } + + if (conn != null) { + conn.disconnect(); + conn = null; + } + }finally { + if(file != null){ + file.deleteOnExit(); + } + } + return file; + } + + + /**鐢熸垚鏈夐檺浜岀淮鐮�,杩斿洖涓存椂鏂� + * @param at 寰俊token + * @param page 璺宠浆閾炬帴 + * @param width 瀹藉害 + * @param autoColor 榛樿false + * @param lineColor 榛樿null + * @param isHyaline 榛樿false + * @param envVersion 瑕佹墦寮�鐨勫皬绋嬪簭鐗堟湰銆傛寮忕増涓� release锛屼綋楠岀増涓� trial锛屽紑鍙戠増涓� develop + * @return + */ + public static File createLimitedQrCode(String at, String page, int width, boolean autoColor, + JSONObject lineColor, boolean isHyaline,String envVersion) { + String imgUrl = null; + InputStream in = null; + HttpURLConnection conn = null; + + //鍒涘缓涓存椂鏂囦欢 + File file = null; + try { + file = File.createTempFile("temp", ".jpg"); + //鐢熸垚鍙戦�佹暟鎹� + JSONObject obj = new JSONObject(); + obj.put("width", width); + obj.put("path", page); + obj.put("auto_color", autoColor); + obj.put("line_color", lineColor); + obj.put("is_hyaline", isHyaline); + obj.put("env_version", envVersion); + + // 鍒涘缓url璧勬簮 + URL url = new URL(StringUtils.format(MAKE_TWOCODE_ROUND_URL, at)); + // 寤虹珛http杩炴帴 + conn = (HttpURLConnection) url.openConnection(); + // 璁剧疆鍏佽杈撳嚭 + conn.setDoOutput(true); + conn.setDoInput(true); + // 璁剧疆涓嶇敤缂撳瓨 + conn.setUseCaches(false); + // 璁剧疆浼犻�掓柟寮� + conn.setRequestMethod("POST"); + // 璁剧疆缁存寔闀胯繛鎺� + conn.setRequestProperty("Connection", "Keep-Alive"); + // 璁剧疆鏂囦欢瀛楃闆�: + conn.setRequestProperty("Charset", "UTF-8"); + // 璁剧疆鏂囦欢绫诲瀷: + conn.setRequestProperty("contentType", "application/json"); + // 寮�濮嬭繛鎺ヨ姹� + conn.connect(); + OutputStream out = conn.getOutputStream(); + // 鍐欏叆璇锋眰鐨勫瓧绗︿覆 + out.write((obj.toString()).getBytes()); + out.flush(); + out.close(); + + // 璇锋眰杩斿洖鐨勭姸鎬� + if (conn.getResponseCode() == 200) { + // 璇锋眰杩斿洖鐨勬暟鎹� + in = conn.getInputStream(); + //杈撳叆鍒颁复鏃舵枃浠� + /*OutputStream os = new FileOutputStream(file); + int bytesRead = 0; + byte[] buffer = new byte[8192]; + while ((bytesRead = in.read(buffer, 0, 8192)) != -1) { + os.write(buffer, 0, bytesRead); + }*/ + FileUtils.copyInputStreamToFile(in, file); + + conn.disconnect(); + conn = null; + } + + if (in != null) { + in.close(); + in = null; + } + + if (conn != null) { + conn.disconnect(); + conn = null; + } + }catch (Exception e) { + e.printStackTrace(); + if (in != null) { + try { + in.close(); + }catch (Exception ep) { + ep.printStackTrace(); + } + in = null; + } + + if (conn != null) { + conn.disconnect(); + conn = null; + } + }finally { + if(file != null){ + file.deleteOnExit(); + } + } + return file; + } + + /**鐢熸垚鏃犻檺浜岀淮鐮�,杩斿洖涓存椂鏂� + * @param at 寰俊token + * @param scene 鍙傛暟锛屽彧鑳�32浣嶏紝鏈�濂戒笉瑕佷腑鏂� + * @param page 璺宠浆閾炬帴 + * @param width 瀹藉害 + * @param autoColor 榛樿false + * @param lineColor 榛樿null + * @param isHyaline 榛樿false + * @return + */ + public static File createUnlimitQrCode(String at, String scene, String page, int width, boolean autoColor, + JSONObject lineColor, boolean isHyaline) throws IOException { + String imgUrl = null; + InputStream in = null; + HttpURLConnection conn = null; + + //鍒涘缓涓存椂鏂囦欢 + File file = File.createTempFile("temp", ".jpg"); + + try { + //鐢熸垚鍙戦�佹暟鎹� + JSONObject obj = new JSONObject(); + obj.put("scene", scene); + obj.put("width", width); + obj.put("page", page); + obj.put("auto_color", autoColor); + obj.put("line_color", lineColor); + obj.put("is_hyaline", isHyaline); + + // 鍒涘缓url璧勬簮 + URL url = new URL(StringUtils.format(URL_UNLIMIT_SQUARE, at)); + // 寤虹珛http杩炴帴 + conn = (HttpURLConnection) url.openConnection(); + // 璁剧疆鍏佽杈撳嚭 + conn.setDoOutput(true); + conn.setDoInput(true); + // 璁剧疆涓嶇敤缂撳瓨 + conn.setUseCaches(false); + // 璁剧疆浼犻�掓柟寮� + conn.setRequestMethod("POST"); + // 璁剧疆缁存寔闀胯繛鎺� + conn.setRequestProperty("Connection", "Keep-Alive"); + // 璁剧疆鏂囦欢瀛楃闆�: + conn.setRequestProperty("Charset", "UTF-8"); + // 璁剧疆鏂囦欢绫诲瀷: + conn.setRequestProperty("contentType", "application/json"); + // 寮�濮嬭繛鎺ヨ姹� + conn.connect(); + OutputStream out = conn.getOutputStream(); + // 鍐欏叆璇锋眰鐨勫瓧绗︿覆 + out.write((obj.toString()).getBytes()); + out.flush(); + out.close(); + + // 璇锋眰杩斿洖鐨勭姸鎬� + if (conn.getResponseCode() == 200) { + // 璇锋眰杩斿洖鐨勬暟鎹� + in = conn.getInputStream(); + //杈撳叆鍒颁复鏃舵枃浠� + /*OutputStream os = new FileOutputStream(file); + int bytesRead = 0; + byte[] buffer = new byte[8192]; + while ((bytesRead = in.read(buffer, 0, 8192)) != -1) { + os.write(buffer, 0, bytesRead); + }*/ + FileUtils.copyInputStreamToFile(in, file); + + conn.disconnect(); + conn = null; + } + + if (in != null) { + in.close(); + in = null; + } + + if (conn != null) { + conn.disconnect(); + conn = null; + } + }catch (Exception e) { + e.printStackTrace(); + if (in != null) { + try { + in.close(); + }catch (Exception ep) { + ep.printStackTrace(); + } + in = null; + } + + if (conn != null) { + conn.disconnect(); + conn = null; + } + }finally { + file.deleteOnExit(); + } + return file; + } + + + /**鐢熸垚灏忕▼搴忎簩缁寸爜宸ュ叿锛堟柟褰級 + * path 浜岀淮鐮佽烦杞摼鎺� + * width 浜岀淮鐮佸搴�,榛樿鏄�430 + * saveUrl 淇濆瓨鍥剧墖鐨勫叏璺緞 + * seeUrl 鏄剧ず鍥剧墖璺緞 + * appid 灏忕▼搴忛厤缃� + * secret 灏忕▼搴忛厤缃� + * return 浜岀淮鐮佹樉绀哄浘鐗囬摼鎺� + * @throws Exception + * */ + public static String twoCodeImgSquare(String at, String path,Integer width,String saveUrl, + String seeUrl,String appid,String secret) throws Exception { + + if(!SimpleTool.checkNotNull(width)) { + width = 430; + } + //鐢熸垚鍙戦�佹暟鎹� + JSONObject obj = new JSONObject(); + obj.put("path", path); + obj.put("width", width); + + //浜岀淮鐮佸浘鐗囪矾寰� + String codeUrl = ""; + codeUrl = HttpURLUtilMakeCodeImg(MAKE_TWOCODE_SQUARE_URL+at,obj,saveUrl,seeUrl); + if(SimpleTool.checkNotNull(codeUrl)){ + if(!codeUrl.startsWith("/")){ + codeUrl = "/"+codeUrl; + } + } + return codeUrl; + } + + public static String twoCodeImgSquare(String at, String path,Integer width, String fileName, String keyId, + String keySecret, String endPoint, String bucket) throws Exception { + + if(!SimpleTool.checkNotNull(width)) { + width = 430; + } + //鐢熸垚鍙戦�佹暟鎹� + JSONObject obj = new JSONObject(); + obj.put("path", path); + obj.put("width", width); + + String imgUrl = null; + InputStream in = null; + HttpURLConnection conn = null; + + try { + + // 鍒涘缓url璧勬簮 + URL url = new URL(MAKE_TWOCODE_SQUARE_URL + at); + // 寤虹珛http杩炴帴 + conn = (HttpURLConnection) url.openConnection(); + // 璁剧疆鍏佽杈撳嚭 + conn.setDoOutput(true); + conn.setDoInput(true); + // 璁剧疆涓嶇敤缂撳瓨 + conn.setUseCaches(false); + // 璁剧疆浼犻�掓柟寮� + conn.setRequestMethod("POST"); + // 璁剧疆缁存寔闀胯繛鎺� + conn.setRequestProperty("Connection", "Keep-Alive"); + // 璁剧疆鏂囦欢瀛楃闆�: + conn.setRequestProperty("Charset", "UTF-8"); + // 璁剧疆鏂囦欢绫诲瀷: + conn.setRequestProperty("contentType", "application/json"); + // 寮�濮嬭繛鎺ヨ姹� + conn.connect(); + OutputStream out = conn.getOutputStream(); + // 鍐欏叆璇锋眰鐨勫瓧绗︿覆 + out.write((obj.toString()).getBytes()); + out.flush(); + out.close(); + + // 璇锋眰杩斿洖鐨勭姸鎬� + if (conn.getResponseCode() == 200) { + // 璇锋眰杩斿洖鐨勬暟鎹� + in = conn.getInputStream(); + imgUrl = OSSUtil.uploadImg(fileName, in, keyId, keySecret, endPoint, bucket); + conn.disconnect(); + conn = null; + } + + if (in != null) { + in.close(); + in = null; + } + + if (conn != null) { + conn.disconnect(); + conn = null; + } + }catch (Exception e) + { + e.printStackTrace(); + + if (in != null) { + try { + in.close(); + }catch (Exception ep) + { + ep.printStackTrace(); + } + in = null; + } + + if (conn != null) { + conn.disconnect(); + conn = null; + } + } + + return imgUrl; + + + } + + /** 鐢熸垚浜岀淮鐮佺殑鍥剧墖 杩斿洖鍥剧墖璺緞 + * urlx 鎵ц閾炬帴 + * objx 鏁版嵁 + * saveUrl 淇濆瓨鍥剧墖璺緞 + * seeUrl 鏄剧ず鍥剧墖璺緞 + * + * **/ + public static String HttpURLUtilMakeCodeImg(String urlx,JSONObject objx,String saveUrl,String seeUrl) throws IOException { + String realpath = null; + + // 鍒涘缓url璧勬簮 + URL url = new URL(urlx); + // 寤虹珛http杩炴帴 + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + // 璁剧疆鍏佽杈撳嚭 + conn.setDoOutput(true); + + conn.setDoInput(true); + + // 璁剧疆涓嶇敤缂撳瓨 + conn.setUseCaches(false); + // 璁剧疆浼犻�掓柟寮� + conn.setRequestMethod("POST"); + // 璁剧疆缁存寔闀胯繛鎺� + conn.setRequestProperty("Connection", "Keep-Alive"); + // 璁剧疆鏂囦欢瀛楃闆�: + conn.setRequestProperty("Charset", "UTF-8"); + // 杞崲涓哄瓧鑺傛暟缁� + // byte[] data = (objx.toString()).getBytes(); + // 璁剧疆鏂囦欢闀垮害 + // conn.setRequestProperty("Content-Length",String.valueOf(data.length)); + + // 璁剧疆鏂囦欢绫诲瀷: + conn.setRequestProperty("contentType", "application/json"); + // 寮�濮嬭繛鎺ヨ姹� + conn.connect(); + OutputStream out = conn.getOutputStream(); + // 鍐欏叆璇锋眰鐨勫瓧绗︿覆 + out.write((objx.toString()).getBytes()); + out.flush(); + out.close(); + + // 璇锋眰杩斿洖鐨勭姸鎬� + if (conn.getResponseCode() == 200) { + System.out.println("杩炴帴鎴愬姛"); + // 璇锋眰杩斿洖鐨勬暟鎹� + InputStream in = conn.getInputStream(); + ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); + byte[] temp = new byte[1024]; + int rc = 0; + while ((rc = in.read(temp, 0, 100)) > 0) { + swapStream.write(temp, 0, rc); + } + byte[] buffer2 = swapStream.toByteArray(); + String base64 = Base64.encodeBase64String(buffer2); + + //鐢熸垚鍚嶇О + java.util.Random r=new java.util.Random(); + StringBuilder str=new StringBuilder();//瀹氫箟鍙橀暱瀛楃涓� + for(int i=0;i<8;i++){ + str.append(r.nextInt(10)); + } + Date date = new Date(); + SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss"); + String imgName = sf.format(date); + imgName = imgName+str.toString(); + + //鏂囦欢淇濆瓨浣嶇疆 + File saveDir = new File(saveUrl); + if(!saveDir.exists()){ + saveDir.mkdir(); + } + File file = new File(saveDir+"/"+imgName+".png"); + FileOutputStream fos = new FileOutputStream(file); + fos.write(buffer2); + if(fos!=null){ + fos.close(); + } + if(in!=null){ + in.close(); + } + realpath = seeUrl+"/"+imgName+".png"; + } else { + System.out.println("no++"); + } + return realpath; + } + + /** 璇锋眰http鍗忚 鑾峰彇淇℃伅宸ュ叿 **/ + private static JSONObject HttpURLUtil(String url,String data) { + HttpURLConnection con = null; + URL u; + String wxMsgXml; + JSONObject obj; + try { + u = new URL(url); + con = (HttpURLConnection) u.openConnection(); + con.setRequestMethod("POST"); + con.setDoOutput(true); + con.setDoInput(true); + con.setUseCaches(false); + con.setReadTimeout(5000); + con.setRequestProperty("Charset", "UTF-8"); + con.setRequestProperty("Content-Type", + "application/x-www-form-urlencoded"); + if (data != null) { + OutputStream os = con.getOutputStream(); + os.write(data.getBytes("utf-8")); + } + if (con.getResponseCode() != 200) + throw new RuntimeException("璇锋眰url澶辫触"); + // 璇诲彇杩斿洖鍐呭 + wxMsgXml = IOUtils.toString(con.getInputStream(), StandardCharsets.UTF_8); + // 鍒ゆ柇杩斿洖鍙傛暟鏄惁姝g‘/鎴愬姛 + obj = JSONObject.fromObject(wxMsgXml); + // System.out.println("HttpURLUtil:"+wxMsgXml); + } catch (Exception e) { + e.printStackTrace(); + obj = new JSONObject(); + try { + obj.put("status", 1); + obj.put("errMsg", e.getMessage()); + } catch (JSONException e1) { + e1.printStackTrace(); + } + } finally { + if (con != null) { + con.disconnect(); + } + } + return obj; + } + + + + /**鐢熸垚鏃犻檺浜岀淮鐮�,杩斿洖涓存椂鏂� + * @param at 寰俊token + * @param scene 鍙傛暟锛屽彧鑳�32浣嶏紝鏈�濂戒笉瑕佷腑鏂� + * @param page 璺宠浆閾炬帴 + * @param width 瀹藉害 + * @param autoColor 榛樿false + * @param lineColor 榛樿null + * @param isHyaline 榛樿false + * @return + */ + public static File createUnlimitQrCode(String at, String scene, String page, int width, boolean autoColor, + JSONObject lineColor, boolean isHyaline, String env_version) throws IOException { + String imgUrl = null; + InputStream in = null; + HttpURLConnection conn = null; + + //鍒涘缓涓存椂鏂囦欢 + File file = File.createTempFile("temp", ".jpg"); + + try { + //鐢熸垚鍙戦�佹暟鎹� + JSONObject obj = new JSONObject(); + obj.put("scene", scene); + obj.put("width", width); + obj.put("page", page); + obj.put("auto_color", autoColor); + obj.put("line_color", lineColor); + obj.put("is_hyaline", isHyaline); + obj.put("env_version", env_version); + //浣撻獙鐗堟椂锛屽彲涓嶆鏌ラ〉闈㈡槸鍚﹀瓨鍦� + if("trial".equals(env_version)){ + obj.put("check_path", false); + } + // 鍒涘缓url璧勬簮 + URL url = new URL(StringUtils.format(URL_UNLIMIT_SQUARE, at)); + // 寤虹珛http杩炴帴 + conn = (HttpURLConnection) url.openConnection(); + // 璁剧疆鍏佽杈撳嚭 + conn.setDoOutput(true); + conn.setDoInput(true); + // 璁剧疆涓嶇敤缂撳瓨 + conn.setUseCaches(false); + // 璁剧疆浼犻�掓柟寮� + conn.setRequestMethod("POST"); + // 璁剧疆缁存寔闀胯繛鎺� + conn.setRequestProperty("Connection", "Keep-Alive"); + // 璁剧疆鏂囦欢瀛楃闆�: + conn.setRequestProperty("Charset", "UTF-8"); + // 璁剧疆鏂囦欢绫诲瀷: + conn.setRequestProperty("contentType", "application/json"); + // 寮�濮嬭繛鎺ヨ姹� + conn.connect(); + OutputStream out = conn.getOutputStream(); + // 鍐欏叆璇锋眰鐨勫瓧绗︿覆 + out.write((obj.toString()).getBytes()); + out.flush(); + out.close(); + + // 璇锋眰杩斿洖鐨勭姸鎬� + if (conn.getResponseCode() == 200) { + // 璇锋眰杩斿洖鐨勬暟鎹� + in = conn.getInputStream(); + //杈撳叆鍒颁复鏃舵枃浠� + /*OutputStream os = new FileOutputStream(file); + int bytesRead = 0; + byte[] buffer = new byte[8192]; + while ((bytesRead = in.read(buffer, 0, 8192)) != -1) { + os.write(buffer, 0, bytesRead); + }*/ + FileUtils.copyInputStreamToFile(in, file); + + conn.disconnect(); + conn = null; + } + + if (in != null) { + in.close(); + in = null; + } + + if (conn != null) { + conn.disconnect(); + conn = null; + } + }catch (Exception e) { + e.printStackTrace(); + if (in != null) { + try { + in.close(); + }catch (Exception ep) { + ep.printStackTrace(); + } + in = null; + } + + if (conn != null) { + conn.disconnect(); + conn = null; + } + }finally { + file.deleteOnExit(); + } + return file; + } + + /** + * 鑾峰彇灏忕▼搴忚闃呮ā鏉� + * @param accessToken token + * **/ + public static HttpHzResponse appTemplateList(String accessToken) { + return HttpHzUtil.HttpURLUtilJson(GET_APP_TEMPLATE + accessToken, null,null,null,"GET",null); + } + + /** + * 鍏紬鍙疯闃呮ā鏉� + * @param accessToken token + * **/ + public static HttpHzResponse gzhTemplateList(String accessToken) { + return HttpHzUtil.HttpURLUtilJson(GET_GZH_TEMPLATE+accessToken, null,null,null,"GET",null); + } + +} diff --git a/hx_common/src/main/java/com/hx/mp/util/MpUtil.java b/hx_common/src/main/java/com/hx/mp/util/MpUtil.java new file mode 100644 index 0000000..2dbc9cc --- /dev/null +++ b/hx_common/src/main/java/com/hx/mp/util/MpUtil.java @@ -0,0 +1,420 @@ +package com.hx.mp.util; + +import com.hx.util.HttpMethodUtil; +import com.hx.util.StringUtils; +import net.sf.json.JSONException; +import net.sf.json.JSONObject; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.io.IOUtils; + +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.sql.Timestamp; +import java.text.MessageFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +/** + * 寰俊灏忕▼搴忓伐鍏风被 + */ +public class MpUtil { + + /** 璇锋眰access_token */ + public static final String URL_ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}"; + /** 璇锋眰鏈嶅姟鍣↖P鍦板潃 */ + public static final String URL_SERVER_ADDR = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token="; + /** 寰俊js鐨刢ode鎹㈠幓sessionKey */ + public static final String JSCODE2SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&grant_type=authorization_code&js_code="; + /** 璇锋眰灏忕▼搴忕爜 **/ + public static final String URL_WXACODE = "https://api.weixin.qq.com/wxa/getwxacode?access_token="; + /** 璇锋眰灏忕▼搴忕爜-鏃犳暟閲忛檺鍒� **/ + public static final String URL_WXACODEUNLIMIT = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="; + /** 璇锋眰灏忕▼搴忎簩缁寸爜 */ + public static final String URL_QRCODE = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token="; + /** 鍙戞ā鐗堟秷鎭� */ + public static final String URL_SEND_TEMP_MSG = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token="; + /** 璁剧疆鍙戠エ鎺堟潈瀛楁 */ + public static final String URL_SET_TICKET_FIELD = "https://api.weixin.qq.com/card/invoice/setbizattr?action=set_auth_field&access_token="; + /** 鑾峰彇鍙戠エticket */ + public static final String URL_GET_TICKET_TICKET = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=wx_card&access_token="; + /** 鑾峰彇鍙戠エ鎺堟潈椤甸摼鎺� */ + public static final String URL_GET_TICKET_AUTH_LINK = "https://api.weixin.qq.com/card/invoice/getauthurl?access_token="; + /** 鏌ヨ鍙戠エ鎺堟潈瀛楁 */ + public static final String URL_GET_AUTH_FIELD = "https://api.weixin.qq.com/card/invoice/getauthdata?access_token="; + /** 璁剧疆 鏀粯鍚庡紑鍙戠エ */ + public static final String URL_SET_PAY_INVOICE = "https://api.weixin.qq.com/card/invoice/setbizattr?action=set_pay_mch&access_token="; + /** 鏌ヨ鏀粯鍚庡紑鍙戠エ */ + public static final String URL_GET_PAY_INVOICE = "https://api.weixin.qq.com/card/invoice/setbizattr?action=get_pay_mch&access_token="; + /** 鍙戦�佸鏈嶆秷鎭� */ + public static final String URL_SEND_KF_MSG = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="; + + /************************************************* + * 灏忕▼搴� + *************************/ + /** 鍒╃敤code鎹㈠彇sessionKey */ + public static JSONObject jsCode2session(String code, String appId, String appSecret) { + JSONObject obj = new JSONObject(); + String url = StringUtils.format(JSCODE2SESSION_URL, appId, appSecret) + code; + obj = HttpURLUtil(url, null); + return obj; + } + + /** 鑾峰彇灏忕▼搴忎簩缁寸爜鍥剧墖 */ + public static String getQrCode(String accessToken, String jsonParam) + throws Exception { + JSONObject obj = HttpURLUtilJson(URL_QRCODE + accessToken, jsonParam); + String qrStr = obj.optString("data"); + return qrStr; + } + + /** 浠巜eixin鎺ュ彛鑾峰彇Access_token **/ + public static JSONObject getApplication_Access_tokenForUrl(String appId, String appSecret) + throws Exception { + String url = MessageFormat.format(URL_ACCESS_TOKEN, appId, appSecret); + JSONObject obj = HttpURLUtil(url, null); + return obj; + } + + /** 璇锋眰http鍗忚 鑾峰彇淇℃伅宸ュ叿 **/ + public static InputStream HttpURLUtilStream(String url, String data) { + HttpURLConnection con = null; + URL u = null; + try { + u = new URL(url); + con = (HttpURLConnection) u.openConnection(); + con.setRequestMethod("POST"); + con.setDoOutput(true); + con.setDoInput(true); + con.setUseCaches(false); + con.setReadTimeout(200000); + con.setRequestProperty("Charset", "UTF-8"); + con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); + + if (data != null) { + OutputStream os = con.getOutputStream(); + os.write(data.getBytes("utf-8")); + } + + if (con.getResponseCode() != 200) + throw new RuntimeException("璇锋眰url澶辫触"); + + return con.getInputStream(); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (con != null) { + con.disconnect(); + } + } + return null; + } + + /** 鑾峰彇浜岀淮鐮佸浘鐗� **/ + public static JSONObject HttpURLUtilJson(String urlx, String objx) { + JSONObject jo = new JSONObject(); + try { + // 鍒涘缓url璧勬簮 + URL url = new URL(urlx); + // 寤虹珛http杩炴帴 + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + // 璁剧疆鍏佽杈撳嚭 + conn.setDoOutput(true); + + conn.setDoInput(true); + + // 璁剧疆涓嶇敤缂撳瓨 + conn.setUseCaches(false); + // 璁剧疆浼犻�掓柟寮� + conn.setRequestMethod("POST"); + // 璁剧疆缁存寔闀胯繛鎺� + conn.setRequestProperty("Connection", "Keep-Alive"); + // 璁剧疆鏂囦欢瀛楃闆�: + conn.setRequestProperty("Charset", "UTF-8"); + // 璁剧疆鏂囦欢绫诲瀷: + conn.setRequestProperty("contentType", "application/json"); + // 寮�濮嬭繛鎺ヨ姹� + conn.connect(); + OutputStream out = conn.getOutputStream(); + // 鍐欏叆璇锋眰鐨勫瓧绗︿覆 + out.write(objx.getBytes()); + out.flush(); + out.close(); + + // 璇锋眰杩斿洖鐨勭姸鎬� + if (conn.getResponseCode() == 200) { + // 璇锋眰杩斿洖鐨勬暟鎹� + InputStream in = conn.getInputStream(); + try { + ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); + byte[] temp = new byte[1024]; + int rc = 0; + while ((rc = in.read(temp, 0, 100)) > 0) { + swapStream.write(temp, 0, rc); + } + byte[] buffer = swapStream.toByteArray(); + String base64 = Base64.encodeBase64String(buffer); + jo.put("data", base64); + } catch (Exception e1) { + e1.printStackTrace(); + } + } else { + // System.out.println("no++"); + } + + } catch (Exception e) { + e.printStackTrace(); + } + return jo; + } + + /** 璇锋眰http鍗忚 鑾峰彇淇℃伅宸ュ叿 **/ + public static JSONObject HttpURLUtil(String url, String data) { + HttpURLConnection con = null; + URL u = null; + String wxMsgXml = null; + JSONObject obj = null; + try { + u = new URL(url); + con = (HttpURLConnection) u.openConnection(); + con.setRequestMethod("POST"); + con.setDoOutput(true); + con.setDoInput(true); + con.setUseCaches(false); + con.setReadTimeout(5000); + con.setRequestProperty("Charset", "UTF-8"); + con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); + + if (data != null) { + OutputStream os = con.getOutputStream(); + os.write(data.getBytes("utf-8")); + } + + if (con.getResponseCode() != 200) + throw new RuntimeException("璇锋眰url澶辫触"); + // 璇诲彇杩斿洖鍐呭 + wxMsgXml = IOUtils.toString(con.getInputStream(), "utf-8"); + obj = JSONObject.fromObject(wxMsgXml); + // //System.out.println("HttpURLUtil:"+wxMsgXml); + } catch (Exception e) { + e.printStackTrace(); + obj = new JSONObject(); + try { + obj.put("status", 1); + obj.put("errMsg", e.getMessage()); + } catch (JSONException e1) { + e1.printStackTrace(); + } + } finally { + if (con != null) { + con.disconnect(); + } + } + return obj; + } + + /** 鍙戦�佹ā鐗堟秷鎭� **/ + public static JSONObject sendTempMsg(String accessToken, String jsonStr) { + JSONObject obj = HttpURLUtil(URL_SEND_TEMP_MSG + accessToken, jsonStr); + return obj; + } + + public static Integer DateToTimestamp(Date time) { + Timestamp ts = new Timestamp(time.getTime()); + return (int) ((ts.getTime()) / 1000); + } + + /** + * 鍙戦�侀摼鎺ュ鏈嶆秷鎭� + * + * @throws JSONException + */ + public static String sendKfLinkMsg(String at, String openId, String title, String description, String url, + String imgUrl) throws JSONException { + String result = "fail"; + + JSONObject obj = new JSONObject(); + obj.put("touser", openId); + obj.put("msgtype", "link"); + + JSONObject pObj = new JSONObject(); + pObj.put("title", title); + pObj.put("description", description); + pObj.put("url", url); + pObj.put("thumb_url", imgUrl); + obj.put("link", pObj); + + JSONObject rObj = HttpURLUtil(URL_SEND_KF_MSG + at, obj.toString()); + // System.out.println("rObj==="+rObj); + if (rObj != null) { + if (rObj.optInt("errcode", -1) == 0) { + result = "suc"; + } else { + result = rObj.optString("errmsg"); + } + } + rObj = null; + obj = null; + + return result; + } + + /** + * 鍙戦�佸浘鐗囧鎴锋秷鎭� + * + * @param access_token + * access_token + * @param toUser + * 鐢ㄦ埛openid + * @param media_id + * 绱犳潗id + * @return + */ + public static String sendKfImageMsg(String access_token, String toUser, String media_id) { + String result = "fail"; + + try { + JSONObject obj = new JSONObject(); + obj.put("touser", toUser); + obj.put("msgtype", "image"); + + JSONObject pObj = new JSONObject(); + pObj.put("media_id", media_id); + obj.put("image", pObj); + + JSONObject rObj = HttpURLUtil(URL_SEND_KF_MSG + access_token, obj.toString()); + System.out.println("rObj==" + rObj.toString()); + if (rObj != null) { + if (rObj.optInt("errcode", -1) == 0) { + result = "suc"; + } else { + result = rObj.optString("errmsg"); + } + } + rObj = null; + obj = null; + } catch (Exception e) { + e.printStackTrace(); + } + + return result; + } + + /** + * 鍙戦�佹枃鏈鎴锋秷鎭� + * + * @param access_token + * access_token + * @param toUser + * 鐢ㄦ埛openid + * @return + */ + public static String sendKfTextMsg(String access_token, String toUser, String content) { + String result = "fail"; + + try { + JSONObject obj = new JSONObject(); + obj.put("touser", toUser); + obj.put("msgtype", "text"); + + JSONObject pObj = new JSONObject(); + pObj.put("content", content); + obj.put("text", pObj); + + JSONObject rObj = HttpURLUtil(URL_SEND_KF_MSG + access_token, obj.toString()); + if (rObj != null) { + if (rObj.optInt("errcode", -1) == 0) { + result = "suc"; + } else { + result = rObj.optString("errmsg"); + } + } + rObj = null; + obj = null; + } catch (Exception e) { + e.printStackTrace(); + } + + return result; + } + + /** 鑾峰彇灏忕▼搴忕爜鍥剧墖 */ + public static String getWXACode(String accessToken, String jsonParam, String path) + throws Exception { + JSONObject obj = HttpURLUtilJson(URL_WXACODE + accessToken, jsonParam); + String qrStr = obj.optString("data"); + return qrStr; + } + + /** 鑾峰彇灏忕▼搴忕爜鍥剧墖 */ + public static String getWXACodeUnlimit(String accessToken, String jsonParam, String path) + throws Exception { + JSONObject obj = HttpURLUtilJson(URL_WXACODEUNLIMIT + accessToken, jsonParam); + String qrStr = obj.optString("data"); + return qrStr; + } + + /** + * 鑾峰彇灏忕▼搴忛摼鎺� + * @param token 灏忕▼搴弔oken + * @param path 灏忕▼搴忛〉闈㈣矾寰� + * @param query 浼犲�煎弬鏁� + * @param env_version + * @return 瑕佹墦寮�鐨勫皬绋嬪簭鐗堟湰銆傛寮忕増涓� "release"锛屼綋楠岀増涓�"trial"锛屽紑鍙戠増涓�"develop"锛屼粎鍦ㄥ井淇″鎵撳紑鏃剁敓鏁� + */ + public static String getAooLetUrl(String token, String path, String query, String env_version) { + Map<String, Object> map = new HashMap<>(); + map.put("access_token", token); + JSONObject data = new JSONObject(); + data.put("path", path); + data.put("query", query); + data.put("env_version", env_version); + return HttpMethodUtil.HttpURLUtilJson("https://api.weixin.qq.com/wxa/generate_urllink", data.toString(), map, null, "POST"); + } + + + /** + * 鍏紬鍙峰彂閫佸皬绋嬪簭鍗$墖瀹㈡埛娑堟伅 + * @param access_token access_token + * @param toUser 鐢ㄦ埛openid + * @param title 鏍囬 + * @param appid 灏忕▼搴廰ppid + * @param pagepath 璺宠浆椤甸潰璺緞 + * @param thumb_media_id 缂╃暐鍥�/灏忕▼搴忓崱鐗囧浘鐗囩殑濯掍綋ID锛屽皬绋嬪簭鍗$墖鍥剧墖寤鸿澶у皬涓�520*416 + * @return + */ + public static String sendMpMsg(String access_token, String toUser, String title,String appid,String pagepath,String thumb_media_id) { + String result = "fail"; + + try { + JSONObject obj = new JSONObject(); + obj.put("touser", toUser); + obj.put("msgtype", "miniprogrampage"); + + JSONObject pObj = new JSONObject(); + pObj.put("title", title); + pObj.put("appid", appid); + pObj.put("pagepath", pagepath); + pObj.put("thumb_media_id", thumb_media_id); + obj.put("miniprogrampage", pObj); + + JSONObject rObj = HttpURLUtil(URL_SEND_KF_MSG + access_token, obj.toString()); + if (rObj != null) { + if (rObj.optInt("errcode", -1) == 0) { + result = "suc"; + } else { + result = rObj.optString("errmsg"); + } + } + rObj = null; + obj = null; + } catch (Exception e) { + e.printStackTrace(); + } + + return result; + } +} diff --git a/hx_common/src/main/java/com/hx/mp/util/RequestHandler.java b/hx_common/src/main/java/com/hx/mp/util/RequestHandler.java new file mode 100644 index 0000000..5fa8a6f --- /dev/null +++ b/hx_common/src/main/java/com/hx/mp/util/RequestHandler.java @@ -0,0 +1,273 @@ +package com.hx.mp.util; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.SortedMap; +import java.util.TreeMap; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * 锟斤拷锟斤拷锟斤拷锟斤拷 锟斤拷锟斤拷锟斤拷锟斤拷坛写锟斤拷啵拷锟叫碿reateSign锟斤拷锟斤拷锟斤拷锟缴★拷 + *JX + *linhan + */ +public class RequestHandler { + + /** 锟斤拷锟絬rl锟斤拷址 */ + private String gateUrl; + + /** 锟斤拷钥 */ + private String key; + + /** 锟斤拷锟斤拷牟锟斤拷锟� */ + @SuppressWarnings("rawtypes") + private SortedMap parameters; + + /** debug锟斤拷息 */ + private String debugInfo; + + private HttpServletRequest request; + + private HttpServletResponse response; + + /** + * 锟斤拷锟届函锟斤拷 + * + * @param request + * @param response + */ + /*@SuppressWarnings("rawtypes") + public RequestHandler(HttpServletRequest request, + HttpServletResponse response) { + this.request = request; + this.response = response; + + this.gateUrl = "https://gw.tenpay.com/gateway/pay.htm"; + this.key = ""; + this.parameters = new TreeMap(); + this.debugInfo = ""; + }*/ + + /** + * 锟斤拷锟届函锟斤拷 + * @param request + * @param response + */ + public RequestHandler(HttpServletRequest request, HttpServletResponse response) { + this.request = request; + this.response = response; + + this.gateUrl = "https://gw.tenpay.com/gateway/pay.htm"; + this.key = ""; + this.parameters = new TreeMap(); + this.debugInfo = ""; + } + + /** + * 锟斤拷始锟斤拷锟斤拷锟斤拷 + */ + public void init() { + // nothing to do + } + + /** + * 锟斤拷取锟斤拷诘锟街�,锟斤拷锟斤拷锟斤拷锟街� + */ + public String getGateUrl() { + return gateUrl; + } + + /** + * 锟斤拷锟斤拷锟斤拷诘锟街�,锟斤拷锟斤拷锟斤拷锟街� + */ + public void setGateUrl(String gateUrl) { + this.gateUrl = gateUrl; + } + + /** + * 锟斤拷取锟斤拷钥 + */ + public String getKey() { + return key; + } + + /** + * 绉橀挜 + */ + public void setKey(String key) { + this.key = key; + } + + /** + * 锟斤拷取锟斤拷锟斤拷值 + * + * @param parameter + * 锟斤拷锟斤拷锟斤拷锟� + * @return String + */ + public String getParameter(String parameter) { + String s = (String) this.parameters.get(parameter); + return (null == s) ? "" : s; + } + + /** + * 锟斤拷锟矫诧拷锟斤拷值 + * + * @param parameter + * 锟斤拷锟斤拷锟斤拷锟� + * @param parameterValue + * 锟斤拷锟斤拷值 + */ + @SuppressWarnings("unchecked") + public void setParameter(String parameter, String parameterValue) { + String v = ""; + if (null != parameterValue) { + v = parameterValue.trim(); + } + this.parameters.put(parameter, v); + } + + /** + * 锟斤拷锟斤拷锟斤拷锟叫的诧拷锟斤拷 + * + * @return SortedMap + */ + @SuppressWarnings("rawtypes") + public SortedMap getAllParameters() { + return this.parameters; + } + + /** + * 锟斤拷取debug锟斤拷息 + */ + public String getDebugInfo() { + return debugInfo; + } + + /** + * 锟斤拷取锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷URL + * + * @return String + * @throws UnsupportedEncodingException + */ + /*@SuppressWarnings("rawtypes") + public String getRequestURL() throws UnsupportedEncodingException { + + this.createSign(); + + StringBuffer sb = new StringBuffer(); + String enc = TenpayUtil.getCharacterEncoding(this.request, + this.response); + Set es = this.parameters.entrySet(); + Iterator it = es.iterator(); + while (it.hasNext()) { + Map.Entry entry = (Map.Entry) it.next(); + String k = (String) entry.getKey(); + String v = (String) entry.getValue(); + + if (!"spbill_create_ip".equals(k)) { + sb.append(k + "=" + URLEncoder.encode(v, enc) + "&"); + } else { + sb.append(k + "=" + v.replace(".", "%2E") + "&"); + + } + } + + // 去锟斤拷锟斤拷锟揭伙拷锟�& + String reqPars = sb.substring(0, sb.lastIndexOf("&")); + + return this.getGateUrl() + "?" + reqPars; + + }*/ + + /** + * 锟斤拷取锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷URL + * @return String + * @throws UnsupportedEncodingException + */ + public String getRequestURL() throws UnsupportedEncodingException { + + this.createSign(); + + StringBuffer sb = new StringBuffer(); + String enc = TenpayUtil.getCharacterEncoding(this.request, this.response); + Set es = this.parameters.entrySet(); + Iterator it = es.iterator(); + while(it.hasNext()) { + Map.Entry entry = (Map.Entry)it.next(); + String k = (String)entry.getKey(); + String v = (String)entry.getValue(); + + if(!"spbill_create_ip".equals(k)) { + sb.append(k + "=" + URLEncoder.encode(v, enc) + "&"); + } else { + sb.append(k + "=" + v.replace(".", "%2E") + "&"); + + + } + } + + //去锟斤拷锟斤拷锟揭伙拷锟�& + String reqPars = sb.substring(0, sb.lastIndexOf("&")); + + return this.getGateUrl() + "?" + reqPars; + + } + + public void doSend() throws UnsupportedEncodingException, IOException { + this.response.sendRedirect(this.getRequestURL()); + } + + /** + * TODO 鐢熸垚绛惧悕 + */ + @SuppressWarnings("rawtypes") + public String createSign() { + StringBuffer sb = new StringBuffer(); + Set es = this.parameters.entrySet(); + Iterator it = es.iterator(); + while (it.hasNext()) { + Map.Entry entry = (Map.Entry) it.next(); + String k = (String) entry.getKey(); + String v = (String) entry.getValue(); + if (null != v && !"".equals(v) && !"sign".equals(k) + && !"key".equals(k)) { + sb.append(k + "=" + v + "&"); + } + } + sb.append("key=" + this.getKey()); +System.out.println("sb="+sb); + String enc = TenpayUtil.getCharacterEncoding(this.request, + this.response); + String sign = MD5Util.MD5Encode(sb.toString(), enc).toUpperCase(); + + this.setParameter("sign", sign); + + // debug锟斤拷息 + this.setDebugInfo(sb.toString() + " => sign:" + sign); + + return sign; + } + + /** + * 锟斤拷锟斤拷debug锟斤拷息 + */ + protected void setDebugInfo(String debugInfo) { + this.debugInfo = debugInfo; + } + + protected HttpServletRequest getHttpServletRequest() { + return this.request; + } + + protected HttpServletResponse getHttpServletResponse() { + return this.response; + } + +} diff --git a/hx_common/src/main/java/com/hx/mp/util/ResponseHandler.java b/hx_common/src/main/java/com/hx/mp/util/ResponseHandler.java new file mode 100644 index 0000000..4a573a3 --- /dev/null +++ b/hx_common/src/main/java/com/hx/mp/util/ResponseHandler.java @@ -0,0 +1,225 @@ +package com.hx.mp.util; + +import java.io.IOException; +import java.io.PrintWriter; +import java.io.UnsupportedEncodingException; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.SortedMap; +import java.util.TreeMap; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * 应锟斤拷锟斤拷锟斤拷 应锟斤拷锟斤拷锟斤拷坛写锟斤拷啵拷锟叫磇sTenpaySign锟斤拷锟斤拷锟斤拷锟缴★拷 + *JX + *linhan + */ +public class ResponseHandler { + + /** 锟斤拷钥 */ + private String key; + + /** 应锟斤拷牟锟斤拷锟� */ + @SuppressWarnings("rawtypes") + private SortedMap parameters; + + /** debug锟斤拷息 */ + private String debugInfo; + + private HttpServletRequest request; + + private HttpServletResponse response; + + private String uriEncoding; + + /** + * 锟斤拷锟届函锟斤拷 + * + * @param request + * @param response + */ + @SuppressWarnings("rawtypes") + public ResponseHandler(HttpServletRequest request, + HttpServletResponse response) { + this.request = request; + this.response = response; + + this.key = ""; + this.parameters = new TreeMap(); + this.debugInfo = ""; + + this.uriEncoding = ""; + + Map m = this.request.getParameterMap(); + Iterator it = m.keySet().iterator(); + while (it.hasNext()) { + String k = (String) it.next(); + String v = ((String[]) m.get(k))[0]; + this.setParameter(k, v); + } + + } + + /** + * 锟斤拷取锟斤拷钥 + */ + public String getKey() { + return key; + } + + /** + * 锟斤拷锟斤拷锟斤拷钥 + */ + public void setKey(String key) { + this.key = key; + } + + /** + * 锟斤拷取锟斤拷锟斤拷值 + * + * @param parameter + * 锟斤拷锟斤拷锟斤拷锟� + * @return String + */ + public String getParameter(String parameter) { + String s = (String) this.parameters.get(parameter); + return (null == s) ? "" : s; + } + + /** + * 锟斤拷锟矫诧拷锟斤拷值 + * + * @param parameter + * 锟斤拷锟斤拷锟斤拷锟� + * @param parameterValue + * 锟斤拷锟斤拷值 + */ + @SuppressWarnings("unchecked") + public void setParameter(String parameter, String parameterValue) { + String v = ""; + if (null != parameterValue) { + v = parameterValue.trim(); + } + this.parameters.put(parameter, v); + } + + /** + * 锟斤拷锟斤拷锟斤拷锟叫的诧拷锟斤拷 + * + * @return SortedMap + */ + @SuppressWarnings("rawtypes") + public SortedMap getAllParameters() { + return this.parameters; + } + + /** + * 锟角凤拷聘锟酵ㄇ╋拷锟�,锟斤拷锟斤拷锟斤拷:锟斤拷锟斤拷锟斤拷锟斤拷锟絘-z锟斤拷锟斤拷,锟斤拷锟斤拷锟斤拷值锟侥诧拷锟斤拷渭锟角╋拷锟� + * + * @return boolean + */ + @SuppressWarnings("rawtypes") + public boolean isTenpaySign() { + StringBuffer sb = new StringBuffer(); + Set es = this.parameters.entrySet(); + Iterator it = es.iterator(); + while (it.hasNext()) { + Map.Entry entry = (Map.Entry) it.next(); + String k = (String) entry.getKey(); + String v = (String) entry.getValue(); + if (!"sign".equals(k) && null != v && !"".equals(v)) { + sb.append(k + "=" + v + "&"); + } + } + + sb.append("key=" + this.getKey()); + + // 锟斤拷锟秸� + String enc = TenpayUtil.getCharacterEncoding(this.request, + this.response); + String sign = MD5Util.MD5Encode(sb.toString(), enc).toLowerCase(); + + String tenpaySign = this.getParameter("sign").toLowerCase(); + + // debug锟斤拷息 + this.setDebugInfo(sb.toString() + " => sign:" + sign + " tenpaySign:" + + tenpaySign); + + return tenpaySign.equals(sign); + } + + /** + * 锟斤拷锟截达拷锟斤拷锟斤拷锟狡革拷通锟斤拷锟斤拷锟斤拷锟斤拷 + * + * @param msg + * : Success or fail锟斤拷 + * @throws IOException + */ + public void sendToCFT(String msg) throws IOException { + String strHtml = msg; + PrintWriter out = this.getHttpServletResponse().getWriter(); + out.println(strHtml); + out.flush(); + out.close(); + + } + + /** + * 锟斤拷取uri锟斤拷锟斤拷 + * + * @return String + */ + public String getUriEncoding() { + return uriEncoding; + } + + /** + * 锟斤拷锟斤拷uri锟斤拷锟斤拷 + * + * @param uriEncoding + * @throws UnsupportedEncodingException + */ + @SuppressWarnings("rawtypes") + public void setUriEncoding(String uriEncoding) + throws UnsupportedEncodingException { + if (!"".equals(uriEncoding.trim())) { + this.uriEncoding = uriEncoding; + + // 锟斤拷锟斤拷转锟斤拷 + String enc = TenpayUtil.getCharacterEncoding(request, response); + Iterator it = this.parameters.keySet().iterator(); + while (it.hasNext()) { + String k = (String) it.next(); + String v = this.getParameter(k); + v = new String(v.getBytes(uriEncoding.trim()), enc); + this.setParameter(k, v); + } + } + } + + /** + * 锟斤拷取debug锟斤拷息 + */ + public String getDebugInfo() { + return debugInfo; + } + + /** + * 锟斤拷锟斤拷debug锟斤拷息 + */ + protected void setDebugInfo(String debugInfo) { + this.debugInfo = debugInfo; + } + + protected HttpServletRequest getHttpServletRequest() { + return this.request; + } + + protected HttpServletResponse getHttpServletResponse() { + return this.response; + } + +} diff --git a/hx_common/src/main/java/com/hx/mp/util/TenpayHttpClient.java b/hx_common/src/main/java/com/hx/mp/util/TenpayHttpClient.java new file mode 100644 index 0000000..24ad9be --- /dev/null +++ b/hx_common/src/main/java/com/hx/mp/util/TenpayHttpClient.java @@ -0,0 +1,559 @@ +package com.hx.mp.util; + +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.UnrecoverableKeyException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.SortedMap; + +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocketFactory; + +import org.dom4j.Document; +import org.dom4j.DocumentHelper; +import org.dom4j.Element; + +/** + * 锟狡革拷通http锟斤拷锟斤拷https锟斤拷锟斤拷通锟脚客伙拷锟斤拷<br/> + * ========================================================================<br/> + * api说锟斤拷锟斤拷<br/> + * setReqContent($reqContent),锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟捷o拷锟斤拷锟斤拷post锟斤拷get锟斤拷锟斤拷锟斤拷get锟斤拷式锟结供<br/> + * getResContent(), 锟斤拷取应锟斤拷锟斤拷锟斤拷<br/> + * setMethod(method),锟斤拷锟斤拷锟斤拷锟襟方凤拷,post锟斤拷锟斤拷get<br/> + * getErrInfo(),锟斤拷取锟斤拷锟斤拷锟斤拷息<br/> + * setCertInfo(certFile, certPasswd),锟斤拷锟斤拷证锟介,双锟斤拷https时锟斤拷要使锟斤拷<br/> + * setCaInfo(caFile), 锟斤拷锟斤拷CA锟斤拷锟斤拷式未pem锟斤拷锟斤拷锟斤拷锟斤拷锟津不硷拷锟�<br/> + * setTimeOut(timeOut)锟斤拷 锟斤拷锟矫筹拷时时锟戒,锟斤拷位锟斤拷<br/> + * getResponseCode(), 取锟斤拷锟截碉拷http状态锟斤拷<br/> + * call(),锟斤拷锟斤拷锟斤拷媒涌锟�<br/> + * getCharset()/setCharset(),锟街凤拷锟斤拷锟�<br/> + * + * ========================================================================<br/> + * + */ +public class TenpayHttpClient { + + private static final String USER_AGENT_VALUE = + "Mozilla/4.0 (compatible; MSIE 6.0; Windows XP)"; + + private static final String JKS_CA_FILENAME = + "tenpay_cacert.jks"; + + private static final String JKS_CA_ALIAS = "tenpay"; + + private static final String JKS_CA_PASSWORD = ""; + + /** ca证锟斤拷锟侥硷拷 */ + private File caFile; + + /** 证锟斤拷锟侥硷拷 */ + private File certFile; + + /** 证锟斤拷锟斤拷锟斤拷 */ + private String certPasswd; + + /** 锟斤拷锟斤拷锟斤拷锟捷o拷锟斤拷锟斤拷post锟斤拷get锟斤拷锟斤拷锟斤拷get锟斤拷式锟结供 */ + private String reqContent; + + /** 应锟斤拷锟斤拷锟斤拷 */ + private String resContent; + + /** 锟斤拷锟襟方凤拷 */ + private String method; + + /** 锟斤拷锟斤拷锟斤拷息 */ + private String errInfo; + + /** 锟斤拷时时锟斤拷,锟斤拷锟斤拷为锟斤拷位 */ + private int timeOut; + + /** http应锟斤拷锟斤拷锟� */ + private int responseCode; + + /** 锟街凤拷锟斤拷锟� */ + private String charset; + + private InputStream inputStream; + + private RequestHandler reqHandler;//鏂逛究鍙栧�兼墍鐢�(quan) + + /*public TenpayHttpClient() { + this.caFile = null; + this.certFile = null; + this.certPasswd = ""; + + this.reqContent = ""; + this.resContent = ""; + this.method = "POST"; + this.errInfo = ""; + this.timeOut = 30;//30锟斤拷 + + this.responseCode = 0; + this.charset = "UTF-8"; + + this.inputStream = null; + }*/ + + public TenpayHttpClient() { + this.caFile = null; + this.certFile = null; + this.certPasswd = ""; + + this.reqContent = ""; + this.resContent = ""; + this.method = "POST"; + this.errInfo = ""; + this.timeOut = 30;//30锟斤拷 + + this.responseCode = 0; + this.charset = "UTF-8"; + + this.inputStream = null; + } + + /** + * 锟斤拷锟斤拷证锟斤拷锟斤拷息 + * @param certFile 证锟斤拷锟侥硷拷 + * @param certPasswd 证锟斤拷锟斤拷锟斤拷 + */ + public void setCertInfo(File certFile, String certPasswd) { + this.certFile = certFile; + this.certPasswd = certPasswd; + } + + /** + * 锟斤拷锟斤拷ca + * @param caFile + */ + public void setCaInfo(File caFile) { + this.caFile = caFile; + } + + /** + * 锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷 + * @param reqContent 锟斤拷锟斤拷锟斤拷锟斤拷 + */ + public void setReqContent(String reqContent) { + this.reqContent = reqContent; + } + + /** + * 锟斤拷取锟斤拷锟斤拷锟斤拷锟� + * @return String + * @throws IOException + */ + public String getResContent() { + try { + this.doResponse(); + } catch (IOException e) { + this.errInfo = e.getMessage(); + //return ""; + } + + return this.resContent; + } + + /** + * 锟斤拷锟斤拷锟斤拷锟襟方凤拷post锟斤拷锟斤拷get + * @param method 锟斤拷锟襟方凤拷post/get + */ + public void setMethod(String method) { + this.method = method; + } + + /** + * 锟斤拷取锟斤拷锟斤拷锟斤拷息 + * @return String + */ + public String getErrInfo() { + return this.errInfo; + } + + /** + * 锟斤拷锟矫筹拷时时锟斤拷,锟斤拷锟斤拷为锟斤拷位 + * @param timeOut 锟斤拷时时锟斤拷,锟斤拷锟斤拷为锟斤拷位 + */ + public void setTimeOut(int timeOut) { + this.timeOut = timeOut; + } + + /** + * 锟斤拷取http状态锟斤拷 + * @return int + */ + public int getResponseCode() { + return this.responseCode; + } + + /** + * 执锟斤拷http锟斤拷锟矫★拷true:锟缴癸拷 false:失锟斤拷 + * @return boolean + */ +/* public boolean call() { + + boolean isRet = false; + + + //http + if(null == this.caFile && null == this.certFile) { + System.out.println("娌℃湁CA"); + try { + this.callHttp(); + isRet = true; + } catch (IOException e) { + this.errInfo = e.getMessage(); + } + return isRet; + } + + //https + try { + this.callHttps(); + isRet = true; + } catch (UnrecoverableKeyException e) { + this.errInfo = e.getMessage(); + } catch (KeyManagementException e) { + this.errInfo = e.getMessage(); + } catch (CertificateException e) { + this.errInfo = e.getMessage(); + } catch (KeyStoreException e) { + this.errInfo = e.getMessage(); + } catch (NoSuchAlgorithmException e) { + this.errInfo = e.getMessage(); + } catch (IOException e) { + this.errInfo = e.getMessage(); + } + + return isRet; + + }*/ + + /** + * 执锟斤拷http锟斤拷锟矫★拷true:锟缴癸拷 false:失锟斤拷 + * @return boolean + */ + public boolean call() { + + boolean isRet = false; + + + //http + if(null == this.caFile && null == this.certFile) { + System.out.println("娌℃湁CA"); + try { + this.callHttp(); + isRet = true; + } catch (IOException e) { + this.errInfo = e.getMessage(); + } + return isRet; + } + + //https + try { + this.callHttps(); + isRet = true; + } catch (UnrecoverableKeyException e) { + this.errInfo = e.getMessage(); + } catch (KeyManagementException e) { + this.errInfo = e.getMessage(); + } catch (CertificateException e) { + this.errInfo = e.getMessage(); + } catch (KeyStoreException e) { + this.errInfo = e.getMessage(); + } catch (NoSuchAlgorithmException e) { + this.errInfo = e.getMessage(); + } catch (IOException e) { + this.errInfo = e.getMessage(); + } + + return isRet; + + } + + protected void callHttp() throws IOException { + + if("POST".equals(this.method.toUpperCase())) { + String url = HttpClientUtil.getURL(this.reqContent); + System.out.println("tenpayHttpClient:url:"+url); + //String queryString = HttpClientUtil.getQueryString(this.reqContent); + //byte[] postData = queryString.getBytes(this.charset); + + String queryString = createXmlPosData(); + byte[] postData = queryString.getBytes(this.charset); + this.httpPostMethod(url, postData); + + return ; + } + + this.httpGetMethod(this.reqContent); + + } + + protected void callHttps() throws IOException, CertificateException, + KeyStoreException, NoSuchAlgorithmException, + UnrecoverableKeyException, KeyManagementException { + // ca目录 + String caPath = this.caFile.getParent(); + + System.out.println("caPath:"+caPath); + File jksCAFile = new File(caPath + "/" + + TenpayHttpClient.JKS_CA_FILENAME); + if (!jksCAFile.isFile()) { + X509Certificate cert = (X509Certificate) HttpClientUtil + .getCertificate(this.caFile); + + FileOutputStream out = new FileOutputStream(jksCAFile); + + // store jks file + HttpClientUtil.storeCACert(cert, TenpayHttpClient.JKS_CA_ALIAS, + TenpayHttpClient.JKS_CA_PASSWORD, out); + + out.close(); + + } + + FileInputStream trustStream = new FileInputStream(jksCAFile); + FileInputStream keyStream = new FileInputStream(this.certFile); + + SSLContext sslContext = HttpClientUtil.getSSLContext(trustStream, + TenpayHttpClient.JKS_CA_PASSWORD, keyStream, this.certPasswd); + + //锟截憋拷锟斤拷 + keyStream.close(); + trustStream.close(); + + if("POST".equals(this.method.toUpperCase())) { + String url = HttpClientUtil.getURL(this.reqContent); + + //鍘熸湰鏄洿鎺ュ弬鏁拌浆涓哄瓧鑺傛暟缁勭殑锛岀幇鍦ㄧ粍鎷紉ml + //String queryString = HttpClientUtil.getQueryString(this.reqContent);//鑾峰彇閾炬帴涓嬮潰鐨勫唴瀹� + //byte[] postData = queryString.getBytes(this.charset);//鎶婂弬鏁拌浆涓哄瓧鑺傛暟缁� + + //鍏堣幏鍙栧弬鏁� + String queryString = createXmlPosData(); + + byte[] postData = queryString.getBytes(this.charset);//鎶婂弬鏁拌浆涓哄瓧鑺傛暟缁� + + this.httpsPostMethod(url, postData, sslContext); + + return ; + } + + this.httpsGetMethod(this.reqContent, sslContext); + + } + + /** + * 锟斤拷http post锟斤拷式通锟斤拷 + * @param url + * @param postData + * @throws IOException + */ + protected void httpPostMethod(String url, byte[] postData) + throws IOException { + + HttpURLConnection conn = HttpClientUtil.getHttpURLConnection(url); + + this.doPost(conn, postData); + } + + /** + * 锟斤拷http get锟斤拷式通锟斤拷 + * + * @param url + * @throws IOException + */ + protected void httpGetMethod(String url) throws IOException { + + HttpURLConnection httpConnection = + HttpClientUtil.getHttpURLConnection(url); + + this.setHttpRequest(httpConnection); + + httpConnection.setRequestMethod("GET"); + + this.responseCode = httpConnection.getResponseCode(); + + this.inputStream = httpConnection.getInputStream(); + + } + + /** + * 锟斤拷https get锟斤拷式通锟斤拷 + * @param url + * @param sslContext + * @throws IOException + */ + protected void httpsGetMethod(String url, SSLContext sslContext) + throws IOException { + + SSLSocketFactory sf = sslContext.getSocketFactory(); + + HttpsURLConnection conn = HttpClientUtil.getHttpsURLConnection(url); + + conn.setSSLSocketFactory(sf); + + this.doGet(conn); + + } + + //鎻愪氦https post 鏁版嵁 s + protected void httpsPostMethod(String url, byte[] postData, + SSLContext sslContext) throws IOException { + + SSLSocketFactory sf = sslContext.getSocketFactory(); + + HttpsURLConnection conn = HttpClientUtil.getHttpsURLConnection(url); + + conn.setSSLSocketFactory(sf); + + this.doPost(conn, postData); + + } + + /** + * 锟斤拷锟斤拷http锟斤拷锟斤拷默锟斤拷锟斤拷锟斤拷 + * @param httpConnection + */ + protected void setHttpRequest(HttpURLConnection httpConnection) { + + //锟斤拷锟斤拷锟斤拷锟接筹拷时时锟斤拷 + httpConnection.setConnectTimeout(this.timeOut * 1000); + + //User-Agent + httpConnection.setRequestProperty("User-Agent", + TenpayHttpClient.USER_AGENT_VALUE); + + //锟斤拷使锟矫伙拷锟斤拷 + httpConnection.setUseCaches(false); + + //锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟� + httpConnection.setDoInput(true); + httpConnection.setDoOutput(true); + + } + + /** + * 锟斤拷锟斤拷应锟斤拷 + * @throws IOException + */ + protected void doResponse() throws IOException { + + if(null == this.inputStream) { + return; + } + + //锟斤拷取应锟斤拷锟斤拷锟斤拷 + this.resContent=HttpClientUtil.InputStreamTOString(this.inputStream,this.charset); + + // System.out.println("tenpayHttpClinet:385:"+resContent); + //锟截憋拷锟斤拷锟斤拷锟斤拷 + this.inputStream.close(); + + } + + /** + * post锟斤拷式锟斤拷锟斤拷 + * @param conn + * @param postData + * @throws IOException + */ + protected void doPost(HttpURLConnection conn, byte[] postData) + throws IOException { + + // 锟斤拷post锟斤拷式通锟斤拷 + conn.setRequestMethod("POST"); + + // 锟斤拷锟斤拷锟斤拷锟斤拷默锟斤拷锟斤拷锟斤拷 + this.setHttpRequest(conn); + + // Content-Type + conn.setRequestProperty("Content-Type", + "application/x-www-form-urlencoded"); + + BufferedOutputStream out = new BufferedOutputStream(conn + .getOutputStream()); + + final int len = 1024; // 1KB + HttpClientUtil.doOutput(out, postData, len); + + // 锟截憋拷锟斤拷 + out.close(); + + // 锟斤拷取锟斤拷应锟斤拷锟斤拷状态锟斤拷 + this.responseCode = conn.getResponseCode(); + + // 锟斤拷取应锟斤拷锟斤拷锟斤拷锟斤拷 + this.inputStream = conn.getInputStream(); + + } + + /** + * get锟斤拷式锟斤拷锟斤拷 + * @param conn + * @throws IOException + */ + protected void doGet(HttpURLConnection conn) throws IOException { + + //锟斤拷GET锟斤拷式通锟斤拷 + conn.setRequestMethod("GET"); + + //锟斤拷锟斤拷锟斤拷锟斤拷默锟斤拷锟斤拷锟斤拷 + this.setHttpRequest(conn); + + //锟斤拷取锟斤拷应锟斤拷锟斤拷状态锟斤拷 + this.responseCode = conn.getResponseCode(); + + //锟斤拷取应锟斤拷锟斤拷锟斤拷锟斤拷 + this.inputStream = conn.getInputStream(); + } + + public void setRequestHandler(RequestHandler reqHandler) { + this.reqHandler = reqHandler; + } + + + //缁勫缓xml鏍煎紡浼犻�掑弬鏁� + @SuppressWarnings({ "rawtypes", "unused" }) + public String createXmlPosData(){ + //鍏堣幏鍙栧弬鏁� + Document document = DocumentHelper.createDocument(); + Element root = document.addElement("xml"); + + if(reqHandler==null)throw new RuntimeException("璇峰厛璁惧叆reqHandler"); + + SortedMap parameters = reqHandler.getAllParameters(); + Set es = reqHandler.getAllParameters().entrySet(); + Iterator it = es.iterator(); + while(it.hasNext()) { + Map.Entry entry = (Map.Entry)it.next(); + String k = (String)entry.getKey(); + String v = (String)entry.getValue(); + + Element ToUserName = root.addElement(k); + ToUserName.addText(v); + } + + String queryString = document.asXML();//杞负String + + queryString = queryString.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "").trim(); + + System.out.println("xml锛�"+queryString); + return queryString; + } + +} diff --git a/hx_common/src/main/java/com/hx/mp/util/TenpayUtil.java b/hx_common/src/main/java/com/hx/mp/util/TenpayUtil.java new file mode 100644 index 0000000..8d6758a --- /dev/null +++ b/hx_common/src/main/java/com/hx/mp/util/TenpayUtil.java @@ -0,0 +1,132 @@ +package com.hx.mp.util; + +import java.text.SimpleDateFormat; +import java.util.Date; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + + +public class TenpayUtil { + + /** + * 锟窖讹拷锟斤拷转锟斤拷锟斤拷锟街凤拷 + * @param obj + * @return String 转锟斤拷锟斤拷锟街凤拷,锟斤拷锟斤拷锟斤拷为null,锟津返回匡拷锟街凤拷. + */ + public static String toString(Object obj) { + if(obj == null) + return ""; + + return obj.toString(); + } + + /** + * 锟窖讹拷锟斤拷转锟斤拷为int锟斤拷值. + * + * @param obj + * 锟斤拷锟斤拷锟街的讹拷锟斤拷. + * @return int 转锟斤拷锟斤拷锟斤拷锟街�,锟皆诧拷锟斤拷转锟斤拷锟侥讹拷锟襟返伙拷0锟斤拷 + */ + public static int toInt(Object obj) { + int a = 0; + try { + if (obj != null) + a = Integer.parseInt(obj.toString()); + } catch (Exception e) { + + } + return a; + } + + /** + * 锟斤拷取锟斤拷前时锟斤拷 yyyyMMddHHmmss + * @return String + */ + public static String getCurrTime() { + Date now = new Date(); + SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss"); + String s = outFormat.format(now); + return s; + } + + /** + * 锟斤拷取锟斤拷前锟斤拷锟斤拷 yyyyMMdd + * @param date + * @return String + */ + public static String formatDate(Date date) { + SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd"); + String strDate = formatter.format(date); + return strDate; + } + + /** + * 取锟斤拷一锟斤拷指锟斤拷锟斤拷锟饺达拷小锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟�. + * + * @param length + * int 锟借定锟斤拷取锟斤拷锟斤拷锟斤拷锟侥筹拷锟饺★拷length小锟斤拷11 + * @return int 锟斤拷锟斤拷锟斤拷傻锟斤拷锟斤拷锟斤拷 + */ + public static int buildRandom(int length) { + int num = 1; + double random = Math.random(); + if (random < 0.1) { + random = random + 0.1; + } + for (int i = 0; i < length; i++) { + num = num * 10; + } + return (int) ((random * num)); + } + + /** + * 锟斤拷取锟斤拷锟斤拷锟街凤拷 + * @param request + * @param response + * @return String + */ + public static String getCharacterEncoding(HttpServletRequest request, + HttpServletResponse response) { + + if(null == request || null == response) { + return "utf-8"; + } + + String enc = request.getCharacterEncoding(); + if(null == enc || "".equals(enc)) { + enc = response.getCharacterEncoding(); + } + + if(null == enc || "".equals(enc)) { + enc = "utf-8"; + } + + return enc; + } + + /** + * 锟斤拷取unix时锟戒,锟斤拷1970-01-01 00:00:00锟斤拷始锟斤拷锟斤拷锟斤拷 + * @param date + * @return long + */ + public static long getUnixTime(Date date) { + if( null == date ) { + return 0; + } + + return date.getTime()/1000; + } + + /** + * 时锟斤拷转锟斤拷锟斤拷锟街凤拷 + * @param date 时锟斤拷 + * @param formatType 锟斤拷式锟斤拷锟斤拷锟斤拷 + * @return String + */ + public static String date2String(Date date, String formatType) { + SimpleDateFormat sdf = new SimpleDateFormat(formatType); + return sdf.format(date); + } + +} diff --git a/hx_common/src/main/java/com/hx/mp/util/WXPayUtil.java b/hx_common/src/main/java/com/hx/mp/util/WXPayUtil.java new file mode 100644 index 0000000..f363886 --- /dev/null +++ b/hx_common/src/main/java/com/hx/mp/util/WXPayUtil.java @@ -0,0 +1,622 @@ +package com.hx.mp.util; + +import com.hx.exception.ServiceException; +import com.hx.util.SimpleTool; +import com.hx.util.StringUtils; +import net.sf.json.JSONObject; +import org.apache.commons.io.IOUtils; +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.ssl.SSLContexts; +import org.apache.http.util.EntityUtils; +import org.dom4j.Document; +import org.dom4j.Element; +import org.dom4j.io.SAXReader; + +import javax.net.ssl.SSLContext; +import javax.servlet.http.HttpServletRequest; +import java.io.File; +import java.io.FileInputStream; +import java.security.KeyStore; +import java.util.*; + + +/** 寰俊鏀粯/閫�娆� + * @author ChenJiaHe + */ +public class WXPayUtil { + + // 閫�娆炬帴鍙h繛鎺� + private static final String REFUND_URL = "https://api.mch.weixin.qq.com/secapi/pay/refund"; + /**鏌ヨ璁㈠崟閾炬帴*/ + @SuppressWarnings("unused") + private static final String QUERY_URL = "https://api.mch.weixin.qq.com/pay/orderquery"; + + /**鍚屾剰涓嬪崟閾炬帴*/ + private static final String FIRST_ORDER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder"; + + // 浼佷笟浠樻 + private static final String CORP_PAY_URL = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers"; + + + /** 浼佷笟浠樻*/ + public static JSONObject qdCorpPay(String appId, String orderNo, String certPath, String mchid, String mchKey, String openId, String payFee, String desc) + throws Exception { + + SortedMap<Object, Object> parameters = new TreeMap<Object, Object>(); + parameters.put("mch_appid", appId); + parameters.put("mchid", mchid); + parameters.put("partner_trade_no", orderNo); + parameters.put("nonce_str", UUID.randomUUID().toString().substring(0, 30)); + parameters.put("openid", openId); + parameters.put("check_name", "NO_CHECK"); + parameters.put("amount", payFee); + parameters.put("spbill_create_ip", "8.8.8.8"); + parameters.put("desc", desc); + + String sign = WXSignUtils.createSign("UTF-8", parameters, mchKey); + + parameters.put("sign", sign); + String xmlInfo = HttpXmlUtils.transferXml(parameters); + + JSONObject returnObj = new JSONObject(); + + try { + CloseableHttpResponse response = HttpUtil.Post(CORP_PAY_URL, xmlInfo, true, certPath, mchid); + String transfersXml = EntityUtils.toString(response.getEntity(), "utf-8"); + // System.out.println("娓犻亾绔紒涓氫粯娆撅細" + transfersXml); + Map<String, String> transferMap = HttpXmlUtils.parseRefundXml(transfersXml); + boolean bl = false; + if (transferMap.size() > 0) { + if (transferMap.get("return_code").equals("SUCCESS")) { + // 閫氳鎴愬姛 + if (transferMap.get("result_code").equals("SUCCESS")) { + // 鎴愬姛闇�瑕佽繘琛岀殑閫昏緫鎿嶄綔 + returnObj.put("status", "suc"); + } else { + bl = true; + returnObj.put("status", "fail"); + returnObj.put("errMsg", transferMap.get("err_code") + "|" + transferMap.get("err_code_des")); + } + } else { + bl = true; + // 閫氳涓嶆垚鍔� + returnObj.put("status", "fail"); + returnObj.put("errMsg", transferMap.get("return_msg")); + } + } else { + bl = true; + returnObj.put("status", "fail"); + returnObj.put("errMsg", "杩斿洖涓虹┖"); + } + if (bl) { + System.out.println("浼佷笟浠樻澶辫触锛�" + transfersXml); + } + } catch (Exception e) { + e.printStackTrace(); + returnObj.put("status", "fail"); + returnObj.put("errMsg", e.getMessage()); + } + + return returnObj; + } + + /**缁熶竴鏀粯 + * @param request 鏂规硶鑾峰彇 + * @param appId 灏忕▼搴忓彿 + * @param partner 鍟嗘埛鍙� + * @param key 绉橀挜 + * @param notifyUrl 鍥炶皟閾炬帴 + * @param out_trade_no 璁㈠崟鍙� + * @param body 鍟嗗搧鎻忚堪 + * @param total_fee 鏀粯閲戦 + * @param openid 鐢ㄦ埛openId + * @param attach 闄勫甫鏁版嵁鍖� + * @param notifyUrl 鍥炶皟閫氱煡鍦板潃 + * @param trade_type 浜ゆ槗绫诲瀷 + * @return JSON status = "SUC"涓烘垚鍔� + */ + public static JSONObject unifiedPay(HttpServletRequest request,String appId,String partner,String key,String notifyUrl,String out_trade_no, String body, String total_fee, String openid, + String attach,String trade_type) throws Exception { + + if (!SimpleTool.checkNotNull(notifyUrl)) { + throw new ServiceException("鏀粯鍔熻兘鏁呴殰锛�"); + } + + // 鍒涘缓鏌ヨ璇锋眰瀵硅薄 + RequestHandler reqHandler = new RequestHandler(null, null); + // 閫氫俊瀵硅薄 + TenpayHttpClient httpClient = new TenpayHttpClient(); + // 搴旂瓟瀵硅薄 + ClientResponseHandler resHandler = new ClientResponseHandler(); + + // ----------------------------- + // 璁剧疆璇锋眰鍙傛暟 + // ----------------------------- + // reqHandler.init(); + reqHandler.setKey(key); + reqHandler.setGateUrl(FIRST_ORDER_URL);// 璇锋眰URL + + // ----------------------------- + // 璁剧疆鎺ュ彛鍙傛暟(sign鍚庡彴鑷姩鐢熸垚) + // ----------------------------- + reqHandler.setParameter("appid", appId); // 鍏紬鍙�/灏忕▼搴� + reqHandler.setParameter("mch_id", partner); // 鍟嗘埛鍙� + reqHandler.setParameter("nonce_str", SimpleTool.getUUIDName().substring(0, 30));// 闅忔満涔辩爜 + reqHandler.setParameter("body", body);// 鍟嗗搧鎻忚堪 + reqHandler.setParameter("out_trade_no", out_trade_no);// 鍟嗘埛璁㈠崟鍙� + reqHandler.setParameter("total_fee", total_fee);// 鎬婚噾棰� + reqHandler.setParameter("spbill_create_ip", "8.8.8.8");// 缁堢IP + reqHandler.setParameter("notify_url",notifyUrl);// 閫氱煡鍦板潃 + reqHandler.setParameter("trade_type", trade_type);// 浜ゆ槗绫诲瀷 + // JSAPI锛孨ATIVE锛孉PP + reqHandler.setParameter("openid", openid);// openId + reqHandler.setParameter("attach", attach);// 闄勫甫鏁版嵁鍖� + + // ----------------------------- + // 璁剧疆閫氫俊鍙傛暟 + // ----------------------------- + // 璁剧疆璇锋眰杩斿洖鐨勭瓑寰呮椂闂� + httpClient.setTimeOut(5); + + // 璁剧疆ca璇佷功 + // httpClient.setCaInfo(new File(CA_PATH)); + + // 璁剧疆涓汉(鍟嗘埛)璇佷功 + // httpClient.setCertInfo(new File(CERT_PATH), CERT_PWD); + + // 璁剧疆鍙戦�佺被鍨婸OST + httpClient.setMethod("POST"); + + // 璁剧疆璇锋眰鍐呭(鐢熸垚sign) + String requestUrl = reqHandler.getRequestURL();// 缁勬嫾https://www.baidu.com?a=x&b=xx + + httpClient.setReqContent(requestUrl);// https://www.baidu.com?a=x&b=xx + String rescontent = "null"; + + httpClient.setRequestHandler(reqHandler);// 鎶婂鐞嗗璞★紝鍍忔槸鍙傛暟鍚勭涓滆タ閮借缃繘鍘绘柟渚胯幏鍙�(quan) + + // 杩斿洖鍑哄幓鐨勫璞�(鐘舵�侊紝閿欒鍘熷洜锛岃鎿嶄綔鐩稿叧淇℃伅(鍙傛暟,杩斿洖鍊�)) + JSONObject returnObj = new JSONObject(); + + // 鍚庡彴璋冪敤 + if (httpClient.call()) { + System.out.println("缁熶竴涓嬪崟,鎴愬姛cll浜�::"); + + // 璁剧疆缁撴灉鍙傛暟 + rescontent = httpClient.getResContent(); + System.out.println("缁熶竴涓嬪崟杩斿洖缁撴灉:" + rescontent); + resHandler.setContent(rescontent);// 瑙f瀽xml + resHandler.setKey(key); + + // 鑾峰彇杩斿洖鍙傛暟 + String return_code = resHandler.getParameter("return_code"); + String return_msg = resHandler.getParameter("return_msg"); + + // 鍒ゆ柇绛惧悕鍙婄粨鏋� + if (resHandler.isTenpaySign() && "SUCCESS".equals(return_code)) { + String prepay_id = resHandler.getParameter("prepay_id");// 棰勬敮浠樹氦鏄撲細璇濇爣璇� + String code_url = resHandler.getParameter("code_url");// 浜岀淮鐮侀摼鎺� + + String result_code = resHandler.getParameter("result_code");// 涓氬姟缁撴灉 + String appid = resHandler.getParameter("appid");// 鍏紬璐﹀彿ID + String mch_id = resHandler.getParameter("mch_id");// 鍟嗘埛鍙� + String nonce_str = resHandler.getParameter("nonce_str");// 闅忔満鐮� + String sign = resHandler.getParameter("sign");// 绛惧悕 + + if (result_code.equals("SUCCESS")) { + returnObj.put("status", "suc"); + returnObj.put("sign", sign); + returnObj.put("nonce_str", nonce_str); + returnObj.put("mch_id", mch_id); + returnObj.put("appid", appid); + returnObj.put("prepay_id", prepay_id); + returnObj.put("code_url", code_url); + returnObj.put("out_trade_no", out_trade_no); + } else { + String errMsg = "[ERROR]result_code:" + resHandler.getParameter("result_code") + " err_code:" + + resHandler.getParameter("err_code") + "err_code_des:" + + resHandler.getParameter("err_code_des"); + + // 閿欒鏃讹紝杩斿洖缁撴灉鏈鍚嶏紝璁板綍retcode銆乺etmsg鐪嬪け璐ヨ鎯呫�� + returnObj.put("status", "ERROR-C"); + returnObj.put("errMsg", errMsg); + } + } else { + String errMsg = "return_code:" + return_code + "err_code:" + resHandler.getParameter("err_code") + + " return_msg:" + return_msg; + // 閿欒鏃讹紝杩斿洖缁撴灉鏈鍚嶏紝璁板綍retcode銆乺etmsg鐪嬪け璐ヨ鎯呫�� + returnObj.put("status", "ERROR-B"); + returnObj.put("errMsg", errMsg); + } + } else { + // 鏈夊彲鑳藉洜涓虹綉缁滃師鍥狅紝璇锋眰宸茬粡澶勭悊锛屼絾鏈敹鍒板簲绛斻�� + returnObj.put("status", "ERROR-A"); + returnObj.put("errMsg", httpClient.getResponseCode() + ":" + httpClient.getErrInfo()); + } + + // 鑾峰彇debug淇℃伅,寤鸿鎶婅姹傘�佸簲绛斿唴瀹广�乨ebug淇℃伅锛岄�氫俊杩斿洖鐮佸啓鍏ユ棩蹇楋紝鏂逛究瀹氫綅闂 + String detail = "http res:" + httpClient.getResponseCode() + "," + httpClient.getErrInfo() + ";" + "req url:" + + requestUrl + ";" + ";" + "req debug:" + reqHandler.getDebugInfo() + ";" + "res content:" + rescontent + + ";" + "res debug:" + resHandler.getDebugInfo() + ";"; + + returnObj.put("detail", detail); + + + return returnObj; + } + + /**缁熶竴鏀粯锛堝垎璐︼級 + * @param request 鏂规硶鑾峰彇 + * @param appId 灏忕▼搴忓彿 + * @param partner 鍟嗘埛鍙� + * @param key 绉橀挜 + * @param notifyUrl 鍥炶皟閾炬帴 + * @param out_trade_no 璁㈠崟鍙� + * @param body 鍟嗗搧鎻忚堪 + * @param total_fee 鏀粯閲戦 + * @param openid 鐢ㄦ埛openId + * @param attach 闄勫甫鏁版嵁鍖� + * @param notifyUrl 鍥炶皟閫氱煡鍦板潃 + * @param trade_type 浜ゆ槗绫诲瀷 + * @param profit_sharing 鏄惁鍒嗚处锛歂涓嶏紝Y鏄� + * @return JSON status = "SUC"涓烘垚鍔� + */ + public static JSONObject unifiedPay(HttpServletRequest request,String appId,String partner,String key,String notifyUrl,String out_trade_no, String body, String total_fee, String openid, + String attach,String trade_type,String profit_sharing) throws Exception { + + if (!SimpleTool.checkNotNull(notifyUrl)) { + throw new ServiceException("鏀粯鍔熻兘鏁呴殰锛�"); + } + + // 鍒涘缓鏌ヨ璇锋眰瀵硅薄 + RequestHandler reqHandler = new RequestHandler(null, null); + // 閫氫俊瀵硅薄 + TenpayHttpClient httpClient = new TenpayHttpClient(); + // 搴旂瓟瀵硅薄 + ClientResponseHandler resHandler = new ClientResponseHandler(); + + // ----------------------------- + // 璁剧疆璇锋眰鍙傛暟 + // ----------------------------- + // reqHandler.init(); + reqHandler.setKey(key); + reqHandler.setGateUrl(FIRST_ORDER_URL);// 璇锋眰URL + + // ----------------------------- + // 璁剧疆鎺ュ彛鍙傛暟(sign鍚庡彴鑷姩鐢熸垚) + // ----------------------------- + + reqHandler.setParameter("appid", appId); // 鍏紬鍙�/灏忕▼搴� + reqHandler.setParameter("mch_id", partner); // 鍟嗘埛鍙� + reqHandler.setParameter("nonce_str", SimpleTool.getUUIDName().substring(0, 30));// 闅忔満涔辩爜 + reqHandler.setParameter("body", body);// 鍟嗗搧鎻忚堪 + reqHandler.setParameter("out_trade_no", out_trade_no);// 鍟嗘埛璁㈠崟鍙� + reqHandler.setParameter("total_fee", total_fee);// 鎬婚噾棰� + reqHandler.setParameter("spbill_create_ip", "8.8.8.8");// 缁堢IP + reqHandler.setParameter("notify_url",notifyUrl);// 閫氱煡鍦板潃 + reqHandler.setParameter("trade_type", trade_type);// 浜ゆ槗绫诲瀷 + //JSAPI锛孨ATIVE锛孉PP + reqHandler.setParameter("openid", openid);// openId + reqHandler.setParameter("attach", attach);// 闄勫甫鏁版嵁鍖� + reqHandler.setParameter("profit_sharing", profit_sharing);// 闄勫甫鏁版嵁鍖� + + // ----------------------------- + // 璁剧疆閫氫俊鍙傛暟 + // ----------------------------- + // 璁剧疆璇锋眰杩斿洖鐨勭瓑寰呮椂闂� + httpClient.setTimeOut(5); + + // 璁剧疆ca璇佷功 + // httpClient.setCaInfo(new File(CA_PATH)); + + // 璁剧疆涓汉(鍟嗘埛)璇佷功 + // httpClient.setCertInfo(new File(CERT_PATH), CERT_PWD); + + // 璁剧疆鍙戦�佺被鍨婸OST + httpClient.setMethod("POST"); + + // 璁剧疆璇锋眰鍐呭(鐢熸垚sign) + String requestUrl = reqHandler.getRequestURL();// 缁勬嫾https://www.baidu.com?a=x&b=xx + + httpClient.setReqContent(requestUrl);// https://www.baidu.com?a=x&b=xx + String rescontent = "null"; + + httpClient.setRequestHandler(reqHandler);// 鎶婂鐞嗗璞★紝鍍忔槸鍙傛暟鍚勭涓滆タ閮借缃繘鍘绘柟渚胯幏鍙�(quan) + + // 杩斿洖鍑哄幓鐨勫璞�(鐘舵�侊紝閿欒鍘熷洜锛岃鎿嶄綔鐩稿叧淇℃伅(鍙傛暟,杩斿洖鍊�)) + JSONObject returnObj = new JSONObject(); + + // 鍚庡彴璋冪敤 + if (httpClient.call()) { + System.out.println("缁熶竴涓嬪崟,鎴愬姛cll浜�::"); + + // 璁剧疆缁撴灉鍙傛暟 + rescontent = httpClient.getResContent(); + System.out.println("缁熶竴涓嬪崟杩斿洖缁撴灉:" + rescontent); + resHandler.setContent(rescontent);// 瑙f瀽xml + resHandler.setKey(key); + + // 鑾峰彇杩斿洖鍙傛暟 + String return_code = resHandler.getParameter("return_code"); + String return_msg = resHandler.getParameter("return_msg"); + + // 鍒ゆ柇绛惧悕鍙婄粨鏋� + if (resHandler.isTenpaySign() && "SUCCESS".equals(return_code)) { + String prepay_id = resHandler.getParameter("prepay_id");// 棰勬敮浠樹氦鏄撲細璇濇爣璇� + String code_url = resHandler.getParameter("code_url");// 浜岀淮鐮侀摼鎺� + + String result_code = resHandler.getParameter("result_code");// 涓氬姟缁撴灉 + String appid = resHandler.getParameter("appid");// 鍏紬璐﹀彿ID + String mch_id = resHandler.getParameter("mch_id");// 鍟嗘埛鍙� + String nonce_str = resHandler.getParameter("nonce_str");// 闅忔満鐮� + String sign = resHandler.getParameter("sign");// 绛惧悕 + + if (result_code.equals("SUCCESS")) { + returnObj.put("status", "suc"); + returnObj.put("sign", sign); + returnObj.put("nonce_str", nonce_str); + returnObj.put("mch_id", mch_id); + returnObj.put("appid", appid); + returnObj.put("prepay_id", prepay_id); + returnObj.put("code_url", code_url); + returnObj.put("out_trade_no", out_trade_no); + } else { + String errMsg = "[ERROR]result_code:" + resHandler.getParameter("result_code") + " err_code:" + + resHandler.getParameter("err_code") + "err_code_des:" + + resHandler.getParameter("err_code_des"); + + // 閿欒鏃讹紝杩斿洖缁撴灉鏈鍚嶏紝璁板綍retcode銆乺etmsg鐪嬪け璐ヨ鎯呫�� + returnObj.put("status", "ERROR-C"); + returnObj.put("errMsg", errMsg); + } + } else { + String errMsg = "return_code:" + return_code + "err_code:" + resHandler.getParameter("err_code") + + " return_msg:" + return_msg; + // 閿欒鏃讹紝杩斿洖缁撴灉鏈鍚嶏紝璁板綍retcode銆乺etmsg鐪嬪け璐ヨ鎯呫�� + returnObj.put("status", "ERROR-B"); + returnObj.put("errMsg", errMsg); + } + } else { + // 鏈夊彲鑳藉洜涓虹綉缁滃師鍥狅紝璇锋眰宸茬粡澶勭悊锛屼絾鏈敹鍒板簲绛斻�� + returnObj.put("status", "ERROR-A"); + returnObj.put("errMsg", httpClient.getResponseCode() + ":" + httpClient.getErrInfo()); + } + + // 鑾峰彇debug淇℃伅,寤鸿鎶婅姹傘�佸簲绛斿唴瀹广�乨ebug淇℃伅锛岄�氫俊杩斿洖鐮佸啓鍏ユ棩蹇楋紝鏂逛究瀹氫綅闂 + String detail = "http res:" + httpClient.getResponseCode() + "," + httpClient.getErrInfo() + ";" + "req url:" + + requestUrl + ";" + ";" + "req debug:" + reqHandler.getDebugInfo() + ";" + "res content:" + rescontent + + ";" + "res debug:" + resHandler.getDebugInfo() + ";"; + + returnObj.put("detail", detail); + + + return returnObj; + } + + /**澶勭悊淇℃伅 + */ + public static JSONObject paymentData(JSONObject payObj,String key){ + JSONObject wxObj = new JSONObject(); + /**缁熶竴涓嬪崟*/ + String payStatus = payObj.getString("status"); + if (payStatus.equals("suc")) { + // JSONObject payObj = po.getJSONObject("inf"); + String appId = payObj.getString("appid"); + String nonceStr = payObj.getString("nonce_str"); + String prepay_id = payObj.getString("prepay_id"); + // JSAPI璋冪敤鏀粯杩斿洖鐨勬暟鎹� + String timeStamp = SimpleTool.getTenTime(new Date()).toString(); + String signType = "MD5"; + String packagef = "prepay_id=" + prepay_id; + RequestHandler reqHandler = new RequestHandler(null, null); + reqHandler.setParameter("appId", appId); + reqHandler.setParameter("nonceStr", nonceStr); + reqHandler.setParameter("timeStamp", timeStamp); + reqHandler.setParameter("package", packagef); + reqHandler.setParameter("signType", signType); + reqHandler.setKey(key); + String paySign = reqHandler.createSign();// 鐢熸垚绛惧悕 + wxObj.put("orderNo", payObj.getString("out_trade_no")); + wxObj.put("paySign", paySign); + wxObj.put("appId", appId); + wxObj.put("nonceStr", nonceStr); + wxObj.put("package", packagef); + wxObj.put("timeStamp", timeStamp); + } else { + throw new RuntimeException(payObj.toString()); + } + return wxObj; + } + + /** + * 閫�娆� + * @param appId 灏忕▼搴�/鍏紬鍙� appId + * @param partner 鍟嗘埛鍙� + * @param key 鍟嗘埛鍙风閽� + * @param certPath 涓汉鍟嗘埛璇佷功 + * @param out_trade_no 鍟嗘埛璁㈠崟鍙� + * @param transaction_id 璐粯閫氳鍗曞彿锛堝井淇¤鍗曞彿锛� + * @param out_refund_no 鍟嗘埛閫�鍗曞彿 + * @param total_fee 璁㈠崟鎬婚(鍗曚綅:鍒�) + * @param refund_fee 閫�娆鹃噾棰�(鍗曚綅:鍒�) + * @return JSON status="SUCCESS"(鎴愬姛) (鐘舵�侊紝閿欒鍘熷洜锛岃鎿嶄綔鐩稿叧淇℃伅(鍙傛暟,杩斿洖鍊�)) + */ + public static JSONObject refund(String appId,String partner,String key,String certPath,String out_trade_no, String transaction_id, String out_refund_no, String total_fee, + String refund_fee) { + try{ + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + FileInputStream instream = new FileInputStream(new File(certPath)); + try { + keyStore.load(instream,partner.toCharArray()); + }finally { + instream.close(); + } + // Trust own CA and all self-signed certs + SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore,partner.toCharArray()).build(); + // Allow TLSv1 protocol only + SSLConnectionSocketFactory sslsf; + sslsf = new SSLConnectionSocketFactory( + sslcontext, new String[] { "TLSv1" }, null, + SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + CloseableHttpClient httpclient = HttpClients.custom() + .setSSLSocketFactory(sslsf).build(); + HttpPost httppost = new HttpPost(REFUND_URL); + String xml = wxPayRefundData(appId, partner, key, out_trade_no, transaction_id, out_refund_no, total_fee, refund_fee); + try { + StringEntity se = new StringEntity(xml); + httppost.setEntity(se); + + CloseableHttpResponse responseEntry = httpclient.execute(httppost); + try { + HttpEntity entity = responseEntry.getEntity(); + if (entity != null) { + + SAXReader saxReader = new SAXReader(); + Document document = saxReader.read(entity.getContent()); + Element rootElt = document.getRootElement(); + String returnCode = rootElt.elementText("return_code"); + JSONObject result = new JSONObject(); + + if(returnCode.equals("SUCCESS")){ + String resultCode = rootElt.elementText("result_code"); + if(resultCode.equals("SUCCESS")) { + result.put("weixinPayUrl", rootElt.elementText("code_url")); + result.put("prepayId", rootElt.elementText("prepay_id")); + result.put("msg", "success"); + + String refund_id = rootElt.elementText("refund_id");//寰俊閫�娆惧崟鍙� + String r_out_refund_no = rootElt.elementText("out_refund_no"); + String errMsg = "鍟嗘埛鍙�" + r_out_refund_no + "鐨勯��娆炬祦姘村彿鏄細" + refund_id; + result.put("status", "SUCCESS"); + result.put("errMsg", errMsg); + result.put("refund_id", refund_id); + }else{ + String errMsg = "[ERROR]result_code:" + rootElt.elementText("result_code")+ + " err_code:" + rootElt.elementText("err_code"); + + //閿欒鏃讹紝杩斿洖缁撴灉鏈鍚嶏紝璁板綍retcode銆乺etmsg鐪嬪け璐ヨ鎯呫�� + result.put("errMsg", errMsg); + result.put("status","false"); + result.put("msg",rootElt.elementText("err_code_des")); + } + }else{ + String errMsg = "[ERROR]return_code:" + rootElt.elementText("return_code"); + + //閿欒鏃讹紝杩斿洖缁撴灉鏈鍚嶏紝璁板綍retcode銆乺etmsg鐪嬪け璐ヨ鎯呫�� + result.put("errMsg", errMsg); + result.put("status","false"); + result.put("msg",rootElt.elementText("return_msg")); + } + return result; + } + EntityUtils.consume(entity); + } + finally { + responseEntry.close(); + } + } + finally { + httpclient.close(); + } + return null; + }catch(Exception e){ + e.printStackTrace(); + JSONObject result = new JSONObject(); + result.put("status","error"); + result.put("msg",e.getMessage()); + return result; + } + } + + /** 灏佽鍙傛暟鏁版嵁 + * @param appId 灏忕▼搴�/鍏紬鍙� appId + * @param partner 鍟嗘埛鍙� + * @param key 鍟嗘埛鍙风閽� + * @param out_trade_no 鍟嗘埛璁㈠崟鍙� + * @param transaction_id 璐粯閫氳鍗曞彿锛堝井淇¤鍗曞彿锛� + * @param out_refund_no 鍟嗘埛閫�鍗曞彿 + * @param total_fee 璁㈠崟鎬婚(鍗曚綅:鍒�) + * @param refund_fee 閫�娆鹃噾棰�(鍗曚綅:鍒�) + * @return + */ + public static String wxPayRefundData(String appId,String partner,String key,String out_trade_no, String transaction_id,String out_refund_no,String total_fee,String refund_fee) { + StringBuffer xml = new StringBuffer(); + String data = null; + try { + String nonceStr = SimpleTool.getUUIDName().substring(0,30); + xml.append("</xml>"); + SortedMap<String,String> parameters = new TreeMap<String,String>(); + parameters.put("appid",appId); + parameters.put("mch_id",partner); + parameters.put("nonce_str", nonceStr); + if(!StringUtils.isEmpty(out_trade_no)) { + parameters.put("out_trade_no", out_trade_no); + } + if(!StringUtils.isEmpty(transaction_id)) { + parameters.put("transaction_id", transaction_id); + } + parameters.put("out_refund_no", out_refund_no); + parameters.put("fee_type", "CNY"); + parameters.put("total_fee", total_fee);//鎬婚噾棰� + parameters.put("refund_fee", refund_fee);//閫�娆鹃噾棰� + parameters.put("op_user_id",partner); + parameters.put("sign", createSign(parameters,key)); + + data =SortedMaptoXml(parameters); + } catch (Exception e) { + System.err.println(e.getMessage()); + return null; + } + return data; + } + + /** + * 鍒涘缓md5鎽樿,瑙勫垯鏄�:鎸夊弬鏁板悕绉癮-z鎺掑簭,閬囧埌绌哄�肩殑鍙傛暟涓嶅弬鍔犵鍚嶃�� + */ + public static String createSign(SortedMap<String, String> packageParams, String AppKey) { + StringBuffer sb; + sb = new StringBuffer(); + Set es = packageParams.entrySet(); + Iterator it = es.iterator(); + while (it.hasNext()) { + Map.Entry entry = (Map.Entry) it.next(); + String k = (String) entry.getKey(); + String v = (String) entry.getValue(); + if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) { + sb.append(k + "=" + v + "&"); + } + } + sb.append("key=" + AppKey); + String sign = MD5Util.MD5Encode(sb.toString(), "UTF-8").toUpperCase(); + return sign; + } + + /** + * @Author: HONGLINCHEN + * @Description:璇锋眰鍊艰浆鎹负xml鏍煎紡 SortedMap杞瑇ml + * @param params + * @Date: 2017-9-7 17:18 + */ + private static String SortedMaptoXml(SortedMap<String,String> params) { + StringBuilder sb = new StringBuilder(); + Set es = params.entrySet(); + Iterator it = es.iterator(); + sb.append("<xml>\n"); + while(it.hasNext()) { + Map.Entry entry = (Map.Entry)it.next(); + String k = (String)entry.getKey(); + Object v = entry.getValue(); + sb.append("<"+k+">"); + sb.append(v); + sb.append("</"+k+">\n"); + } + sb.append("</xml>"); + return sb.toString(); + } +} diff --git a/hx_common/src/main/java/com/hx/mp/util/WXSignUtils.java b/hx_common/src/main/java/com/hx/mp/util/WXSignUtils.java new file mode 100644 index 0000000..8e921c5 --- /dev/null +++ b/hx_common/src/main/java/com/hx/mp/util/WXSignUtils.java @@ -0,0 +1,33 @@ +package com.hx.mp.util; + +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.SortedMap; + +public class WXSignUtils { + /** + * 寰俊鏀粯绛惧悕绠楁硶sign + * @param characterEncoding + * @param parameters + * @return + */ + @SuppressWarnings("rawtypes") + public static String createSign(String characterEncoding, SortedMap<Object,Object> parameters, String key){ + StringBuffer sb = new StringBuffer(); + Set es = parameters.entrySet();//鎵�鏈夊弬涓庝紶鍙傜殑鍙傛暟鎸夌収accsii鎺掑簭锛堝崌搴忥級 + Iterator it = es.iterator(); + while(it.hasNext()) { + Map.Entry entry = (Map.Entry)it.next(); + String k = (String)entry.getKey(); + Object v = entry.getValue(); + if(null != v && !"".equals(v) + && !"sign".equals(k) && !"key".equals(k)) { + sb.append(k + "=" + v + "&"); + } + } + sb.append("key=" + key); + String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase(); + return sign; + } +} diff --git a/hx_common/src/main/java/com/hx/mp/util/WechatUtil.java b/hx_common/src/main/java/com/hx/mp/util/WechatUtil.java new file mode 100644 index 0000000..9d6406e --- /dev/null +++ b/hx_common/src/main/java/com/hx/mp/util/WechatUtil.java @@ -0,0 +1,77 @@ +package com.hx.mp.util; + +import com.sun.org.apache.xerces.internal.impl.dv.util.Base64; +import net.sf.json.JSONObject; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.UnsupportedEncodingException; +import java.security.AlgorithmParameters; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.Security; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; + + +public class WechatUtil { + public static boolean initialized = false; + + //log4j鏃ュ織 + private static Logger logger = LoggerFactory.getLogger(WechatUtil.class.getName()); + + public static JSONObject encryptedData(String encryptedData, String session_key, String iv) throws Exception { + JSONObject encrypted_obj = null; + byte[] resultByte =decrypt(Base64.decode(encryptedData), + Base64.decode(session_key), + Base64.decode(iv)); + if(null != resultByte && resultByte.length > 0){ + String userInfo = new String(resultByte, "UTF-8"); + encrypted_obj = JSONObject.fromObject(userInfo); + }else{ + logger.error("鑾峰彇unionid瑙e瘑澶辫触锛歟ncryptedData="+encryptedData+";session_key="+session_key+";iv="+iv); + } + return encrypted_obj; + } + + + /** + * AES瑙e瘑 + * @param content 瀵嗘枃 + * @return + * @throws InvalidAlgorithmParameterException + * @throws NoSuchProviderException + */ + public static byte[] decrypt(byte[] content, byte[] keyByte, byte[] ivByte) throws Exception { + initialize(); + Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); + Key sKeySpec = new SecretKeySpec(keyByte, "AES"); + + cipher.init(Cipher.DECRYPT_MODE, sKeySpec, generateIV(ivByte));// 鍒濆鍖� + byte[] result = cipher.doFinal(content); + return result; + } + + public static void initialize(){ + if (initialized) return; + Security.addProvider(new BouncyCastleProvider()); + initialized = true; + } + //鐢熸垚iv + public static AlgorithmParameters generateIV(byte[] iv) throws Exception{ + AlgorithmParameters params = AlgorithmParameters.getInstance("AES"); + params.init(new IvParameterSpec(iv)); + return params; + } + + +} diff --git a/hx_common/src/main/java/com/hx/mp/util/WxMpPayUtil.java b/hx_common/src/main/java/com/hx/mp/util/WxMpPayUtil.java new file mode 100644 index 0000000..736c589 --- /dev/null +++ b/hx_common/src/main/java/com/hx/mp/util/WxMpPayUtil.java @@ -0,0 +1,98 @@ +package com.hx.mp.util; + +import net.sf.json.JSONObject; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.util.EntityUtils; + +import java.util.Map; +import java.util.SortedMap; +import java.util.TreeMap; +import java.util.UUID; + +/** + * 寰俊灏忕▼搴忔敮浠樼浉鍏冲伐鍏风被 + */ +public class WxMpPayUtil { + + /**灏忕▼搴忕孩鍖呭彂閫侀摼鎺�*/ + private static final String URL_SEND_RED_PACK = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendminiprogramhb"; + + /** + * 鍙戦�佸皬绋嬪簭绾㈠寘 + * @param orderNo 璁㈠崟鍙� + * @param mchId 鍟嗘埛鍙� + * @param mchKey 鍟嗘埛瀵嗛挜 + * @param appId 灏忕▼搴廰ppId + * @param sendName 鍙戦�佽�呭悕绉� + * @param openId 鎺ユ敹鑰卭penId + * @param payFee 绾㈠寘閲戦锛屼互鍒嗕负鍗曚綅 + * @param wishing 绁濈璇� + * @param actName 娲诲姩鍚嶇О + * @param remark 澶囨敞 + * @param certPath 鏀粯璇佷功璺緞 + * @return + */ + public static JSONObject sendMiniProgramReadPack(String orderNo, String mchId, String mchKey, String appId, String sendName, String openId, + int payFee, String wishing, String actName, String remark, String certPath) + { + SortedMap<Object, Object> parameters = new TreeMap<Object, Object>(); + parameters.put("nonce_str", UUID.randomUUID().toString().substring(0, 30)); + parameters.put("mch_billno", orderNo);//鍟嗘埛璁㈠崟鍙� + parameters.put("mchid", mchId);//鍟嗘埛鍙� + parameters.put("wxappid", appId);//鍏紬璐﹀彿appId + parameters.put("send_name", sendName);//绾㈠寘鍙戦�佽�呭悕绉� + parameters.put("re_openid", openId);//鐢ㄦ埛openId + parameters.put("total_amount", payFee);//绾㈠寘鎬婚噾棰濓紝浠ュ垎涓哄崟浣� + parameters.put("total_num", 1);//绾㈠寘鏁伴噺锛屽浐瀹氫负1 + parameters.put("wishing", wishing);//绾㈠寘绁濈璇紝128瀛楃 + parameters.put("act_name", actName);//娲诲姩鍚嶇О + parameters.put("remark", remark);//澶囨敞 + parameters.put("notify_way", "MINI_PROGRAM_JSAPI");//閫氱煡鐢ㄦ埛褰㈠紡锛屽浐瀹� + + String sign = WXSignUtils.createSign("UTF-8", parameters, mchKey); + + parameters.put("sign", sign); + String xmlInfo = HttpXmlUtils.transferXml(parameters); + + JSONObject returnObj = new JSONObject(); + + try { + CloseableHttpResponse response = HttpUtil.Post(URL_SEND_RED_PACK, xmlInfo, true, certPath, mchId); + String transfersXml = EntityUtils.toString(response.getEntity(), "utf-8"); + Map<String, String> transferMap = HttpXmlUtils.parseRefundXml(transfersXml); + boolean bl = false; + if (transferMap.size() > 0) { + if (transferMap.get("return_code").equals("SUCCESS")) { + // 閫氳鎴愬姛 + if (transferMap.get("result_code").equals("SUCCESS")) { + // 鎴愬姛闇�瑕佽繘琛岀殑閫昏緫鎿嶄綔 + returnObj.put("status", "suc"); + } else { + bl = true; + returnObj.put("status", "fail"); + returnObj.put("errMsg", transferMap.get("err_code") + "|" + transferMap.get("err_code_des")); + } + } else { + bl = true; + // 閫氳涓嶆垚鍔� + returnObj.put("status", "fail"); + returnObj.put("errMsg", transferMap.get("return_msg")); + } + } else { + bl = true; + returnObj.put("status", "fail"); + returnObj.put("errMsg", "杩斿洖涓虹┖"); + } + if (bl) { + System.out.println("浼佷笟浠樻澶辫触锛�" + transfersXml); + } + } catch (Exception e) { + e.printStackTrace(); + returnObj.put("status", "fail"); + returnObj.put("errMsg", e.getMessage()); + } + + return returnObj; + } + +} diff --git a/hx_common/src/main/java/com/hx/mp/util/XMLUtil.java b/hx_common/src/main/java/com/hx/mp/util/XMLUtil.java new file mode 100644 index 0000000..120edff --- /dev/null +++ b/hx_common/src/main/java/com/hx/mp/util/XMLUtil.java @@ -0,0 +1,109 @@ +package com.hx.mp.util; + +import org.jdom.Document; +import org.jdom.Element; +import org.jdom.JDOMException; +import org.jdom.input.SAXBuilder; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +/** + * xml锟斤拷锟斤拷锟斤拷 + *JX + *linhan + */ +public class XMLUtil { + + /** + * 锟斤拷锟斤拷xml,锟斤拷锟截碉拷一锟斤拷元锟截硷拷值锟皆★拷锟斤拷锟斤拷一锟斤拷元锟斤拷锟斤拷锟接节点,锟斤拷私诘锟斤拷值锟斤拷锟接节碉拷锟絰ml锟斤拷荨锟� + * @param strxml + * @return + * @throws JDOMException + * @throws IOException + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + public static Map doXMLParse(String strxml) throws JDOMException, IOException { + strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\""); + + if(null == strxml || "".equals(strxml)) { + return null; + } + + Map m = new HashMap(); + + InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8")); + SAXBuilder builder = new SAXBuilder(); + Document doc = builder.build(in); + Element root = doc.getRootElement(); + List list = root.getChildren(); + Iterator it = list.iterator(); + while(it.hasNext()) { + Element e = (Element) it.next(); + String k = e.getName(); + String v = ""; + List children = e.getChildren(); + if(children.isEmpty()) { + v = e.getTextNormalize(); + } else { + v = XMLUtil.getChildrenText(children); + } + + m.put(k, v); + } + + //锟截憋拷锟斤拷 + in.close(); + + return m; + } + + /** + * 锟斤拷取锟接斤拷锟斤拷xml + * @param children + * @return String + */ + @SuppressWarnings("rawtypes") + public static String getChildrenText(List children) { + StringBuffer sb = new StringBuffer(); + if(!children.isEmpty()) { + Iterator it = children.iterator(); + while(it.hasNext()) { + Element e = (Element) it.next(); + String name = e.getName(); + String value = e.getTextNormalize(); + List list = e.getChildren(); + sb.append("<" + name + ">"); + if(!list.isEmpty()) { + sb.append(XMLUtil.getChildrenText(list)); + } + sb.append(value); + sb.append("</" + name + ">"); + } + } + + return sb.toString(); + } + + /** + * 锟斤拷取xml锟斤拷锟斤拷锟街凤拷 + * @param strxml + * @return + * @throws IOException + * @throws JDOMException + */ + public static String getXMLEncoding(String strxml) throws JDOMException, IOException { + InputStream in = HttpClientUtil.String2Inputstream(strxml); + SAXBuilder builder = new SAXBuilder(); + Document doc = builder.build(in); + in.close(); + return (String)doc.getProperty("encoding"); + } + + +} diff --git a/hx_common/src/main/java/com/hx/mybatis/aes/handler/GenericStringHandler.java b/hx_common/src/main/java/com/hx/mybatis/aes/handler/GenericStringHandler.java new file mode 100644 index 0000000..2598bdf --- /dev/null +++ b/hx_common/src/main/java/com/hx/mybatis/aes/handler/GenericStringHandler.java @@ -0,0 +1,72 @@ +package com.hx.mybatis.aes.handler; + +import com.hx.mybatis.aes.springbean.VariableAesKey; +import com.hx.util.mysql.aes.MysqlHexAesTool; +import org.apache.ibatis.type.BaseTypeHandler; +import org.apache.ibatis.type.JdbcType; +import org.apache.ibatis.type.MappedJdbcTypes; +import org.apache.ibatis.type.MappedTypes; + +import java.sql.CallableStatement; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +/** + * @author CJH + * @Date 2021-01-02 + * // @MappedTypes娉ㄨВ涓殑绫讳唬琛ㄦ杞崲鍣ㄥ彲浠ヨ嚜鍔ㄨ浆鎹负鐨刯ava瀵硅薄锛孈MappedJdbcTypes娉ㄨВ涓缃殑鏄搴旂殑jdbctype锛宮ysql鐨刯son瀵硅薄瀵瑰簲鐨刯dbctype涓篤ARCHAR銆� + */ +@MappedTypes(value = {String.class}) +@MappedJdbcTypes(value = {JdbcType.VARCHAR}, includeNullJdbcType = true) +public class GenericStringHandler extends BaseTypeHandler<String> { + + public GenericStringHandler() { + } + + @Override + public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException { + ps.setString(i, parameter); + } + + @Override + public String getNullableResult(ResultSet rs, String columnName) throws SQLException { + String data = rs.getString(columnName); + if(data != null && data.length()%32==0 && MysqlHexAesTool.isHexStrValid(data)){ + try{ + data = MysqlHexAesTool.decryptData(data, VariableAesKey.getAesKey(columnName),null); + }catch (Exception e){ + //e.printStackTrace(); + } + } + return data; + } + + @Override + public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException { + String data = rs.getString(columnIndex); + if(data != null && data.length()%32==0 && MysqlHexAesTool.isHexStrValid(data)){ + try{ + data = MysqlHexAesTool.decryptData(data, VariableAesKey.getAesKey(null),null); + }catch (Exception e){ + //e.printStackTrace(); + } + } + return data; + } + + @Override + public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { + String data = cs.getString(columnIndex); + if(data != null && data.length() < 129 && data.length()%32==0 && MysqlHexAesTool.isHexStrValid(data)){ + try{ + data = MysqlHexAesTool.decryptData(data, VariableAesKey.getAesKey(null),null); + }catch (Exception e){ + //e.printStackTrace(); + } + } + return data; + } + +} + diff --git a/hx_common/src/main/java/com/hx/mybatis/aes/springbean/ConstantBean.java b/hx_common/src/main/java/com/hx/mybatis/aes/springbean/ConstantBean.java new file mode 100644 index 0000000..2cdc32d --- /dev/null +++ b/hx_common/src/main/java/com/hx/mybatis/aes/springbean/ConstantBean.java @@ -0,0 +1,46 @@ +package com.hx.mybatis.aes.springbean; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +/** + * 閫氱敤甯搁噺闆嗕腑钀� + * @author CJH + */ +@Component +public class ConstantBean { + + /**鑾峰彇AES绉橀挜鐨勯厤缃紙浠庝粈涔堝寘鑾峰彇鍒帮級*/ + @Value("${mysql.hxe.aes.find.packs:}") + private String packPath; + /**鍥哄畾AES鐨勭閽�*/ + @Value("${mysql.hxe.aes.fixd.key:}") + private String fixedAesKey; + /**鏁版嵁搴撳垵濮嬪寲鍔犲瘑瀛楁鐗堟湰鍙�*/ + @Value("${mysql.hxe.aes.init.version:}") + private String initVersion; + + public String getPackPath() { + return packPath; + } + + public void setPackPath(String packPath) { + this.packPath = packPath; + } + + public String getFixedAesKey() { + return fixedAesKey; + } + + public void setFixedAesKey(String fixedAesKey) { + this.fixedAesKey = fixedAesKey; + } + + public String getInitVersion() { + return initVersion; + } + + public void setInitVersion(String initVersion) { + this.initVersion = initVersion; + } +} diff --git a/hx_common/src/main/java/com/hx/mybatis/aes/springbean/ExportTableAliasVisitor.java b/hx_common/src/main/java/com/hx/mybatis/aes/springbean/ExportTableAliasVisitor.java new file mode 100644 index 0000000..78d4c32 --- /dev/null +++ b/hx_common/src/main/java/com/hx/mybatis/aes/springbean/ExportTableAliasVisitor.java @@ -0,0 +1,53 @@ +package com.hx.mybatis.aes.springbean; + +import com.alibaba.druid.sql.ast.statement.SQLExprTableSource; +import com.alibaba.druid.sql.visitor.SQLASTVisitorAdapter; + +import java.util.HashMap; +import java.util.Map; + +/** + * ExportTableAliasVisitor + * @author Mwg + * @date 2020/09/08 23:47 + */ +public class ExportTableAliasVisitor extends SQLASTVisitorAdapter { + + private Map<String,String> tableMap = new HashMap<>(); + + public Map<String, String> getTableMap() { + return tableMap; + } + + public void setTableMap(Map<String, String> tableMap) { + this.tableMap = tableMap; + } + + @Override + public boolean visit(SQLExprTableSource x) { + + //鍒悕锛屽鏋滄湁鍒悕锛屽埆鍚嶄繚鎸佷笉鍙� + //System.out.println("alias:"+x.getAlias());//鍒悕 + //System.out.println("expr:"+x.getExpr());//琛ㄥ悕 + tableMap.put(x.getExpr().toString(),x.getAlias()); + + + //String s = StringUtils.isEmpty(x.getAlias()) ? x.getExpr().toString() : x.getAlias(); + + // 淇敼琛ㄥ悕锛屼笉鍖呭惈鐐规墠鍔� select id from c left join d on c.id = d.id 涓殑c 鍜� d + + /*if(!x.getExpr().toString().contains(".")) { + + x.setExpr("`" + dbName.get() + "`." + x.getExpr()); + + }*/ + //x.setExpr("mymymytable");//淇敼琛ㄥ悕 + //x.setAlias("aa");//淇敼鍒悕 + //x.setAlias(s); + return true; + + } + + + +} \ No newline at end of file diff --git a/hx_common/src/main/java/com/hx/mybatis/aes/springbean/FieldData.java b/hx_common/src/main/java/com/hx/mybatis/aes/springbean/FieldData.java new file mode 100644 index 0000000..cd54cbc --- /dev/null +++ b/hx_common/src/main/java/com/hx/mybatis/aes/springbean/FieldData.java @@ -0,0 +1,40 @@ +package com.hx.mybatis.aes.springbean; + +import java.util.Set; + +public class FieldData { + + //涓婚敭 + private String id; + //鏁版嵁搴撹〃鏄� + private String tableName; + //闇�瑕佸姞瀵嗗緱琛ㄥ瓧娈� + private Set<String> encrypFields; + + public FieldData() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getTableName() { + return tableName; + } + + public void setTableName(String tableName) { + this.tableName = tableName; + } + + public Set<String> getEncrypFields() { + return encrypFields; + } + + public void setEncrypFields(Set<String> encrypFields) { + this.encrypFields = encrypFields; + } +} diff --git a/hx_common/src/main/java/com/hx/mybatis/aes/springbean/InitMysqlData.java b/hx_common/src/main/java/com/hx/mybatis/aes/springbean/InitMysqlData.java new file mode 100644 index 0000000..4975d2b --- /dev/null +++ b/hx_common/src/main/java/com/hx/mybatis/aes/springbean/InitMysqlData.java @@ -0,0 +1,197 @@ +package com.hx.mybatis.aes.springbean; + +import com.gitee.sunchenbin.mybatis.actable.annotation.Column; +import com.gitee.sunchenbin.mybatis.actable.annotation.Table; +import com.hx.common.annotations.MysqlHexAes; +import com.hx.common.dao.mapper.CommonMapper; +import com.hx.common.service.CommonService; +import com.hx.exception.ServiceException; +import com.hx.mybatisTool.SqlSentence; +import com.hx.util.StringUtils; +import com.hx.util.mysql.aes.MysqlHexAesTool; + +import java.lang.reflect.Field; +import java.util.*; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +public class InitMysqlData { + + /** + * 椤圭洰鍚姩灏辨墽琛屽悗灏辨墽琛岃鏂规硶 + */ + //@PostConstruct 2022-06-17灞忔帀锛屾殏鏃剁敤涓嶄笂 + public static void initData(String packPath, CommonService commonService){ + + //椤圭洰鍚姩鐨勬椂鍊欏~鍏� + if(!StringUtils.isEmpty(packPath)){ + Set<Class<?>> classes = VariableAesKey.classData(packPath); + + SqlSentence sqlSentence = new SqlSentence(); + Map<String,Object> values = new HashMap<>(); + + //瑙f瀽琛ㄦ暟鎹� + List<FieldData> fieldDatas = entityhandle(classes); + + int pageSize = 500; + //鍒涘缓涓�涓畾闀跨嚎绋嬫睜锛屽彲鎺у埗绾跨▼鏈�澶у苟鍙戞暟锛岃秴鍑虹殑绾跨▼浼氬湪闃熷垪涓瓑寰呫�� + ExecutorService fixedThreadPool = Executors.newFixedThreadPool(20); + try{ + for(FieldData fieldData:fieldDatas){ + //鑾峰彇鏉℃暟 + sqlSentence.sqlSentence("SELECT COUNT(0) FROM "+fieldData.getTableName(),values); + int total = commonService.selectCountSql(sqlSentence); + if(total ==0 ){ + continue; + } + int pageTotal = total/pageSize+1; + for(int i= 0;i<pageTotal;i++){ + int finalI = i; + fixedThreadPool.execute(new Runnable() { + @Override + public void run() { + //鏇存柊鏁版嵁 + updateData(fieldData,commonService, finalI,pageSize); + } + }); + } + } + }catch (Exception e){ + e.printStackTrace(); + }finally { + fixedThreadPool.shutdown(); + } + } + } + + /**鏇存柊鏁版嵁*/ + public static void updateData(FieldData fieldData,CommonService commonService,int pageNum,int pageSize){ + SqlSentence sqlSentence = new SqlSentence(); + Map<String,Object> values = new HashMap<>(); + + //鏌ヨ鏁版嵁 + StringBuilder selectField = new StringBuilder(); + selectField.append(fieldData.getId()); + for(String fieldName:fieldData.getEncrypFields()){ + selectField.append(","+fieldName); + } + pageNum = pageNum*pageSize; + + sqlSentence.sqlSentence("SELECT "+selectField.toString()+" FROM "+fieldData.getTableName()+" LIMIT "+pageNum+","+pageSize,values); + List<Map<String,Object>> list = commonService.selectListMap(CommonMapper.class,sqlSentence); + + boolean isUpdate = false; + for (Map<String,Object> map:list){ + isUpdate = false; + StringBuilder setField = new StringBuilder(); + for (Map.Entry<String, Object> entry : map.entrySet()) { + String mapKey = entry.getKey(); + String mapValue = (String) entry.getValue(); + if(StringUtils.isEmpty(mapValue)){ + continue; + } + if(mapValue.length()%32==0 && MysqlHexAesTool.isHexStrValid(mapValue)){ + continue; + } + if(fieldData.getId().equals(mapKey)){ + continue; + } + if(setField.length()>0){ + setField.append(","); + } + setField.append(mapKey+" = #{m."+mapKey+"}"); + isUpdate = true; + } + + if(isUpdate){ + values = map; + sqlSentence.sqlSentence("UPDATE "+fieldData.getTableName()+" SET "+setField.toString()+" WHERE "+fieldData.getId()+" = #{m."+fieldData.getId()+"}",values); + + if(commonService.updateSentence(sqlSentence)!=1){ + throw new ServiceException("鏇存柊瓒呰繃1鏉★紝鏇存柊澶辫触锛�"); + } + } + } + + } + + /**鑾峰彇鍒拌〃鐨勬暟鎹�*/ + public static List<FieldData> entityhandle(Set<Class<?>> classes){ + + List<FieldData> fildDatas = new ArrayList<>(); + //瀛樺偍鍗曡〃瀛楁淇℃伅 + FieldData fildData; + //瀛樺偍闇�瑕佸姞瀵嗙殑瀛楁 + Set<String> encrypFields; + + String fildName; + + for(Class<?> cl:classes){ + fildData = new FieldData(); + encrypFields = new HashSet<>(); + + //琛ㄥ悕绉� + if(!cl.isAnnotationPresent(Table.class)){ + continue; + } + Table table = cl.getAnnotation(Table.class); + fildData.setTableName(table.name()); + + // 鍙栧緱鏈被鐨勫叏閮ㄥ睘鎬� + Field[] fields = cl.getDeclaredFields(); + fields = VariableAesKey.getPatentFields(fields,cl); + for (Field field:fields) { + + fildName = null; + if(field.isAnnotationPresent(Column.class)){ + Column column = field.getAnnotation(Column.class); + fildName = column.name(); + if(StringUtils.isEmpty(fildName)){ + fildName = field.getName(); + } + if(column.isKey()){ + fildData.setId(fildName); + } + }else{ + fildName = field.getName(); + } + + // 鍒ゆ柇鏂规硶涓槸鍚︽湁鎸囧畾娉ㄨВ绫诲瀷鐨勬敞瑙� + if (!field.isAnnotationPresent(MysqlHexAes.class)) { + continue; + } + // 鏍规嵁娉ㄨВ绫诲瀷杩斿洖鏂规硶鐨勬寚瀹氱被鍨嬫敞瑙� + MysqlHexAes mysqlHexAes = field.getAnnotation(MysqlHexAes.class); + //鍒ゆ柇鐗堟湰鍙锋槸涓嶆槸涓�鏍风殑 + if(!StringUtils.isEmpty(VariableAesKey.INIT_VERSION)){ + if(!VariableAesKey.INIT_VERSION.equals(mysqlHexAes.initVersion())){ + continue; + } + }else{ + if(!StringUtils.isEmpty(mysqlHexAes.initVersion())){ + continue; + } + } + + String aesKey = mysqlHexAes.aesKey(); + if(StringUtils.isEmpty(aesKey)){ + aesKey = VariableAesKey.AES_KEY; + if(StringUtils.isEmpty(aesKey)){ + throw new RuntimeException("mysql鐨凙ES绉橀挜涓嶈兘涓虹┖:"+field.getName()); + } + } + + encrypFields.add(fildName); + } + //鏄惁鏈夐渶瑕佸姞瀵嗗緱瀛楁 + if(encrypFields.size()<=0){ + continue; + } + fildData.setEncrypFields(encrypFields); + fildDatas.add(fildData); + } + return fildDatas; + } + + +} diff --git a/hx_common/src/main/java/com/hx/mybatis/aes/springbean/MySqlInterceptor.java b/hx_common/src/main/java/com/hx/mybatis/aes/springbean/MySqlInterceptor.java new file mode 100644 index 0000000..cff0067 --- /dev/null +++ b/hx_common/src/main/java/com/hx/mybatis/aes/springbean/MySqlInterceptor.java @@ -0,0 +1,101 @@ +package com.hx.mybatis.aes.springbean; + +import org.apache.ibatis.executor.statement.StatementHandler; +import org.apache.ibatis.mapping.BoundSql; +import org.apache.ibatis.mapping.MappedStatement; +import org.apache.ibatis.mapping.ParameterMapping; +import org.apache.ibatis.mapping.SqlCommandType; +import org.apache.ibatis.plugin.*; +import org.apache.ibatis.reflection.DefaultReflectorFactory; +import org.apache.ibatis.reflection.MetaObject; +import org.apache.ibatis.reflection.SystemMetaObject; +import org.apache.ibatis.session.Configuration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import java.lang.reflect.Field; +import java.sql.Connection; +import java.util.List; +import java.util.Properties; + + +@Component +@Intercepts({ + @Signature( + type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class + }) +}) +public class MySqlInterceptor implements Interceptor { + + private static Logger logger = LoggerFactory.getLogger(MySqlInterceptor.class.getName()); + @Override + public Object intercept(Invocation invocation) throws Throwable { + + // 鏂规硶涓� + StatementHandler statementHandler = (StatementHandler) invocation.getTarget(); + MetaObject metaObject = MetaObject.forObject(statementHandler, SystemMetaObject.DEFAULT_OBJECT_FACTORY, SystemMetaObject.DEFAULT_OBJECT_WRAPPER_FACTORY, new DefaultReflectorFactory()); + //鍏堟嫤鎴埌RoutingStatementHandler锛岄噷闈㈡湁涓猄tatementHandler绫诲瀷鐨刣elegate鍙橀噺锛屽叾瀹炵幇绫绘槸BaseStatementHandler锛岀劧鍚庡氨鍒癇aseStatementHandler鐨勬垚鍛樺彉閲弇appedStatement + MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement"); + //id涓烘墽琛岀殑mapper鏂规硶鐨勫叏璺緞鍚嶏紝濡俢om.uv.dao.UserMapper.insertUser + //String id = mappedStatement.getId(); + //sql璇彞绫诲瀷 select銆乨elete銆乮nsert銆乽pdate + SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType(); + BoundSql boundSql = statementHandler.getBoundSql(); + + // 鑾峰彇鑺傜偣鐨勯厤缃� + Configuration configuration = mappedStatement.getConfiguration(); + // 鑾峰彇鍙傛暟 + Object parameterObject = boundSql.getParameterObject(); + // MetaObject涓昏鏄皝瑁呬簡originalObject瀵硅薄锛屾彁渚涗簡get鍜宻et鐨勬柟娉曠敤浜庤幏鍙栧拰璁剧疆originalObject鐨勫睘鎬у��,涓昏鏀寔瀵笿avaBean銆丆ollection銆丮ap涓夌绫诲瀷瀵硅薄鐨勬搷浣� + // MetaObject metaObject1 = configuration.newMetaObject(parameterObject); + //鑾峰彇sql涓棶鍙风殑鍩烘湰淇℃伅 + List<ParameterMapping> parameterMappings = boundSql + .getParameterMappings(); + + /*for (ParameterMapping parameterMapping : parameterMappings) { + String propertyName = parameterMapping.getProperty(); + System.out.println("propertyName锛�"+ propertyName); + System.out.println("parameterObject锛�"+ parameterObject); + }*/ + + //杩欓噷鍙互杩涜sql淇敼 + //鑾峰彇鍒板師濮媠ql璇彞 + String sql = boundSql.getSql(); + //鏂板 + if(sqlCommandType == SqlCommandType.INSERT){ + sql = SqlUtils.insertSql(sql, VariableAesKey.aesKeysTable); + }else if(sqlCommandType == SqlCommandType.UPDATE){ + sql = SqlUtils.updateSql(sql, VariableAesKey.aesKeysTable); + }else if(sqlCommandType == SqlCommandType.SELECT){ + if(VariableAesKey.isRun == 1){ + sql = SqlUtils.selectSql(sql, VariableAesKey.aesKeysTable); + } + }else if(sqlCommandType == SqlCommandType.DELETE){ + sql = SqlUtils.deleteSql(sql, VariableAesKey.aesKeysTable); + } + + //閫氳繃鍙嶅皠淇敼sql璇彞 + Field field = boundSql.getClass().getDeclaredField("sql"); + field.setAccessible(true); + field.set(boundSql, sql); + + return invocation.proceed(); + + } + + @Override + public Object plugin(Object target) { + if (target instanceof StatementHandler) { + return Plugin.wrap(target, this); + } else { + return target; + } + + } + + @Override + public void setProperties(Properties properties) { + + } +} \ No newline at end of file diff --git a/hx_common/src/main/java/com/hx/mybatis/aes/springbean/SqlUtils.java b/hx_common/src/main/java/com/hx/mybatis/aes/springbean/SqlUtils.java new file mode 100644 index 0000000..8d978db --- /dev/null +++ b/hx_common/src/main/java/com/hx/mybatis/aes/springbean/SqlUtils.java @@ -0,0 +1,578 @@ +package com.hx.mybatis.aes.springbean; + +import com.alibaba.druid.sql.SQLUtils; +import com.alibaba.druid.sql.ast.SQLExpr; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.ast.statement.*; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlDeleteStatement; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlInsertStatement; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlUpdateStatement; +import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; +import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor; +import com.alibaba.druid.sql.visitor.SQLASTOutputVisitor; +import com.alibaba.druid.stat.TableStat; +import com.alibaba.druid.util.JdbcConstants; +import com.alibaba.druid.util.JdbcUtils; +import com.hx.util.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Collection; +import java.util.List; +import java.util.Map; + +/** + * sql璇彞澶勭悊宸ュ叿 + * @author CJH 2022-01-12 + */ +public class SqlUtils { + //log4j鏃ュ織 + private static Logger logger = LoggerFactory.getLogger(SqlUtils.class.getName()); + + + /**鏌ヨ鍔犲瘑鏁版嵁澶勭悊锛屽彧瀵规煡璇㈠仛澶勭悊 + * @param sql sql璇彞 + * @param aesKeysTable aes绉橀挜 + * @return + */ + public static String selectSql(String sql,Map<String,Map<String,String>> aesKeysTable){ + + MySqlStatementParser parser = new MySqlStatementParser(sql); + SQLSelectStatement sqlStatement = (SQLSelectStatement) parser.parseSelect(); + + SQLSelect sqlSelect = sqlStatement.getSelect(); + if (sqlSelect.getQuery() instanceof SQLSelectQueryBlock) { + // 闈瀠nion鐨勬煡璇㈣鍙� + return selectSqlRoutine( sqlStatement,aesKeysTable); + } else if (sqlSelect.getQuery() instanceof SQLUnionQuery) { + // union鐨勬煡璇㈣鍙� + return selectSqlUnion( sql, sqlStatement, aesKeysTable); + }else { + return selectSqlRoutine( sqlStatement,aesKeysTable); + } + } + + /**鏌ヨ鍔犲瘑鏁版嵁澶勭悊锛屽彧瀵规煡璇㈠仛澶勭悊锛宻elect杩斿洖涓嶅仛澶勭悊锛圲nion鐗规畩璇彞锛� + * @param sql sql璇彞 + * @param aesKeysTable aes绉橀挜 + * @return + */ + public static String selectSqlUnion(String sql,SQLSelectStatement sqlStatement,Map<String,Map<String,String>> aesKeysTable){ + + //鑾峰彇琛ㄥ拰鍒悕 + ExportTableAliasVisitor visitorTable = new ExportTableAliasVisitor(); + sqlStatement.accept(visitorTable); + Map<String,String> tableMaps = visitorTable.getTableMap(); + + //鑾峰彇鎵�鏈夌殑瀛楁 + MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); + sqlStatement.accept(visitor); + //閬嶅巻鎵�鏈夊瓧娈� + Collection<TableStat.Column> columns= visitor.getColumns(); + + //澶勭悊闇�瑕佸姞瀵嗗緱瀛楁 + + if(!StringUtils.isEmpty(sql)){ + Map<String,String> aesKeys = null; + String aeskey = null; + //鎶婂墿涓嬬殑鎷兼帴涓婃潵 + String tableAl = null; + for(TableStat.Column column:columns){ + aesKeys= aesKeysTable.get(column.getTable()); + if(aesKeys == null){ + continue; + } + aeskey = aesKeys.getOrDefault(column.getName(),null); + if(StringUtils.isEmpty(aeskey)){ + continue; + } + tableAl = tableMaps.get(column.getTable()); + if(!StringUtils.isEmpty(tableAl)){ + tableAl = tableAl+"."+column.getName(); + }else{ + tableAl = column.getName(); + } + sql = sql.replaceAll("((?<!\\.)\\b"+tableAl+"\\b(?!\\.))","AES_DECRYPT(UNHEX("+tableAl+"),'"+aeskey+"')"); + } + } + return sql; + } + + + /**鏌ヨ鍔犲瘑鏁版嵁澶勭悊锛屽彧瀵规煡璇㈠仛澶勭悊锛宻elect杩斿洖涓嶅仛澶勭悊锛堝父瑙勮鍙ワ級 + * @param sqlStatement sql璇彞 + * @param aesKeysTable aes绉橀挜 + * @return + */ + public static String selectSqlRoutine(SQLSelectStatement sqlStatement,Map<String,Map<String,String>> aesKeysTable){ + + //瑙f瀽select鏌ヨ + //SQLSelect sqlSelect = sqlStatement.getSelect() + //鑾峰彇sql鏌ヨ鍧� + SQLSelectQueryBlock sqlSelectQuery = null; + boolean b = true; + try{ + sqlSelectQuery = (SQLSelectQueryBlock)sqlStatement.getSelect().getQuery() ; + }catch (Exception e){ + b = false; + logger.error("瑙f瀽sql鎶ラ敊锛�"+e.getMessage()); + } + if(!b){ + return "err"; + } + + StringBuffer out = new StringBuffer() ; + //鍒涘缓sql瑙f瀽鐨勬爣鍑嗗寲杈撳嚭 + SQLASTOutputVisitor sqlastOutputVisitor = SQLUtils.createFormatOutputVisitor(out , null , JdbcUtils.MYSQL) ; + + //鑾峰彇琛ㄥ拰鍒悕 + ExportTableAliasVisitor visitorTable = new ExportTableAliasVisitor(); + sqlStatement.accept(visitorTable); + Map<String,String> tableMaps = visitorTable.getTableMap(); + + //鑾峰彇鎵�鏈夌殑瀛楁 + MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); + sqlStatement.accept(visitor); + //閬嶅巻鎵�鏈夊瓧娈� + Collection<TableStat.Column> columns= visitor.getColumns(); + + StringBuilder sqlWhere = new StringBuilder(); + + StringBuilder sqlSelect = new StringBuilder(); + String expr = null; + sqlSelect.append("SELECT "); + //瑙f瀽select杩斿洖鐨勬暟鎹瓧娈甸」 + for (SQLSelectItem sqlSelectItem : sqlSelectQuery.getSelectList()) { + if(sqlSelect.length() > 7){ + sqlSelect.append(","); + } + + out.delete(0, out.length()) ; + sqlSelectItem.accept(sqlastOutputVisitor) ; + expr = out.toString(); + sqlSelect.append(expr); + + /* if(expr.indexOf("SELECT") == -1){ + sqlSelect.append(expr); + }else{ + //sqlSelect.append("("); + sqlSelect.append(expr); + //sqlSelect.append(")"); + *//* if(!StringUtils.isEmpty(sqlSelectItem.getAlias())){ + sqlSelect.append(" AS "+sqlSelectItem.getAlias()); + }*//* + }*/ + } + + //瑙f瀽from + if(sqlSelectQuery.getFrom() != null){ + out.delete(0, out.length()) ; + sqlSelectQuery.getFrom().accept(sqlastOutputVisitor) ; + sqlWhere.append(" FROM "+out); + } + + //瑙f瀽where + if(sqlSelectQuery.getWhere() != null){ + out.delete(0, out.length()) ; + sqlSelectQuery.getWhere().accept(sqlastOutputVisitor) ; + sqlWhere.append(" WHERE "+out+" "); + } + + if(sqlSelectQuery.getGroupBy() != null){ + out.delete(0, out.length()) ; + sqlSelectQuery.getGroupBy().accept(sqlastOutputVisitor) ; + sqlWhere.append(" "+out); + } + if(sqlSelectQuery.getOrderBy() != null){ + out.delete(0, out.length()) ; + sqlSelectQuery.getOrderBy().accept(sqlastOutputVisitor) ; + sqlWhere.append(" "+out); + } + if(sqlSelectQuery.getLimit() != null){ + out.delete(0, out.length()) ; + sqlSelectQuery.getLimit().accept(sqlastOutputVisitor) ; + sqlWhere.append(" "+out); + } + + //澶勭悊where闇�瑕佸姞瀵嗗緱瀛楁 + String sql = sqlWhere.toString(); + if(!StringUtils.isEmpty(sql)){ + Map<String,String> aesKeys = null; + String aeskey = null; + //鎶婂墿涓嬬殑鎷兼帴涓婃潵 + String tableAl = null; + for(TableStat.Column column:columns){ + aesKeys= aesKeysTable.get(column.getTable()); + if(aesKeys == null){ + continue; + } + aeskey = aesKeys.getOrDefault(column.getName(),null); + if(StringUtils.isEmpty(aeskey)){ + continue; + } + tableAl = tableMaps.get(column.getTable()); + if(!StringUtils.isEmpty(tableAl)){ + tableAl = tableAl+"."+column.getName(); + }else{ + tableAl = column.getName(); + } + sql = sql.replaceAll("((?<!\\.)\\b"+tableAl+"\\b(?!\\.))","AES_DECRYPT(UNHEX("+tableAl+"),'"+aeskey+"')"); + } + } + return sqlSelect.toString()+sql; + } + + /** + * 澶勭悊select杩斿洖瀛楁鐨勫弬鏁� + * @param sql + * @param aesKeysTable + * @param tableMaps + * @param columns + * @return + */ + public static String selectSqlHandle(String sql,Map<String,Map<String,String>> aesKeysTable + ,Map<String,String> tableMaps,Collection<TableStat.Column> columns){ + + + MySqlStatementParser parser = new MySqlStatementParser(sql); + SQLSelectStatement sqlStatement = (SQLSelectStatement) parser.parseSelect(); + //鑾峰彇鏍煎紡鍖栫殑slq璇彞 + sql = sqlStatement.toString(); + + //瑙f瀽select鏌ヨ + //SQLSelect sqlSelect = sqlStatement.getSelect() ; + //鑾峰彇sql鏌ヨ鍧� + SQLSelectQueryBlock sqlSelectQuery = (SQLSelectQueryBlock)sqlStatement.getSelect().getQuery() ; + StringBuffer out = new StringBuffer() ; + //鍒涘缓sql瑙f瀽鐨勬爣鍑嗗寲杈撳嚭 + SQLASTOutputVisitor sqlastOutputVisitor = SQLUtils.createFormatOutputVisitor(out , null , JdbcUtils.MYSQL) ; + + StringBuilder sqlWhere = new StringBuilder(); + + StringBuilder sqlSelect = new StringBuilder(); + String expr = null; + sqlSelect.append("SELECT "); + //瑙f瀽select杩斿洖鐨勬暟鎹瓧娈甸」 + for (SQLSelectItem sqlSelectItem : sqlSelectQuery.getSelectList()) { + if(sqlSelect.length() > 7){ + sqlSelect.append(","); + } + expr = sqlSelectItem.getExpr().toString(); + if(expr.indexOf("SELECT") == -1){ + sqlSelect.append(expr); + if(!StringUtils.isEmpty(sqlSelectItem.getAlias())){ + sqlSelect.append(" AS "+sqlSelectItem.getAlias()); + } + }else{ + sqlSelect.append("("); + selectSqlHandle(expr,aesKeysTable,tableMaps,columns); + sqlSelect.append(")"); + if(!StringUtils.isEmpty(sqlSelectItem.getAlias())){ + sqlSelect.append(" AS "+sqlSelectItem.getAlias()); + } + } + } + + //瑙f瀽from + if(sqlSelectQuery.getFrom() != null){ + out.delete(0, out.length()) ; + sqlSelectQuery.getFrom().accept(sqlastOutputVisitor) ; + sqlWhere.append(" FROM "+out); + } + + //瑙f瀽where + if(sqlSelectQuery.getWhere() != null){ + out.delete(0, out.length()) ; + sqlSelectQuery.getWhere().accept(sqlastOutputVisitor) ; + sqlWhere.append(" WHERE "+out+" "); + } + + if(sqlSelectQuery.getGroupBy() != null){ + out.delete(0, out.length()) ; + sqlSelectQuery.getGroupBy().accept(sqlastOutputVisitor) ; + sqlWhere.append(" "+out); + } + if(sqlSelectQuery.getOrderBy() != null){ + out.delete(0, out.length()) ; + sqlSelectQuery.getOrderBy().accept(sqlastOutputVisitor) ; + sqlWhere.append(" "+out); + } + if(sqlSelectQuery.getLimit() != null){ + out.delete(0, out.length()) ; + sqlSelectQuery.getLimit().accept(sqlastOutputVisitor) ; + sqlWhere.append(" "+out); + } + + sql = sqlWhere.toString(); + if(!StringUtils.isEmpty(sql)){ + Map<String,String> aesKeys = null; + String aeskey = null; + //鎶婂墿涓嬬殑鎷兼帴涓婃潵 + String tableAl = null; + + for(TableStat.Column column:columns){ + aesKeys= aesKeysTable.get(column.getTable()); + if(aesKeys == null){ + continue; + } + aeskey = aesKeys.getOrDefault(column.getName(),null); + if(StringUtils.isEmpty(aeskey)){ + continue; + } + tableAl = tableMaps.get(column.getTable()); + if(!StringUtils.isEmpty(tableAl)){ + tableAl = tableAl+"."+column.getName(); + }else{ + tableAl = column.getName(); + } + sql = sql.replaceAll("((?<!\\.)\\b"+tableAl+"\\b(?!\\.))","AES_DECRYPT(UNHEX("+tableAl+"),'"+aeskey+"')"); + } + } + return sqlSelect.toString()+sql; + } + + /**鏂板鍔犲瘑鏁版嵁澶勭悊 + * @param sql sql璇彞 + * @param aesKeysTable aes绉橀挜 + * @return + */ + public static String insertSql(String sql,Map<String,Map<String,String>> aesKeysTable){ + //瑁呰浇閲嶅啓鐨剆ql璇彞 + StringBuilder splicingSql = new StringBuilder(); + + sql = SQLUtils.format(sql, JdbcConstants.MYSQL); + String[] datas = sql.split("VALUES",2); + + splicingSql.append(datas[0]+"VALUES "); + + //閲嶆柊鎷兼帴SQL璇彞 + + //瑙f瀽sql璇彞 + MySqlStatementParser parser = new MySqlStatementParser(sql); + SQLStatement statement = parser.parseStatement(); + MySqlInsertStatement insert = (MySqlInsertStatement)statement; + + String insertName = insert.getTableName().getSimpleName(); + + //鏍规嵁琛ㄥ悕绉拌幏鍙栧埌AES绉橀挜 + Map<String,String> aesKeys= aesKeysTable.get(insertName); + if(aesKeys == null){ + return sql; + } + + //鑾峰彇鎵�鏈夌殑瀛楁 + List<SQLExpr> columns = insert.getColumns(); + + String fildValue = null; + String aeskey = null; + //閬嶅巻鍊� + List<SQLInsertStatement.ValuesClause> vcl = insert.getValuesList(); + for(int j = 0; j<vcl.size(); j++){ + if( j != 0){ + splicingSql.append(","); + } + for(int i = 0;i < columns.size();i++){ + //鏌ヨ鏀瑰瓧娈垫槸鍚﹂渶瑕佸姞瀵� + aeskey = aesKeys.getOrDefault(columns.get(i).toString(),null); + fildValue = vcl.get(j).getValues().get(i).toString(); + if(i == 0){ + splicingSql.append("("); + if(aeskey != null && fildValue.indexOf("AES_ENCRYPT") == -1){ + splicingSql.append("HEX(AES_ENCRYPT("+fildValue+",'"+aeskey+"'))"); + }else{ + splicingSql.append(fildValue); + } + }else if(i == columns.size()-1){ + splicingSql.append(","); + if(aeskey != null && fildValue.indexOf("AES_ENCRYPT") == -1){ + splicingSql.append("HEX(AES_ENCRYPT("+fildValue+",'"+aeskey+"'))"); + }else{ + splicingSql.append(fildValue); + } + splicingSql.append(")"); + }else{ + splicingSql.append(","); + if(aeskey != null && fildValue.indexOf("AES_ENCRYPT") == -1){ + splicingSql.append("HEX(AES_ENCRYPT("+fildValue+",'"+aeskey+"'))"); + }else{ + splicingSql.append(fildValue); + } + } + } + } + return splicingSql.toString(); + } + + /**鏇存柊鍔犲瘑鏁版嵁澶勭悊 + * @param sql sql璇彞 + * @param aesKeysTable aes绉橀挜 + * @return + */ + public static String updateSql(String sql,Map<String,Map<String,String>> aesKeysTable){ + + //瑁呰浇閲嶅啓鐨剆ql璇彞 + StringBuilder splicingSql = new StringBuilder(); + + //sql = SQLUtils.format(sql, JdbcConstants.MYSQL); + MySqlStatementParser parser = new MySqlStatementParser(sql); + SQLStatement sqlStatement = parser.parseStatement(); + //鑾峰彇鏍煎紡鍖栫殑slq璇彞 + sql = sqlStatement.toString(); + + MySqlUpdateStatement updateStatement = (MySqlUpdateStatement)sqlStatement; + + String insertName = updateStatement.getTableName().getSimpleName(); + + String[] datas = sql.split("WHERE",2); + + Map<String,String> aesKeys = aesKeysTable.get(insertName); + if(aesKeys == null){ + return sql; + } + + splicingSql.append("UPDATE "+insertName+" SET "); + String aeskey = null; + String fildValue = null; + List<SQLUpdateSetItem> items = updateStatement.getItems(); + for(int i = 0;i<items.size();i++){ + if(i != 0){ + splicingSql.append(","); + } + SQLUpdateSetItem item = items.get(i); + //鏌ヨ鏀瑰瓧娈垫槸鍚﹂渶瑕佸姞瀵� + aeskey = aesKeys.getOrDefault(item.getColumn().toString(),null); + + fildValue = item.getValue().toString(); + if(aeskey != null && fildValue.indexOf("AES_ENCRYPT") == -1){ + splicingSql.append(item.getColumn()+" = HEX(AES_ENCRYPT("+fildValue+",'"+aeskey+"'))"); + }else{ + splicingSql.append(item.getColumn()+" = "+fildValue); + } + } + String sqlWhere = " WHERE"; + //鎶婂墿涓嬬殑鎷兼帴涓婃潵 + if(datas.length > 1){ + for(int i =1;i<datas.length;i++){ + sqlWhere = sqlWhere+datas[i]; + } + + parser = new MySqlStatementParser("SELECT * FROM "+insertName+" "+sqlWhere); + sqlStatement = parser.parseStatement(); + + ExportTableAliasVisitor visitorTable = new ExportTableAliasVisitor(); + sqlStatement.accept(visitorTable); + + //鑾峰彇琛ㄥ拰鍒悕 + Map<String,String> tableMaps = visitorTable.getTableMap(); + tableMaps.put(insertName,null); + + //鑾峰彇鎵�鏈夌殑瀛楁 + MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); + sqlStatement.accept(visitor); + + String tableAl = null; + //閬嶅巻鎵�鏈夊瓧娈� + Collection<TableStat.Column> columns= visitor.getColumns(); + for(TableStat.Column column:columns){ + + aesKeys= aesKeysTable.get(column.getTable()); + if(aesKeys == null){ + continue; + } + aeskey = aesKeys.getOrDefault(column.getName(),null); + if(StringUtils.isEmpty(aeskey)){ + continue; + } + tableAl = tableMaps.get(column.getTable()); + if(!StringUtils.isEmpty(tableAl)){ + tableAl = tableAl+"."+column.getName(); + }else{ + tableAl = column.getName(); + } + sqlWhere = sqlWhere.replaceAll("((?<!\\.)\\b"+tableAl+"\\b(?!\\.))","AES_DECRYPT(UNHEX("+tableAl+"),'"+aeskey+"')"); + } + + } + splicingSql.append(sqlWhere); + return splicingSql.toString(); + } + + /**鍒犻櫎鍔犲瘑鏁版嵁澶勭悊 + * @param sql sql璇彞 + * @param aesKeysTable aes绉橀挜 + * @return + */ + public static String deleteSql(String sql,Map<String,Map<String,String>> aesKeysTable){ + //瑁呰浇閲嶅啓鐨剆ql璇彞 + StringBuilder splicingSql = new StringBuilder(); + + //sql = SQLUtils.format(sql, JdbcConstants.MYSQL); + MySqlStatementParser parser = new MySqlStatementParser(sql); + SQLStatement sqlStatement = parser.parseStatement(); + //鑾峰彇鏍煎紡鍖栫殑slq璇彞 + sql = sqlStatement.toString(); + + MySqlDeleteStatement deleteStatement = (MySqlDeleteStatement)sqlStatement; + + String insertName = deleteStatement.getTableName().getSimpleName(); + + String[] datas = sql.split("WHERE",2); + + Map<String,String> aesKeys = aesKeysTable.get(insertName); + if(aesKeys == null){ + return sql; + } + + splicingSql.append("DELETE FROM "+insertName); + + String aeskey = null; + + String sqlWhere = " WHERE"; + //鎶婂墿涓嬬殑鎷兼帴涓婃潵 + if(datas.length > 1){ + for(int i =1;i<datas.length;i++){ + sqlWhere = sqlWhere+datas[i]; + } + + parser = new MySqlStatementParser("SELECT * FROM "+insertName+" "+sqlWhere); + sqlStatement = parser.parseStatement(); + + ExportTableAliasVisitor visitorTable = new ExportTableAliasVisitor(); + sqlStatement.accept(visitorTable); + + //鑾峰彇琛ㄥ拰鍒悕 + Map<String,String> tableMaps = visitorTable.getTableMap(); + tableMaps.put(insertName,null); + + //鑾峰彇鎵�鏈夌殑瀛楁 + MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); + sqlStatement.accept(visitor); + + String tableAl = null; + //閬嶅巻鎵�鏈夊瓧娈� + Collection<TableStat.Column> columns= visitor.getColumns(); + for(TableStat.Column column:columns){ + + aesKeys= aesKeysTable.get(column.getTable()); + if(aesKeys == null){ + continue; + } + aeskey = aesKeys.getOrDefault(column.getName(),null); + if(StringUtils.isEmpty(aeskey)){ + continue; + } + tableAl = tableMaps.get(column.getTable()); + if(!StringUtils.isEmpty(tableAl)){ + tableAl = tableAl+"."+column.getName(); + }else{ + tableAl = column.getName(); + } + sqlWhere = sqlWhere.replaceAll("((?<!\\.)\\b"+tableAl+"\\b(?!\\.))","AES_DECRYPT(UNHEX("+tableAl+"),'"+aeskey+"')"); + } + + } + splicingSql.append(sqlWhere); + return splicingSql.toString(); + } + +} diff --git a/hx_common/src/main/java/com/hx/mybatis/aes/springbean/VariableAesKey.java b/hx_common/src/main/java/com/hx/mybatis/aes/springbean/VariableAesKey.java new file mode 100644 index 0000000..059c03e --- /dev/null +++ b/hx_common/src/main/java/com/hx/mybatis/aes/springbean/VariableAesKey.java @@ -0,0 +1,294 @@ +package com.hx.mybatis.aes.springbean; + +import com.gitee.sunchenbin.mybatis.actable.annotation.Table; +import com.hx.common.annotations.MysqlHexAes; +import com.hx.util.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import javax.annotation.Resource; +import java.io.File; +import java.io.FileFilter; +import java.io.IOException; +import java.lang.reflect.Field; +import java.net.JarURLConnection; +import java.net.URL; +import java.net.URLDecoder; +import java.util.*; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; + +/** + * 鑾峰彇鎸囧畾鍖呴噷闈㈢殑AES绉橀挜 + */ +@Component +public class VariableAesKey { + + //log4j鏃ュ織 + private static Logger logger = LoggerFactory.getLogger(VariableAesKey.class.getName()); + + @Resource + private ConstantBean constantBean; + + /**鏄惁宸茬粡鍚姩瀹�*/ + public static int isRun = 0; + + /**瀛樺偍鎵�鏈堿ES鐨勭閽�*/ + public static Map<String,String> aesKeys = new HashMap<>(); + /**鏍规嵁琛ㄦ槑鏉ュ瓨鍌ˋES绉橀挜*/ + public static Map<String,Map<String,String>> aesKeysTable = new HashMap<>(); + + /**鍥哄畾鐨刟es绉橀挜*/ + public static String AES_KEY = null; + /**鏁版嵁搴撳姞瀵嗗瓧娈靛垵濮嬪寲鐗堟湰鍙�*/ + public static String INIT_VERSION = null; + + + + /**瀛樺偍AES绉橀挜*/ + public static void setAesKey(String aesKeyFild,String aesKey){ + aesKeys.put(aesKeyFild,aesKey); + } + /**鑾峰彇AES绉橀挜*/ + public static String getAesKey(String aesKeyFild){ + if(aesKeyFild == null){ + return AES_KEY; + } + if(StringUtils.isEmpty(aesKeys.get(aesKeyFild))){ + return AES_KEY; + }else { + return aesKeys.get(aesKeyFild); + } + } + + /** + * 椤圭洰鍚姩灏辨墽琛屽悗灏辨墽琛岃鏂规硶 + */ + @PostConstruct + public void VariableAesKey(){ + System.out.println("鍔犺浇AES"); + isRun = 1; + //椤圭洰鍚姩鐨勬椂鍊欏~鍏� + logger.info("鎵弿鑾峰彇AES鐨勫寘:" + constantBean.getPackPath()); + AES_KEY = constantBean.getFixedAesKey(); + INIT_VERSION = constantBean.getInitVersion(); + if(!StringUtils.isEmpty(constantBean.getPackPath())){ + Set<Class<?>> classes = classData(constantBean.getPackPath()); + logger.info("鎵弿鑾峰彇AES鐨勫寘classes:" + classes.size()); + Map<String,String> aesKeysFild = new HashMap<>(); + boolean isAes = false; + String tableName = null; + + for(Class<?> cl:classes){ + //琛ㄥ悕绉� + boolean hasAnnotation = cl.isAnnotationPresent(Table.class); + if(!hasAnnotation){ + continue; + } + Table table = cl.getAnnotation(Table.class); + tableName = table.name(); + + aesKeysFild = new HashMap<>(); + isAes = false; + + // 鍙栧緱鏈被鐨勫叏閮ㄥ睘鎬� + Field[] fields = cl.getDeclaredFields(); + fields = getPatentFields(fields,cl); + for (Field field:fields) { + // 鍒ゆ柇鏂规硶涓槸鍚︽湁鎸囧畾娉ㄨВ绫诲瀷鐨勬敞瑙� + hasAnnotation = field.isAnnotationPresent(MysqlHexAes.class); + if (hasAnnotation) { + // 鏍规嵁娉ㄨВ绫诲瀷杩斿洖鏂规硶鐨勬寚瀹氱被鍨嬫敞瑙� + MysqlHexAes mysqlHexAes = field.getAnnotation(MysqlHexAes.class); + + //String aesKeyField = mysqlHexAes.aesKeyField(); + String aesKey = mysqlHexAes.aesKey(); + + if(StringUtils.isEmpty(aesKey)){ + aesKey = constantBean.getFixedAesKey(); + if(StringUtils.isEmpty(aesKey)){ + throw new RuntimeException("mysql鐨凙ES绉橀挜涓嶈兘涓虹┖:"+field.getName()); + } + } + String key = aesKeys.get(field.getName()); + if(StringUtils.isEmpty(key)){ + aesKeys.put(field.getName(),aesKey); + aesKeysFild.put(field.getName(),aesKey); + isAes = true; + }else{ + isAes = true; + aesKeysFild.put(field.getName(),aesKey); + if(!aesKey.equals(key)){ + throw new RuntimeException("瀛楁/瀹氫箟鐨凙ES绉橀挜瀛楁銆�"+field.getName()+"銆戝涓竴鏍凤紝浣嗘槸AES绉橀挜涓嶄竴鏍�"); + } + } + } + } + if(isAes){ + aesKeysTable.put(tableName,aesKeysFild); + } + } + } + } + + /**鑾峰彇鍖呬笅闈㈢殑鎵�鏈夋枃浠�*/ + public static Set<Class<?>> classData(String packPath){ + Set<Class<?>> classes = new LinkedHashSet(); + String[] split = packPath.split(",|;"); + String[] var3 = split; + int var4 = split.length; + + label82: + for(int var5 = 0; var5 < var4; ++var5) { + String pack = var3[var5]; + boolean recursive = true; + String packageName = pack; + String packageDirName = pack.replace('.', '/'); + + try { + Enumeration dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName); + + while(true) { + label75: + while(true) { + if (!dirs.hasMoreElements()) { + continue label82; + } + + URL url = (URL)dirs.nextElement(); + String protocol = url.getProtocol(); + if ("file".equals(protocol)) { + System.err.println("file绫诲瀷鐨勬壂鎻�:" + pack); + String filePath = URLDecoder.decode(url.getFile(), "UTF-8"); + findAndAddClassesInPackageByFile(packageName, filePath, recursive, classes); + } else if ("jar".equals(protocol)) { + System.err.println("jar绫诲瀷鐨勬壂鎻�"); + + try { + JarFile jar = ((JarURLConnection)url.openConnection()).getJarFile(); + Enumeration entries = jar.entries(); + + while(true) { + JarEntry entry; + String name; + int idx; + do { + do { + if (!entries.hasMoreElements()) { + continue label75; + } + + entry = (JarEntry)entries.nextElement(); + name = entry.getName(); + if (name.charAt(0) == '/') { + name = name.substring(1); + } + } while(!name.startsWith(packageDirName)); + + idx = name.lastIndexOf(47); + if (idx != -1) { + packageName = name.substring(0, idx).replace('/', '.'); + } + } while(idx == -1 && !recursive); + + if (name.endsWith(".class") && !entry.isDirectory()) { + String className = name.substring(packageName.length() + 1, name.length() - 6); + + try { + classes.add(Class.forName(packageName + '.' + className)); + } catch (ClassNotFoundException var20) { + var20.printStackTrace(); + } + } + } + } catch (IOException var21) { + var21.printStackTrace(); + } + } + } + } + } catch (IOException var22) { + var22.printStackTrace(); + } + } + + return classes; + } + + /** + * 浠ユ枃浠剁殑褰㈠紡鏉ヨ幏鍙栧寘涓嬬殑鎵�鏈塁lass + * + * @param packageName + * @param packagePath + * @param recursive + * @param classes + */ + public static void findAndAddClassesInPackageByFile( + String packageName, + String packagePath, + final boolean recursive, + Set<Class<?>> classes){ + // 鑾峰彇姝ゅ寘鐨勭洰褰� 寤虹珛涓�涓狥ile + File dir = new File(packagePath); + // 濡傛灉涓嶅瓨鍦ㄦ垨鑰� 涔熶笉鏄洰褰曞氨鐩存帴杩斿洖 + if (!dir.exists() || !dir.isDirectory()) { + // log.warn("鐢ㄦ埛瀹氫箟鍖呭悕 " + packageName + " 涓嬫病鏈変换浣曟枃浠�"); + return; + } + // 濡傛灉瀛樺湪 灏辫幏鍙栧寘涓嬬殑鎵�鏈夋枃浠� 鍖呮嫭鐩綍 + File[] dirfiles = dir.listFiles(new FileFilter(){ + // 鑷畾涔夎繃婊よ鍒� 濡傛灉鍙互寰幆(鍖呭惈瀛愮洰褰�) 鎴栧垯鏄互.class缁撳熬鐨勬枃浠�(缂栬瘧濂界殑java绫绘枃浠�) + @Override + public boolean accept(File file){ + return (recursive && file.isDirectory()) || (file.getName().endsWith(".class")); + } + }); + // 寰幆鎵�鏈夋枃浠� + for (File file : dirfiles){ + // 濡傛灉鏄洰褰� 鍒欑户缁壂鎻� + if (file.isDirectory()) { + findAndAddClassesInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), recursive, classes); + }else{ + // 濡傛灉鏄痡ava绫绘枃浠� 鍘绘帀鍚庨潰鐨�.class 鍙暀涓嬬被鍚� + String className = file.getName().substring(0, file.getName().length() - 6); + try{ + // 娣诲姞鍒伴泦鍚堜腑鍘� + // classes.add(Class.forName(packageName + '.' + + // className)); + // 缁忚繃鍥炲鍚屽鐨勬彁閱掞紝杩欓噷鐢╢orName鏈変竴浜涗笉濂斤紝浼氳Е鍙憇tatic鏂规硶锛屾病鏈変娇鐢╟lassLoader鐨刲oad骞插噣 + classes.add(Thread.currentThread().getContextClassLoader().loadClass(packageName + '.' + className)); + }catch (ClassNotFoundException e){ + // log.error("娣诲姞鐢ㄦ埛鑷畾涔夎鍥剧被閿欒 鎵句笉鍒版绫荤殑.class鏂囦欢"); + e.printStackTrace(); + } + } + } + } + + /** + * 鑾峰彇鐖剁被鐨勫瓧娈� + * @param fields + * @param clas + * @return + */ + public static Field[] getPatentFields(Field[] fields,Class<?> clas){ + if (clas.getSuperclass() != null) { + Class clsSup = clas.getSuperclass(); + List<Field> fieldList = new ArrayList<Field>(); + fieldList.addAll(Arrays.asList(fields)); + fieldList.addAll(Arrays.asList(clsSup.getDeclaredFields())); + fields = new Field[fieldList.size()]; + int i = 0; + for (Object field : fieldList.toArray()) { + fields[i] = (Field) field; + i++; + } + fields = getPatentFields(fields,clsSup); + } + return fields; + } + + +} diff --git a/hx_common/src/main/java/com/hx/mybatis/date/handler/GenericDateHandler.java b/hx_common/src/main/java/com/hx/mybatis/date/handler/GenericDateHandler.java new file mode 100644 index 0000000..187ea91 --- /dev/null +++ b/hx_common/src/main/java/com/hx/mybatis/date/handler/GenericDateHandler.java @@ -0,0 +1,38 @@ +package com.hx.mybatis.date.handler; + +import org.apache.ibatis.type.BaseTypeHandler; +import org.apache.ibatis.type.JdbcType; +import org.apache.ibatis.type.MappedJdbcTypes; +import org.apache.ibatis.type.MappedTypes; + +import java.sql.*; +import java.time.LocalDateTime; + +/** + * @author CJH + * @Date 2021-01-02 + * // @MappedTypes娉ㄨВ涓殑绫讳唬琛ㄦ杞崲鍣ㄥ彲浠ヨ嚜鍔ㄨ浆鎹负鐨刯ava瀵硅薄锛孈MappedJdbcTypes娉ㄨВ涓缃殑鏄搴旂殑jdbctype锛宮ysql鐨刯son瀵硅薄瀵瑰簲鐨刯dbctype涓篤ARCHAR銆� + */ +@MappedTypes(value = {LocalDateTime.class}) +@MappedJdbcTypes(value = {JdbcType.TIMESTAMP}, includeNullJdbcType = true) +public class GenericDateHandler extends BaseTypeHandler<Timestamp> { + + public GenericDateHandler() { + } + + public void setNonNullParameter(PreparedStatement ps, int i, Timestamp parameter, JdbcType jdbcType) throws SQLException { + ps.setTimestamp(i, parameter); + } + + public Timestamp getNullableResult(ResultSet rs, String columnName) throws SQLException { + return rs.getTimestamp(columnName); + } + + public Timestamp getNullableResult(ResultSet rs, int columnIndex) throws SQLException { + return rs.getTimestamp(columnIndex); + } + + public Timestamp getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { + return cs.getTimestamp(columnIndex); + } +} diff --git a/hx_common/src/main/java/com/hx/mybatisTool/SqlSentence.java b/hx_common/src/main/java/com/hx/mybatisTool/SqlSentence.java new file mode 100644 index 0000000..882a2a9 --- /dev/null +++ b/hx_common/src/main/java/com/hx/mybatisTool/SqlSentence.java @@ -0,0 +1,251 @@ +package com.hx.mybatisTool; + +import com.hx.exception.TipsException; +import com.hx.util.SimpleTool; +import com.hx.util.StringUtils; + +import java.util.Map; + +/** + * mybatis 鑷畾涔夊鐞唖ql璇彞 + * @author chenjiahe + * @Data: 2020-06-08 + */ +public class SqlSentence { + + /**鎵ц璇彞*/ + private String sqlSentence; + + /**鏂板瀛樺湪鏌ヨ鍒ゆ柇*/ + private String whereExist; + + private Map<String,Object> m; + /**鎺掑簭*/ + private String orderBy; + /**寮�濮嬮〉鏁�*/ + private Integer startPage = 0; + /**姣忛〉鏁伴噺*/ + private Integer pageNum = 0; + /**鏉℃暟锛堝綋鍓嶇被浣跨敤锛�*/ + private Integer pageSize; + + ////////////////////////////////////////////////////////////// + + /********************mother****************************/ + + public SqlSentence() + { + + } + + public SqlSentence(Class c, String where, Map<String, Object> values) + { + if(StringUtils.isEmpty(where)) + { + throw new TipsException("sql is null"); + } + + if(values == null) + { + throw new TipsException("values is null"); + } + + sqlSentence = "select * from " + c.getSimpleName()+ " where " + where; + m = values; + } + + public SqlSentence(String where, Map<String, Object> values) + { + if(StringUtils.isEmpty(where)) + { + throw new TipsException("sql is null"); + } + + if(values == null) + { + throw new TipsException("values is null"); + } + + sqlSentence = where; + m = values; + } + + + /** + * sql鏁存潯璇彞 + * @param sql 濡傦細select * from user Where name = #{m.userName} order by age desc + * @param values 瀛樻斁鐨勫�煎锛歷alues.put("userName","ChenJiaHe") + */ + public void sqlSentence(String sql,Map<String,Object> values) { + if(StringUtils.isEmpty(sql)) + { + throw new TipsException("sql is null"); + } + + if(values == null) + { + throw new TipsException("values is null"); + } + + sqlSentence = sql; + m = values; + } + + /** + * sql鏁存潯璇彞-鍒嗛〉 + * @param sql 濡傦細select * from user Where name = #{m.userName} order by age desc + * @param values 瀛樻斁鐨勫�煎锛歷alues.put("userName","ChenJiaHe") + * @param pageNum 褰撳墠椤垫暟 + * @param pageSize 褰撳墠鏉℃暟 + */ + public void sqlSentencePage(String sql,Map<String,Object> values,int pageNum,int pageSize) { + if(StringUtils.isEmpty(sql)) { + throw new TipsException("sql is null"); + } + + if(values == null) { + throw new TipsException("values is null"); + } + if(pageNum < 1){ + pageNum = 1; + } + if(pageSize < 1){ + pageSize = 1; + } + this.pageNum = pageNum; + this.pageSize = pageSize; + + //绠楄捣鐐� + int pageStart = (pageNum-1)*pageSize; + sql = sql+" LIMIT "+pageStart+","+pageSize; + sqlSentence = sql; + m = values; + } + + /**鍒嗛〉缁勮淇℃伅 + * @param data 瑁呰浇淇℃伅 + * @param totalNum 鎬婚〉鏁� + * @return 瑁呰浇淇℃伅 + */ + public Map<String,Object> pageAssembleData(Map<String,Object> data,int totalNum){ + data.put("pageNum",pageNum); + data.put("pageSize",pageSize); + data.put("total",totalNum); + int pages; + if(pageSize > 0){ + if(totalNum%pageSize > 0){ + pages = totalNum/pageSize+1; + }else{ + pages = totalNum/pageSize; + } + }else{ + pages = 0; + } + data.put("pages",pages); + if(pages <= pageNum){ + data.put("isLastPage",true); + }else{ + data.put("isLastPage",false); + } + return data; + } + + + /** + * 鏌ヨ鐨勮鍙� + * @param sql 濡傦細id = #{m.userId} order by age DESC + * @param values 瀛樻斁鐨勫�煎锛歷alues.put("userId","123456") + */ + public void sqlWhere(String sql,Map<String,Object> values) { + if(!SimpleTool.checkNotNull(values)){ + throw new TipsException("values is null"); + } + if(!SimpleTool.checkNotNull(sql)) { + sql = "1=1"; + } + sqlSentence = sql; + m = values; + } + + /** + * 鏇存柊璇彞鐨勮鍙� + * @param sql 濡傦細name = #{m.name},age = ? WHERE id = #{m.id} + * @param values 瀛樻斁鐨勫�� + */ + public void sqlUpdate(String sql,Map<String,Object> values) { + if(!SimpleTool.checkNotNull(values)){ + throw new TipsException("values is null"); + } + m = values; + sqlSentence = sql; + } + + + /************************************************************************/ + + public Map<String, Object> getM() { + return m; + } + + public void setM(Map<String, Object> m) { + this.m = m; + } + + public String getSqlSentence() { + return sqlSentence; + } + + public void setSqlSentence(String sqlSentence) { + this.sqlSentence = sqlSentence; + } + + public String getOrderBy() { + return orderBy; + } + + public void setOrderBy(String orderBy) { + this.orderBy = orderBy; + } + + public Integer getStartPage() { + return startPage; + } + + public void setStartPage(Integer startPage) { + this.startPage = startPage; + } + + public Integer getPageNum() { + return pageNum; + } + + public void setPageNum(Integer pageNum) { + this.pageNum = pageNum; + } + + public Integer getStartIndex() + { + return (startPage - 1) * pageNum; + } + + public String getWhereExist() { + return whereExist; + } + + public void setWhereExist(String whereExist) { + if(StringUtils.isNull(whereExist)){ + whereExist = null; + } + this.whereExist = whereExist; + } + + public Integer getPageSize() { + return pageSize; + } + + public void setPageSize(Integer pageSize) { + this.pageSize = pageSize; + } +} + + diff --git a/hx_common/src/main/java/com/hx/mybatisTool/SqlStringTool.java b/hx_common/src/main/java/com/hx/mybatisTool/SqlStringTool.java new file mode 100644 index 0000000..1941897 --- /dev/null +++ b/hx_common/src/main/java/com/hx/mybatisTool/SqlStringTool.java @@ -0,0 +1,172 @@ +package com.hx.mybatisTool; + +import com.hx.util.StringUtils; + +import java.util.List; +import java.util.Map; + +/** + * Sql宸ュ叿绫� + * @author fwq + */ +public class SqlStringTool { + + /**鍩虹key*/ + private static final String BASE_KEY = "k"; + /**AND绗﹀彿*/ + private static final String AND_STR = " AND "; + /**宸﹁竟鎷彿鎷兼帴*/ + private static final String LEFT_STR = "#{m."; + /**鍙宠竟鎷彿鎷兼帴*/ + private static final String RIGHT_STR = "}"; + /**閫楀彿鍒嗛殧*/ + private static final String SIGN_STR = ","; + /**IN宸︾鍙�*/ + private static final String IN_LEFT = " IN ( "; + /**IN鍙崇鍙�*/ + private static final String IN_RIGHT = " ) "; + + /** + * 閫掑綊key,鐩村埌涓嶉噸澶�,杩欎釜閫掑綊鏄拡瀵瑰悓涓�涓猻qlMap,闃叉鍚屾柟娉曞涓煡璇㈡椂瀛樺湪key瑕嗙洊闂銆� + * PS:寤鸿鏌ヨ瀹屼笂涓�娆�,娓呯悊sqlMap鍚庡啀浼犻�掕繘鏉�,鍑忓皯閫掑綊鐨勬搷浣� + */ + private static String getKey(String key, Map<String, Object> sqlMap) { + if (sqlMap.get(key) != null) { + getKey(BASE_KEY + key, sqlMap); + } + return key; + } + + /** + * 鎷兼帴sql璇彞 + * @param sql StringBuilder鐨剆ql璇彞 + * @param tableColumn 鍚埆鍚嶈〃瀛楁,渚嬪:user AS u 鏍规嵁id鏌ヨ鏃朵紶閫抲.id + * @param dataList 瑕佸惊鐜殑鏁板��,List闆嗗悎 + * @param sqlMap sql璇彞瀵瑰簲鐨勫弬鏁癕ap + */ + public static void handleList(StringBuilder sql, String tableColumn, List<String> dataList, Map<String, Object> sqlMap) { + if (sql == null || StringUtils.isEmpty(tableColumn) || dataList == null || dataList.size() < 1) { + return; + } + String key = null; + sql.append(AND_STR).append(tableColumn).append(IN_LEFT); + for (int i = 0; i < dataList.size(); i++) { + key = getKey(BASE_KEY + i, sqlMap); + sql.append(LEFT_STR).append(key).append(RIGHT_STR).append(SIGN_STR); + sqlMap.put(key, dataList.get(i)); + } + sql.deleteCharAt(sql.length() - 1).append(IN_RIGHT); + } + + + /** + * 鎷兼帴sql璇彞 + * @param sql StringBuffer鐨剆ql璇彞 + * @param tableColumn 鍚埆鍚嶈〃瀛楁,渚嬪:user AS u 鏍规嵁id鏌ヨ鏃朵紶閫抲.id + * @param dataList 瑕佸惊鐜殑鏁板��,List闆嗗悎 + * @param sqlMap sql璇彞瀵瑰簲鐨勫弬鏁癕ap + */ + public static void handleList(StringBuffer sql, String tableColumn, List<String> dataList, Map<String, Object> sqlMap) { + if (sql == null || StringUtils.isEmpty(tableColumn) || dataList == null || dataList.size() < 1) { + return; + } + String key = null; + sql.append(AND_STR).append(tableColumn).append(IN_LEFT); + for (int i = 0; i < dataList.size(); i++) { + key = getKey(BASE_KEY + i, sqlMap); + sql.append(LEFT_STR).append(key).append(RIGHT_STR).append(SIGN_STR); + sqlMap.put(key, dataList.get(i)); + } + sql.deleteCharAt(sql.length() - 1).append(IN_RIGHT); + } + + /** + * 鎷兼帴sql璇彞 + * @param sql StringBuilder鐨剆ql璇彞 + * @param tableColumn 鍚埆鍚嶈〃瀛楁,渚嬪:user AS u 鏍规嵁id鏌ヨ鏃朵紶閫抲.id + * @param dataList 瑕佸惊鐜殑鏁板��,String鏁扮粍 + * @param sqlMap sql璇彞瀵瑰簲鐨勫弬鏁癕ap + */ + public static void handleList(StringBuilder sql, String tableColumn, String[] dataList, Map<String, Object> sqlMap) { + if (sql == null || StringUtils.isEmpty(tableColumn) || dataList == null || dataList.length < 1) { + return; + } + String key = null; + sql.append(AND_STR).append(tableColumn).append(IN_LEFT); + for (int i = 0; i < dataList.length; i++) { + key = getKey(BASE_KEY + i, sqlMap); + sql.append(LEFT_STR).append(key).append(RIGHT_STR).append(SIGN_STR); + sqlMap.put(key, dataList[i]); + } + sql.deleteCharAt(sql.length() - 1).append(IN_RIGHT); + } + + /** + * 鎷兼帴sql璇彞 + * @param sql StringBuffer鐨剆ql璇彞 + * @param tableColumn 鍚埆鍚嶈〃瀛楁,渚嬪:user AS u 鏍规嵁id鏌ヨ鏃朵紶閫抲.id + * @param dataList 瑕佸惊鐜殑鏁板��,String鏁扮粍 + * @param sqlMap sql璇彞瀵瑰簲鐨勫弬鏁癕ap + */ + public static void handleList(StringBuffer sql, String tableColumn, String[] dataList, Map<String, Object> sqlMap) { + if (sql == null || StringUtils.isEmpty(tableColumn) || dataList == null || dataList.length < 1) { + return; + } + String key = null; + sql.append(AND_STR).append(tableColumn).append(IN_LEFT); + for (int i = 0; i < dataList.length; i++) { + key = getKey(BASE_KEY + i, sqlMap); + sql.append(LEFT_STR).append(key).append(RIGHT_STR).append(SIGN_STR); + sqlMap.put(key, dataList[i]); + } + sql.deleteCharAt(sql.length() - 1).append(IN_RIGHT); + } + + /** + * 鎷兼帴sql璇彞 + * @param sql StringBuilder鐨剆ql璇彞 + * @param tableColumn 鍚埆鍚嶈〃瀛楁,渚嬪:user AS u 鏍规嵁id鏌ヨ鏃朵紶閫抲.id + * @param dataList 瑕佸惊鐜殑鏁板��,Map鏁扮粍瀵硅薄 + * @param dataListKey Map鏁扮粍瀵硅薄涓寰幆鍊煎搴旂殑key + * @param sqlMap sql璇彞瀵瑰簲鐨勫弬鏁癕ap + */ + public static void handleList(StringBuilder sql, String tableColumn, List<Map<String, Object>> dataList, String dataListKey, Map<String, Object> sqlMap) { + if (sql == null || StringUtils.isEmpty(tableColumn) || dataList == null || dataList.size() < 1) { + return; + } + String key = null; + sql.append(AND_STR).append(tableColumn).append(IN_LEFT); + for (int i = 0; i < dataList.size(); i++) { + key = getKey(BASE_KEY + i, sqlMap); + sql.append(LEFT_STR).append(key).append(RIGHT_STR).append(SIGN_STR); + sqlMap.put(key, dataList.get(i).get(dataListKey)); + } + sql.deleteCharAt(sql.length() - 1).append(IN_RIGHT); + } + + /** + * 鎷兼帴sql璇彞 + * @param sql StringBuffer鐨剆ql璇彞 + * @param tableColumn 鍚埆鍚嶈〃瀛楁,渚嬪:user AS u 鏍规嵁id鏌ヨ鏃朵紶閫抲.id + * @param dataList 瑕佸惊鐜殑鏁板��,Map鏁扮粍瀵硅薄 + * @param dataListKey Map鏁扮粍瀵硅薄涓寰幆鍊煎搴旂殑key + * @param sqlMap sql璇彞瀵瑰簲鐨勫弬鏁癕ap + */ + public static void handleList(StringBuffer sql, String tableColumn, List<Map<String, Object>> dataList, String dataListKey, Map<String, Object> sqlMap) { + if (sql == null || StringUtils.isEmpty(tableColumn) || dataList == null || dataList.size() < 1) { + return; + } + String key = null; + sql.append(AND_STR).append(tableColumn).append(IN_LEFT); + for (int i = 0; i < dataList.size(); i++) { + key = getKey(BASE_KEY + i, sqlMap); + sql.append(LEFT_STR).append(key).append(RIGHT_STR).append(SIGN_STR); + sqlMap.put(key, dataList.get(i).get(dataListKey)); + } + sql.deleteCharAt(sql.length() - 1).append(IN_RIGHT); + } + + +} + + diff --git a/hx_common/src/main/java/com/hx/platform/tool/PlatformSign.java b/hx_common/src/main/java/com/hx/platform/tool/PlatformSign.java new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/hx_common/src/main/java/com/hx/platform/tool/PlatformSign.java diff --git a/hx_common/src/main/java/com/hx/redis/RedisConfig.java b/hx_common/src/main/java/com/hx/redis/RedisConfig.java new file mode 100644 index 0000000..834af2f --- /dev/null +++ b/hx_common/src/main/java/com/hx/redis/RedisConfig.java @@ -0,0 +1,34 @@ +package com.hx.redis; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.PropertyAccessor; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +@Configuration +@EnableCaching +public class RedisConfig { + @Bean + public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { + RedisTemplate<String, Object> template = new RedisTemplate<String, Object>(); + template.setConnectionFactory(factory); + Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); + ObjectMapper om = new ObjectMapper(); + om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); + om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); + jackson2JsonRedisSerializer.setObjectMapper(om); + StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); + template.setKeySerializer(stringRedisSerializer); + template.setHashKeySerializer(stringRedisSerializer); + template.setValueSerializer(jackson2JsonRedisSerializer); + template.setHashValueSerializer(jackson2JsonRedisSerializer); + template.afterPropertiesSet(); + return template; + } +} diff --git a/hx_common/src/main/java/com/hx/redis/RedisUtil.java b/hx_common/src/main/java/com/hx/redis/RedisUtil.java new file mode 100644 index 0000000..d9b582b --- /dev/null +++ b/hx_common/src/main/java/com/hx/redis/RedisUtil.java @@ -0,0 +1,414 @@ +package com.hx.redis; + +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + + +/** + * 鏂囦欢澶勭悊宸ュ叿 + * + * @author wangrenhuang + * @Date 2021-10-19 + */ +@Component +public class RedisUtil { + /** + * [redis] + */ + @Resource + private RedisTemplate<String, Object> redisTemplate; + + /** + * 鍒囨崲鏁版嵁搴� + * @param dataNumber 鏁版嵁搴撶紪鍙� + */ + public void setDataBase(int dataNumber) { + LettuceConnectionFactory connectionFactory = (LettuceConnectionFactory) redisTemplate.getConnectionFactory(); + if (connectionFactory != null && dataNumber != connectionFactory.getDatabase()) { + connectionFactory.setDatabase(dataNumber); + this.redisTemplate.setConnectionFactory(connectionFactory); + connectionFactory.resetConnection(); + } + } + + /** + * [鍒ゆ柇key鏄惁瀛樺湪] + * + * @param key 閿� + * @return true 瀛樺湪 false涓嶅瓨鍦� + */ + public boolean hasKey(String key) { + try { + return redisTemplate.hasKey(key); + } catch (Exception e) { + return false; + } + } + + /** + * [鏅�氱紦瀛樿幏鍙朷 + * + * @param key 閿� + * @return 鍊� + */ + public Object get(String key) { + return key == null ? null : redisTemplate.opsForValue().get(key); + } + + /** + * [鏅�氱紦瀛樺垹闄 + * + * @param key 閿� + * @return 鍊� + */ + public boolean delete(String key) { + try { + Boolean aBoolean = redisTemplate.hasKey(key); + return aBoolean == false ? true : redisTemplate.delete(key); + } catch (Exception e) { + return false; + } + } + + /** + * [鏅�氱紦瀛樻斁鍏 + * + * @param key 閿� + * @param value 鍊� + * @return true鎴愬姛 false澶辫触 + */ + public boolean set(String key, Object value) { + try { + redisTemplate.opsForValue().set(key, value); + return true; + } catch (Exception e) { + return false; + } + } + + + /** + * 鏅�氱紦瀛樻斁鍏ュ苟璁剧疆鏃堕棿 + * + * @param key 閿� + * @param value 鍊� + * @param time 鏃堕棿(绉�) time瑕佸ぇ浜�0 濡傛灉time灏忎簬绛変簬0 灏嗚缃棤闄愭湡 + * @return true鎴愬姛 false 澶辫触 + */ + public boolean set(String key, Object value, long time) { + try { + if (time > 0) { + redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); + } else { + set(key, value); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 26 + * 鎸囧畾缂撳瓨澶辨晥鏃堕棿 + * 27 + * + * @param key 閿� + * 28 + * @param time 鏃堕棿(绉�) + * 29 + * @return 30 + */ + + public boolean expire(String key, long time) { + try { + if (time > 0) { + redisTemplate.expire(key, time, TimeUnit.SECONDS); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + + } + + } + + /** + * 璁剧疆鍒版湡鏃堕棿 + * @param key 瀵瑰簲閿� + * @param time 鏃堕暱 + * @param timeUnit 鏃堕棿鍗曚綅 + * @return + */ + public boolean expire(String key, long time, TimeUnit timeUnit) { + try { + if (time > 0) { + return redisTemplate.expire(key, time, timeUnit); + } + } catch (Exception e) { + e.printStackTrace(); + return false; + + } + return false; + } + + + /** + * hash 鍒犻櫎鎿嶄綔 + * + * @param key 閿� + * @param valueKey 鍊� + * @return true鎴愬姛 false 澶辫触 + */ + public boolean hashDel(String key, Object... valueKey) { + try { + redisTemplate.opsForHash().delete(key,valueKey); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * hash 璁剧疆hashMapt鎿嶄綔 + * + * @param key 閿� + * @return true鎴愬姛 false 澶辫触 + */ + public boolean hashSetMap(String key, Map<String,Object> map) { + try { + redisTemplate.opsForHash().putAll(key, map); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * hash 璁剧疆鍗曚釜hashMap鎿嶄綔 + * + * @param key 閿� + * @return true鎴愬姛 false 澶辫触 + */ + public boolean hashSet(String hashKey, String key, Object value) { + try { + redisTemplate.opsForHash().put(hashKey,key,value); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * hash 鑾峰彇鏁翠釜hashKey鏁版嵁 + * + * @param hashKey 閿� + * @return true鎴愬姛 false 澶辫触 + */ + public Map<Object, Object> hashGetAll(String hashKey) { + try { + return redisTemplate.opsForHash().entries(hashKey); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * hash 鑾峰彇鍗曚釜hashKey + * + * @param hashKey 閿� + * @return true鎴愬姛 false 澶辫触 + */ + public Object hashGet(String hashKey,Object key) { + try { + return redisTemplate.opsForHash().get(hashKey,key); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * list 鏂板-宸︽彃鍏� + * + * @param listKey 閿� + * @return true鎴愬姛 false 澶辫触 + */ + public Object leftPush(String listKey,Object value) { + try { + return redisTemplate.opsForList().leftPush(listKey,value); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * list 鏂板-宸︽彃鍏�(瀛樺湪鎵嶆彃鍏�) + * + * @param listKey 閿� + * @return true鎴愬姛 false 澶辫触 + */ + public Object leftPushIfPresent(String listKey,Object value) { + try { + return redisTemplate.opsForList().leftPushIfPresent(listKey,value); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * list 鏂板-鍙虫彃鍏�(瀛樺湪鎵嶆彃鍏�) + * + * @param listKey 閿� + * @return true鎴愬姛 false 澶辫触 + */ + public Object rightPushIfPresent(String listKey,Object value) { + try { + return redisTemplate.opsForList().rightPushIfPresent(listKey,value); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * list 鏂板-鍙虫彃鍏� + * + * @param listKey 閿� + * @return true鎴愬姛 false 澶辫触 + */ + public Object rightPush(String listKey,Object value) { + try { + return redisTemplate.opsForList().rightPush(listKey,value); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * list 寮瑰嚭-宸� + * + * @param listKey 閿� + * @return true鎴愬姛 false 澶辫触 + */ + public Object leftPop(String listKey) { + try { + return redisTemplate.opsForList().leftPop(listKey); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * list 寮瑰嚭-鍙� + * + * @param listKey 閿� + * @return true鎴愬姛 false 澶辫触 + */ + public Object rightPop(String listKey) { + try { + return redisTemplate.opsForList().rightPop(listKey); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * list 鑾峰彇绱㈠紩涓嬬殑鍊� + * + * @param key 閿� + * @param index 绱㈠紩 + * @return true鎴愬姛 false 澶辫触 + */ + public Object listGet(String key, long index) { + try { + return redisTemplate.opsForList().index(key,index); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * list 鑾峰彇绱㈠紩涓嬬殑鍊� + * + * @param key 閿� + * @param start 寮�濮嬩綅缃� 0鏄紑濮嬩綅缃� + * @param end 缁撴潫浣嶇疆,-1杩斿洖鎵�鏈� + * @return true鎴愬姛 false 澶辫触 + */ + public List<Object> listGetRange(String key, long start , long end) { + try { + return redisTemplate.opsForList().range(key, start, end); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * list 鑾峰彇闀垮害 + * + * @param listKey 閿� + * @return true鎴愬姛 false 澶辫触 + */ + public Object listSize(String listKey) { + try { + return redisTemplate.opsForList().size(listKey); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * list 鍒犻櫎 + * + * @param listKey 閿� + * @param index index=0, 鍒犻櫎鎵�鏈夊�肩瓑浜巚alue鐨勫厓绱�; index>0, 浠庡ご閮ㄥ紑濮嬪垹闄ょ涓�涓�肩瓑浜巚alue鐨勫厓绱�; index<0, 浠庡熬閮ㄥ紑濮嬪垹闄ょ涓�涓�肩瓑浜巚alue鐨勫厓绱� + * @param value 鍒犻櫎鐨勫�� + * @return true鎴愬姛 false 澶辫触 + */ + public Object listRemove(String listKey,long index,Object value) { + try { + return redisTemplate.opsForList().remove(listKey, index, value); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * @param key 閿� + * @param value 鍊� + * @param timeOut 鏃堕棿 + * @param unit 鏃堕棿鍗曚綅 + */ + public Boolean setIfAbsent(String key, Object value, long timeOut, TimeUnit unit) { + try { + return redisTemplate.opsForValue().setIfAbsent(key, value, timeOut, unit); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + +} diff --git a/hx_common/src/main/java/com/hx/repeat/check/RequestRepeatUtil.java b/hx_common/src/main/java/com/hx/repeat/check/RequestRepeatUtil.java new file mode 100644 index 0000000..39f1703 --- /dev/null +++ b/hx_common/src/main/java/com/hx/repeat/check/RequestRepeatUtil.java @@ -0,0 +1,76 @@ +package com.hx.repeat.check; + +import com.hx.common.annotations.repeat.RequestRepeat; +import com.hx.exception.TipsException; +import com.hx.redis.RedisUtil; +import com.hx.util.DateUtil; +import com.hx.util.IPUtils; + +import javax.servlet.http.HttpServletRequest; +import java.lang.reflect.Method; +import java.util.Date; +import java.util.concurrent.TimeUnit; + +/** + * URL闃查噸澶嶆彁浜� + * @author CJH + */ +public class RequestRepeatUtil { + + /**璇锋眰閲嶅鏍¢獙 + * 鐩墠鍖哄垎閲嶅鏄疘P鍦板潃鍜岃姹傛柟娉曪紝濡傛灉鎯宠鏇寸簿鍑嗭紝浼燾ode + * @param code 鍓嶇紑鏍囪瘑锛岀敤浜庡尯鍒嗕笉鍚岃姹傛潵婧愶紝闀垮害鏈�濂�12浣嶄箣鍐咃紝鍙┖ + * @param request HttpServletRequest + * @param redisUtil redis + * @param millisecond 闂撮殧鏃堕棿锛屾绉掞紙榛樿500姣锛� + * @param annotateCheck 鏄惁娉ㄨВ鏍¢獙锛屽鏋滄槸锛屽皢浠ユ敞瑙f潵鍋氭牎楠岋紝鍚﹀垯灏卞叏閮ㄥ仛鏍¢獙 + * @param method 璇锋眰鏂规硶锛屾柟娉曟垨鑰呯被涓婇潰鏈夋牎楠屾敞瑙o紝娉ㄨВ璺宠繃鎴栬�呮嫤鎴� + */ + public static void checkRequest(String code,HttpServletRequest request, RedisUtil redisUtil, Long millisecond + , boolean annotateCheck, Method method){ + //浼樺厛鏍¢獙娉ㄨВ锛屼紭鍏堟柟娉曞啀鍒扮被 + RequestRepeat requestRepeat = method.getAnnotation(RequestRepeat.class); + if(requestRepeat != null){ + if(requestRepeat.isRepeat()){ + check(code,request,redisUtil,requestRepeat.millisecond()); + }else{ + return; + } + }else{ + requestRepeat = method.getClass().getAnnotation(RequestRepeat.class); + if(requestRepeat != null){ + if(requestRepeat.isRepeat()){ + check(code,request,redisUtil,requestRepeat.millisecond()); + }else{ + return; + } + } + } + //閫氳繃娉ㄨВ鏍¢獙锛屼笉闇�瑕佸叏閮� + if(!annotateCheck){ + check(code,request,redisUtil,millisecond); + } + } + + public static void check(String code,HttpServletRequest request,RedisUtil redisUtil,Long millisecond){ + //娌℃湁璁剧疆锛岄粯璁�0.5绉� + if(millisecond == null){ + millisecond = 500L; + } + //鑾峰彇璇锋眰鐨処P鍦板潃 + String ip = IPUtils.getIpAddr(request); + //鑾峰彇URL + String method = request.getServletPath(); + if(code != null){ + code = code+"-"+ip+"-"+method; + }else{ + code = ip+"-"+method; + } + if(!redisUtil.setIfAbsent(code, DateUtil.formatDate(new Date(),"yyyy-MM-dd HH:mm:ss"),millisecond, TimeUnit.MILLISECONDS)){ + throw new TipsException("璇峰嬁棰戠箒鎿嶄綔锛�"); + } + + } + + +} diff --git a/hx_common/src/main/java/com/hx/resultTool/ResponseCode.java b/hx_common/src/main/java/com/hx/resultTool/ResponseCode.java new file mode 100644 index 0000000..73e2f9a --- /dev/null +++ b/hx_common/src/main/java/com/hx/resultTool/ResponseCode.java @@ -0,0 +1,30 @@ +package com.hx.resultTool; + +/** + * 缁熶竴鐘舵�佺爜 + * @author chenjiahe + * @Data: 2020-06-20 + */ +public final class ResponseCode { + + /*鎴愬姛*/ + public static final String SUCCESS = "100"; + /*閿欒鎻愮ず锛屽墠绔牴鎹繖涓爜寮瑰嚭鎻愮ず*/ + public static final String ERROR_TIPS="200"; + /*鍙傛暟楠岃瘉閿欒*/ + public static final String ERROR_PARAMS_VALIDATOR="205"; + /*涓氬姟楠岃瘉閿欒*/ + public static final String ERROR_SERVICE_VALIDATOR="300"; + /*绯荤粺鏁版嵁閿欒*/ + public static final String ERROR_DATA_VALIDATOR="400"; + /*鐧诲綍鏈夎*/ + public static final String ERROR_LOGIN="603"; + /*绯荤粺寮傚父*/ + public static final String ERROR_SYSTEM = "999"; + /*绛惧悕閿欒*/ + public static final String ERROR_SIGN = "203"; + + + +} + diff --git a/hx_common/src/main/java/com/hx/resultTool/Result.java b/hx_common/src/main/java/com/hx/resultTool/Result.java new file mode 100644 index 0000000..5c696b0 --- /dev/null +++ b/hx_common/src/main/java/com/hx/resultTool/Result.java @@ -0,0 +1,125 @@ +package com.hx.resultTool; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.hx.exception.TipsException; + +import java.io.Serializable; +import java.util.List; + +/** + * 缁熶竴杩斿洖鏍煎紡 + * @author chenjiahe + * @Data: 2020-06-20 + */ +public class Result implements Serializable { + + private static final long serialVersionUID = -3948389268046368059L; + + private String code; + + private String msg; + + private Object data; + + public Result() {} + + public Result(String code, String msg) { + this.code = code; + this.msg = msg; + } + + public static Result success() { + Result Result = new Result(); + Result.setCode(ResponseCode.SUCCESS); + Result.setMsg("SUCCESS"); + return Result; + } + + public static Result success(Object data) { + Result Result = new Result(); + Result.setCode(ResponseCode.SUCCESS); + Result.setData(data); + Result.setMsg("SUCCESS"); + return Result; + } + + public static Result failure(String code, String msg) { + Result Result = new Result(); + Result.setCode(code); + Result.setMsg(msg); + return Result; + } + + public static Result failure(String code, String msg, Object data) { + Result Result = new Result(); + Result.setCode(code); + Result.setMsg(msg); + Result.setData(data); + return Result; + } + + /**鏍¢獙杩斿洖鐮�*/ + public Boolean checkCode(){ + if(ResponseCode.SUCCESS.equals(code)){ + return true; + } + return false; + } + + /**鏍¢獙杩斿洖鐮侊紝杩涜閿欒鎻愮ず*/ + public void checkTips(){ + if(!ResponseCode.SUCCESS.equals(code)){ + throw new TipsException("璇锋眰澶辫触锛�"+this.code+","+this.msg); + } + } + + /**杩斿洖鏁版嵁杞琂SONObject*/ + public JSONObject getJsonObject(Object data){ + return JSONObject.parseObject(JSON.toJSONString(data)); + } + + /**杩斿洖鏁版嵁杞琂SONArray*/ + public JSONArray getJsonArray(Object data){ + return JSONArray.parseArray(JSON.toJSONString(data)); + } + + /**杩斿洖鏁版嵁杞璞�*/ + public <T> T getObject(Object data, Class<T> clazz) { + return JSONObject.parseObject(JSON.toJSONString(data), clazz); + } + + /**杩斿洖鏁版嵁杞垪琛�*/ + public <T> List<T> getArray(Object data, Class<T> clazz) { + return JSONArray.parseArray(JSON.toJSONString(data), clazz); + } + + /*******************************************************************************/ + + public String getCode() { + return this.code; + } + + public void setCode(final String code) { + this.code = code; + } + + public String getMsg() { + return this.msg; + } + + public void setMsg(final String msg) { + this.msg = msg; + } + + public Object getData() { + return this.data; + } + + public void setData(final Object data) { + this.data = data; + } + +} + diff --git a/hx_common/src/main/java/com/hx/security/request/RequestRestriction.java b/hx_common/src/main/java/com/hx/security/request/RequestRestriction.java new file mode 100644 index 0000000..825855c --- /dev/null +++ b/hx_common/src/main/java/com/hx/security/request/RequestRestriction.java @@ -0,0 +1,39 @@ +package com.hx.security.request; + +import org.apache.tomcat.util.descriptor.web.SecurityCollection; +import org.apache.tomcat.util.descriptor.web.SecurityConstraint; +import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; +import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/**璁剧疆闄愬埗璇锋眰*/ +@Configuration +public class RequestRestriction { + + @Bean + public ConfigurableServletWebServerFactory configurableServletWebServerFactory() { + TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(); + factory.addContextCustomizers(context -> { + SecurityConstraint securityConstraint = new SecurityConstraint(); + securityConstraint.setUserConstraint("CONFIDENTIAL"); + SecurityCollection collection = new SecurityCollection(); + //璁剧疆涓嶅畨鍏ㄨ姹備笉鑳介�氳繃 + collection.addPattern("/*"); + collection.addMethod("HEAD"); + collection.addMethod("PUT"); + collection.addMethod("DELETE"); + collection.addMethod("OPTIONS"); + collection.addMethod("TRACE"); + collection.addMethod("COPY"); + collection.addMethod("SEARCH"); + collection.addMethod("PROPFIND"); + //collection.addMethod("PATCH"); + securityConstraint.addCollection(collection); + context.addConstraint(securityConstraint); + }); + return factory; + } + + +} diff --git a/hx_common/src/main/java/com/hx/util/Aes.java b/hx_common/src/main/java/com/hx/util/Aes.java new file mode 100644 index 0000000..2a25c9e --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/Aes.java @@ -0,0 +1,113 @@ +package com.hx.util; + +import org.apache.commons.codec.binary.Base64; + +import javax.crypto.Cipher; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; +import java.io.UnsupportedEncodingException; + +/** + * AES鍔犲瘑宸ュ叿绫� + */ +public class Aes { + + /** + * 灏嗕簩杩涘埗杞崲鎴�16杩涘埗 + * + * @param buf 瀛楄妭鏁扮粍 + * @return + */ + public static String parseByte2HexStr(byte buf[]) { + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < buf.length; i++) { + String hex = Integer.toHexString(buf[i] & 0xFF); + if (hex.length() == 1) { + hex = '0' + hex; + } + sb.append(hex.toUpperCase()); + } + return sb.toString(); + } + + /** + * 灏�16杩涘埗杞崲涓轰簩杩涘埗 + * + * @param hexStr 16杩涘埗瀛楃 + * @return + */ + public static byte[] parseHexStr2Byte(String hexStr) { + if (hexStr.length() < 1) + return null; + byte[] result = new byte[hexStr.length() / 2]; + for (int i = 0; i < hexStr.length() / 2; i++) { + int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16); + int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16); + result[i] = (byte) (high * 16 + low); + } + return result; + } + + /** + * 鍔犲瘑 + * @param str 寰呭姞瀵嗗瓧绗︿覆 + * @param secret 瀵嗛挜 + * @return + */ + public static byte[] encrypt(String str, String secret) { + if (null != str) { + byte[] bytes = null; + + try { + Base64 base64 = new Base64(); + String ALGORITHM = "AES"; + SecretKey desKey = new SecretKeySpec(secret.getBytes("UTF-8"), ALGORITHM);// 鐢熸垚瀵嗛挜 + Cipher c; + c = Cipher.getInstance(ALGORITHM); + c.init(Cipher.ENCRYPT_MODE, desKey); + bytes = c.doFinal(str.getBytes("UTF-8")); + return bytes; + } catch (Exception e) { + e.printStackTrace(); + } + + } + return null; + } + + /** + * 瑙e瘑 + * @param str 寰呰В瀵嗗瓧绗︿覆 + * @param secret 瀵嗛挜 + * @return + */ + public static byte[] decrypt(byte[] str, String secret) { + try { + String ALGORITHM = "AES"; + SecretKey desKey = new SecretKeySpec(secret.getBytes("UTF-8"), ALGORITHM);// 鐢熸垚瀵嗛挜 + Cipher c = Cipher.getInstance(ALGORITHM); + c.init(Cipher.DECRYPT_MODE, desKey); + return c.doFinal(str); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static void main(String[] args) throws UnsupportedEncodingException { + + String content = "apiKey=phitabfaceapi&userId=o5W1it6Pvqn6vPX6E1BGERH8J1lw"; + String password = "phitabfacesecret"; + + byte[] encode = encrypt(content, password); + String code = parseByte2HexStr(encode); + System.out.println("瀵嗘枃瀛楃涓诧細" + code); + + //16杩涘埗瀛楃涓茶浆鎴愬瓧鑺傛暟缁� + byte[] decode = parseHexStr2Byte(code); + // 瑙e瘑 + byte[] decryptResult = decrypt(decode, password); + System.out.println("瑙e瘑鍚庯細" + new String(decryptResult, "UTF-8")); //涓嶈浆鐮佷細涔辩爜 + + } +} diff --git a/hx_common/src/main/java/com/hx/util/AesUtil.java b/hx_common/src/main/java/com/hx/util/AesUtil.java new file mode 100644 index 0000000..ceda343 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/AesUtil.java @@ -0,0 +1,125 @@ +package com.hx.util; + +import javax.crypto.Cipher; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; + +import org.apache.commons.codec.binary.Base64; + +/** + * AES鍔犺В瀵嗗伐鍏� + * 浣跨敤璇ョ被锛岄渶瑕佽鏇挎崲local_policy.jar鍙妘s_export_policy.jar + * @author ChenJiaHe + * + */ +public class AesUtil { + + /**16浣嶅姞瀵嗙閽�*/ + public static final String SECRET = "huoXiong16816888"; + + /** + * AES鍔犲瘑 + * + * @param str + * 闇�瑕佸姞瀵嗙殑鏄庢枃 + * @param secret + * 绉橀挜 + * @return 鍔犲瘑鍚庣殑瀵嗘枃(base64缂栫爜瀛楃涓�) + */ + public static String aesEncryp(String str, String secret) { + if (null != str) { + byte[] bytes = null; + + try { + Base64 base64 = new Base64(); + String ALGORITHM = "AES"; + SecretKey deskey = new SecretKeySpec(secret.getBytes("UTF-8"), ALGORITHM);// 鐢熸垚瀵嗛挜 + Cipher c; + c = Cipher.getInstance(ALGORITHM); + c.init(Cipher.ENCRYPT_MODE, deskey); + bytes = c.doFinal(str.getBytes("UTF-8")); + if (bytes != null) { + return new String(base64.encode(bytes)); + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + return null; + } + + /** + * AES瑙e瘑 + * + * @param str + * 闇�瑕佽В瀵嗙殑绉樻枃 + * @param secret + * 绉橀挜 + * @return 瑙e瘑鍚庣殑鏄庢枃 + */ + public static String aesDecryp(String str, String secret) { + try { + Base64 base64 = new Base64(); + String ALGORITHM = "AES"; + SecretKey deskey = new SecretKeySpec(secret.getBytes("UTF-8"), ALGORITHM);// 鐢熸垚瀵嗛挜 + Cipher c = Cipher.getInstance(ALGORITHM); + c.init(Cipher.DECRYPT_MODE, deskey); + return new String(c.doFinal(base64.decode(str.getBytes("UTF-8"))), "UTF-8"); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** + * AES鍔犲瘑锛堝浐瀹氱閽ワ級 + * + * @param str 闇�瑕佸姞瀵嗙殑鏄庢枃 + * @return 鍔犲瘑鍚庣殑瀵嗘枃(base64缂栫爜瀛楃涓�) + */ + public static String aesEncryp(String str) { + String secret = SECRET; + if (null != str) { + byte[] bytes = null; + + try { + Base64 base64 = new Base64(); + String ALGORITHM = "AES"; + SecretKey deskey = new SecretKeySpec(secret.getBytes("UTF-8"), ALGORITHM);// 鐢熸垚瀵嗛挜 + Cipher c; + c = Cipher.getInstance(ALGORITHM); + c.init(Cipher.ENCRYPT_MODE, deskey); + bytes = c.doFinal(str.getBytes("UTF-8")); + if (bytes != null) { + return new String(base64.encode(bytes)); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + return null; + } + + /** + * AES瑙e瘑锛堝浐瀹氱閽ワ級 + * + * @param str 闇�瑕佽В瀵嗙殑绉樻枃 + * @return 瑙e瘑鍚庣殑鏄庢枃 + */ + public static String aesDecryp(String str) { + String secret = SECRET; + try { + Base64 base64 = new Base64(); + String ALGORITHM = "AES"; + SecretKey deskey = new SecretKeySpec(secret.getBytes("UTF-8"), ALGORITHM);// 鐢熸垚瀵嗛挜 + Cipher c = Cipher.getInstance(ALGORITHM); + c.init(Cipher.DECRYPT_MODE, deskey); + return new String(c.doFinal(base64.decode(str.getBytes("UTF-8"))), "UTF-8"); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + +} diff --git a/hx_common/src/main/java/com/hx/util/BarCodeUtil.java b/hx_common/src/main/java/com/hx/util/BarCodeUtil.java new file mode 100644 index 0000000..a73e54d --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/BarCodeUtil.java @@ -0,0 +1,57 @@ +package com.hx.util; + +import com.google.zxing.BarcodeFormat; +import com.google.zxing.MultiFormatWriter; +import com.google.zxing.client.j2se.MatrixToImageWriter; +import com.google.zxing.common.BitMatrix; +import sun.misc.BASE64Encoder; + +import javax.imageio.ImageIO; +import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; + +public class BarCodeUtil { + + /** + * 缁欏墠绔骇鐢熶竴涓潯褰㈢爜 + * + * @param number 缂栫爜 + * @param width 瀹藉害 + * @param height 楂樺害 + */ + public static String getCode(String number, Integer width, Integer height) { + // 鐢熸垚鏉″舰鐮� + BufferedImage image = getBarCode(number, width, height); + // 浣跨敤娴佺殑鏂瑰紡 + ByteArrayOutputStream out = new ByteArrayOutputStream(); + try { + ImageIO.write(image, "png", out); + } catch (Exception e) { + // log.error("generate code error! error message:{}", "鍑虹幇闂锛�"); + e.printStackTrace(); + } + // 灏嗘祦杞垚鏁扮粍 + byte[] bytes = out.toByteArray(); + BASE64Encoder encoder = new BASE64Encoder(); + // 鎶婄敓鎴愮殑缂栫爜杩斿洖鍘� + return "data:image/png;base64," + encoder.encodeBuffer(bytes).trim(); + } + + /** + * 浜х敓鏉″舰鐮佺殑鏂规硶 + * + * @param number 缂栫爜 + * @param width 瀹藉害 + * @param height 楂樺害 + */ + public static BufferedImage getBarCode(String number, Integer width, Integer height) { + try { + BitMatrix bitMatrix = new MultiFormatWriter().encode(number, BarcodeFormat.CODE_128, width, height); + return MatrixToImageWriter.toBufferedImage(bitMatrix); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + +} diff --git a/hx_common/src/main/java/com/hx/util/Base64Util.java b/hx_common/src/main/java/com/hx/util/Base64Util.java new file mode 100644 index 0000000..f7e312e --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/Base64Util.java @@ -0,0 +1,65 @@ +package com.hx.util; + +/** + * Base64 宸ュ叿绫� + */ +public class Base64Util { + private static final char last2byte = (char) Integer.parseInt("00000011", 2); + private static final char last4byte = (char) Integer.parseInt("00001111", 2); + private static final char last6byte = (char) Integer.parseInt("00111111", 2); + private static final char lead6byte = (char) Integer.parseInt("11111100", 2); + private static final char lead4byte = (char) Integer.parseInt("11110000", 2); + private static final char lead2byte = (char) Integer.parseInt("11000000", 2); + private static final char[] encodeTable = new char[]{'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', '+', '/'}; + + public Base64Util() { + } + + public static String encode(byte[] from) { + StringBuilder to = new StringBuilder((int) ((double) from.length * 1.34D) + 3); + int num = 0; + char currentByte = 0; + + int i; + for (i = 0; i < from.length; ++i) { + for (num %= 8; num < 8; num += 6) { + switch (num) { + case 0: + currentByte = (char) (from[i] & lead6byte); + currentByte = (char) (currentByte >>> 2); + case 1: + case 3: + case 5: + default: + break; + case 2: + currentByte = (char) (from[i] & last6byte); + break; + case 4: + currentByte = (char) (from[i] & last4byte); + currentByte = (char) (currentByte << 2); + if (i + 1 < from.length) { + currentByte = (char) (currentByte | (from[i + 1] & lead2byte) >>> 6); + } + break; + case 6: + currentByte = (char) (from[i] & last2byte); + currentByte = (char) (currentByte << 4); + if (i + 1 < from.length) { + currentByte = (char) (currentByte | (from[i + 1] & lead4byte) >>> 4); + } + } + + to.append(encodeTable[currentByte]); + } + } + + if (to.length() % 4 != 0) { + for (i = 4 - to.length() % 4; i > 0; --i) { + to.append("="); + } + } + + return to.toString(); + } +} diff --git a/hx_common/src/main/java/com/hx/util/BigDecimalUtil.java b/hx_common/src/main/java/com/hx/util/BigDecimalUtil.java new file mode 100644 index 0000000..27349e6 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/BigDecimalUtil.java @@ -0,0 +1,28 @@ +package com.hx.util; + +import java.math.BigDecimal; + +public class BigDecimalUtil { + + /**淇濈暀涓や綅灏忔暟 + * + * @param bigDecimal 灏忔暟鍊� + * @return + */ + public static BigDecimal retainDecimal(BigDecimal bigDecimal){ + bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP); + return bigDecimal; + } + + /**淇濈暀灏忓井灏忔暟 + * + * @param bigDecimal 灏忔暟鍊� + * @param decimalNum 淇濈暀灏忔暟浣嶆暟 + * @return + */ + public static BigDecimal retainDecimal(BigDecimal bigDecimal,int decimalNum){ + bigDecimal.setScale(decimalNum, BigDecimal.ROUND_HALF_UP); + return bigDecimal; + } + +} diff --git a/hx_common/src/main/java/com/hx/util/BlurDataUtil.java b/hx_common/src/main/java/com/hx/util/BlurDataUtil.java new file mode 100644 index 0000000..bef9fd0 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/BlurDataUtil.java @@ -0,0 +1,119 @@ +package com.hx.util; + +import org.apache.commons.lang.StringUtils; + +/** + * 鏁版嵁鑴辨晱宸ュ叿绫� + * + */ +public class BlurDataUtil { + + /** + * 鎵嬫満鍙疯劚鏁忓鐞� + * 鑴辨晱瑙勫垯: 淇濈暀鍓嶄笁鍚庡洓, 姣斿 18738291234 缃崲涓� 187****1234 + * @param phone + * @return + */ + public static final String blurPhone(String phone) { + if (StringUtils.isEmpty(phone) || (phone.length() != 11)) { + return phone; + } + return phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"); + } + + /** + * 韬唤璇佸彿鑴辨晱澶勭悊 + * 鍘熻韩浠借瘉鍙凤細500222202110275699锛岃劚鏁忓悗锛�132****99308084911 + * @param idCard + * @return + */ + public static String blurIdCard(String idCard) { + if (StringUtils.isEmpty(idCard)) { + return ""; + } + /* + * 鍙傛暟1锛氳瘉浠跺彿锛屽弬鏁�2锛圤VERLAY锛夛細鏇挎崲鍚庣殑瀛楃涓诧紝 + * 鍙傛暟3锛圫TART锛夛細鏇挎崲鐨勮捣濮嬩笅鏍囷紝鍙傛暟4锛圗ND锛夛細鏇挎崲鐨勭粨鏉熶笅鏍囷紙涓嶅寘鍚級 + */ + return StringUtils.overlay(idCard, "****", 3, 7); + } + + /** + * 韬唤璇佸彿鑴辨晱澶勭悊 + * 灞曠ず 鍓�6浣嶅拰鍚�6浣� + * @param idCard + * @return + */ + public static String hiddenIdCard(String idCard) {//韬唤璇� + if (StringUtils.isBlank(idCard)) { + return ""; + } + return StringUtils.left(idCard, 6).concat(StringUtils.removeStart(StringUtils.leftPad(StringUtils.right(idCard, 4), StringUtils.length(idCard), "*"), "***")); + } + + /** + * 閭鑴辨晱澶勭悊 + * 鍘熼偖绠憋細zhangsan@qq.com锛岃劚鏁忓悗锛歾hang***@qq.com + * @param email + * @return + */ + public static String blurEmail(String email) { + if (StringUtils.isEmpty(email)) { + return email; + } + String encrypt = email.replaceAll("(\\w+)\\w{3}@(\\w+)", "$1***@$2"); + if(StringUtils.equalsIgnoreCase(email, encrypt)){ + encrypt = email.replaceAll("(\\w*)\\w{1}@(\\w+)", "$1*@$2"); + } + return encrypt; + } + + /** + * 鎶ょ収鑴辨晱澶勭悊 + * 鑴辨晱瑙勫垯锛氭姢鐓у墠2鍚�3浣嶈劚鏁忥紝鎶ょ収涓�鑸负8鎴�9浣� + * @param passport + * @return + */ + public static String blurPassport(String passport) { + if (StringUtils.isEmpty(passport) || (passport.length() < 8)) { + return passport; + } + return passport.substring(0, 2) + new String(new char[passport.length() - 5]).replace("\0", "*") + passport.substring(passport.length() - 3); + } + + /** + * 瀛楁淇℃伅鑴辨晱 + * 鑴辨晱瑙勫垯:濡傛灉瀛楃闀垮害澶т簬3浣嶏紝鍒欓殣钘忔渶鍚庝笁浣嶏紝鍚﹀垯闅愯棌鏈�鍚�1浣� + * @param field + * @return + */ + public static String blurField(String field) { + if (StringUtils.isEmpty(field)) { + return field; + } + String encrypt = field.replaceAll("(\\w+)\\w{3}", "$1***"); + if(StringUtils.equalsIgnoreCase(field, encrypt)){ + encrypt = field.replaceAll("(\\w*)\\w{1}", "$1*"); + } + return encrypt; + } + + public static void main(String[] args) { + System.out.println(blurPhone("18738291234")); // 187****1234 + System.out.println(blurIdCard("500222202110275699")); // 500****99410275467 + System.out.println(blurEmail("zhangsan@qq.com")); // zhang***@qq.com + System.out.println(blurPassport("12345678")); // 12***678 + System.out.println(blurField("I feel so good")); // I f*** so g*** + } + + /* + * 澶囨敞锛� + * 1銆丼tring.replaceAll(绗�1涓弬鏁版槸鑴辨晱绛涢�夌殑姝e垯锛岀2涓弬鏁版槸鑴辨晱鏇挎崲鐨勬鍒�) + * 2銆侀渶瑕佸紩鍏ommons-lang3锛岃繖涓熀鏈瘡涓」鐩兘鐢ㄥ埌 + * <dependency> + * <groupId>org.apache.commons</groupId> + * <artifactId>commons-lang3</artifactId> + * <version>3.7</version> + * </dependency> + */ +} \ No newline at end of file diff --git a/hx_common/src/main/java/com/hx/util/COSUtil.java b/hx_common/src/main/java/com/hx/util/COSUtil.java new file mode 100644 index 0000000..92efaba --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/COSUtil.java @@ -0,0 +1,237 @@ +package com.hx.util; + +import com.hx.exception.TipsException; +import com.qcloud.cos.COSClient; +import com.qcloud.cos.ClientConfig; +import com.qcloud.cos.auth.BasicCOSCredentials; +import com.qcloud.cos.auth.COSCredentials; +import com.qcloud.cos.exception.CosClientException; +import com.qcloud.cos.exception.CosServiceException; +import com.qcloud.cos.http.HttpProtocol; +import com.qcloud.cos.model.GetObjectRequest; +import com.qcloud.cos.model.ObjectMetadata; +import com.qcloud.cos.model.PutObjectRequest; +import com.qcloud.cos.model.PutObjectResult; +import com.qcloud.cos.region.Region; +import com.qcloud.cos.transfer.Download; +import com.qcloud.cos.transfer.TransferManager; +import org.springframework.web.multipart.MultipartFile; + +import java.io.File; +import java.io.IOException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/**鑵捐浜� COS + * @author ChenJiaHe + * @date 2020-12-03 + */ +public class COSUtil { + + /** 鍚庣璋冪敤涓婁紶鍥剧墖 + * @param key 涓婁紶璺緞锛堝寘鎷浘鐗囧悕绉板拰鍜屽悗缂�锛夛紝鎸囧畾瑕佷笂浼犲埌 COS 涓婂璞¢敭 + * @param localFile + * @param secretId 鐢ㄦ埛id + * @param secretKey 鐢ㄦ埛绉橀挜 + * @param regionName 瀛樺湪鍩燂紝鍙傝�冭吘璁簯 + * @param bucketName 鎸囧畾瑕佷笂浼犲埌鐨勫瓨鍌ㄦ《 + * @return + * @throws IOException + */ + public static String uploadImg(String key,MultipartFile localFile,String secretId, String secretKey,String regionName,String bucketName) throws IOException { + + // 1 鍒濆鍖栫敤鎴疯韩浠戒俊鎭紙secretId, secretKey锛夈�� + COSCredentials cred = new BasicCOSCredentials(secretId, secretKey); + // 2 璁剧疆 bucket 鐨勫尯鍩�, COS 鍦板煙鐨勭畝绉拌鍙傜収 https://cloud.tencent.com/document/product/436/6224 + // clientConfig 涓寘鍚簡璁剧疆 region, https(榛樿 http), 瓒呮椂, 浠g悊绛� set 鏂规硶, 浣跨敤鍙弬瑙佹簮鐮佹垨鑰呭父瑙侀棶棰� Java SDK 閮ㄥ垎銆� + Region region = new Region(regionName); + ClientConfig clientConfig = new ClientConfig(region); + // 3 鐢熸垚 cos 瀹㈡埛绔�� + COSClient cosClient = new COSClient(cred, clientConfig); + + //寮�濮嬩笂浼� + ObjectMetadata objectMetadata = new ObjectMetadata(); + // 璁剧疆杈撳叆娴侀暱搴︿负500 + objectMetadata.setContentLength(localFile.getSize()); + // 璁剧疆 Content type, 榛樿鏄� application/octet-stream,瀵逛簬鏈湴鏂囦欢涓婁紶锛岄粯璁ゆ牴鎹湰鍦版枃浠剁殑鍚庣紑杩涜鏄犲皠 + // 锛屼緥濡� jpg 鏂囦欢鏄犲皠 涓篿mage/jpeg瀵逛簬娴佸紡涓婁紶 榛樿鏄� application/octet-stream + //objectMetadata.setContentType("application/pdf"); + PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key,localFile.getInputStream(),objectMetadata); + PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest); + + //鎷兼帴璺緞 + StringBuilder imgUrl = new StringBuilder(); + imgUrl.append("https://"+bucketName+".cos."+regionName+".myqcloud.com"); + if(key.startsWith("/")){ + imgUrl.append(key); + }else{ + imgUrl.append("/"+key); + } + cosClient.shutdown(); + return imgUrl.toString(); + + } + + + /** 鍚庣璋冪敤涓婁紶鍥剧墖 + * @param key 涓婁紶璺緞锛堝寘鎷浘鐗囧悕绉板拰鍜屽悗缂�锛夛紝鎸囧畾瑕佷笂浼犲埌 COS 涓婂璞¢敭 + * @param localFile + * @param secretId 鐢ㄦ埛id + * @param secretKey 鐢ㄦ埛绉橀挜 + * @param regionName 瀛樺湪鍩燂紝鍙傝�冭吘璁簯 + * @param bucketName 鎸囧畾瑕佷笂浼犲埌鐨勫瓨鍌ㄦ《 + * @return + * @throws IOException + */ + public static String uploadImg(String key,File localFile,String secretId, String secretKey,String regionName,String bucketName) throws IOException { + + // 1 鍒濆鍖栫敤鎴疯韩浠戒俊鎭紙secretId, secretKey锛夈�� + COSCredentials cred = new BasicCOSCredentials(secretId, secretKey); + // 2 璁剧疆 bucket 鐨勫尯鍩�, COS 鍦板煙鐨勭畝绉拌鍙傜収 https://cloud.tencent.com/document/product/436/6224 + // clientConfig 涓寘鍚簡璁剧疆 region, https(榛樿 http), 瓒呮椂, 浠g悊绛� set 鏂规硶, 浣跨敤鍙弬瑙佹簮鐮佹垨鑰呭父瑙侀棶棰� Java SDK 閮ㄥ垎銆� + Region region = new Region(regionName); + ClientConfig clientConfig = new ClientConfig(region); + // 3 鐢熸垚 cos 瀹㈡埛绔�� + COSClient cosClient = new COSClient(cred, clientConfig); + + // 璁剧疆 Content type, 榛樿鏄� application/octet-stream,瀵逛簬鏈湴鏂囦欢涓婁紶锛岄粯璁ゆ牴鎹湰鍦版枃浠剁殑鍚庣紑杩涜鏄犲皠 + // 锛屼緥濡� jpg 鏂囦欢鏄犲皠 涓篿mage/jpeg瀵逛簬娴佸紡涓婁紶 榛樿鏄� application/octet-stream + //objectMetadata.setContentType("application/pdf"); + PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile); + PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest); + + //鎷兼帴璺緞 + StringBuilder imgUrl = new StringBuilder(); + imgUrl.append("https://"+bucketName+".cos."+regionName+".myqcloud.com"); + if(key.startsWith("/")){ + imgUrl.append(key); + }else{ + imgUrl.append("/"+key); + } + cosClient.shutdown(); + return imgUrl.toString(); + + } + + /**涓嬭浇鏂囦欢 + * @param key 涓婁紶璺緞锛堝寘鎷浘鐗囧悕绉板拰鍜屽悗缂�锛夛紝鎸囧畾瑕佷笂浼犲埌 COS 涓婂璞¢敭 + * @param secretId 鐢ㄦ埛id + * @param secretKey 鐢ㄦ埛绉橀挜 + * @param regionName 瀛樺湪鍩燂紝鍙傝�冭吘璁簯 + * @param bucketName 鎸囧畾瑕佷笂浼犲埌鐨勫瓨鍌ㄦ《 + */ + public static File download(String key,String secretId, String secretKey,String regionName,String bucketName){ + + // 浣跨敤楂樼骇鎺ュ彛蹇呴』鍏堜繚璇佹湰杩涚▼瀛樺湪涓�涓� TransferManager 瀹炰緥锛屽鏋滄病鏈夊垯鍒涘缓 + // 璇︾粏浠g爜鍙傝鏈〉锛氶珮绾ф帴鍙� -> 鍒涘缓 TransferManager + TransferManager transferManager = createTransferManager( secretId, secretKey,regionName); + // 鏈湴鏂囦欢璺緞 + File downloadFile = null; + try { + GetObjectRequest getObjectRequest; + //鎴彇鏂囦欢鍚嶇О + String[] datas = key.split(regionName+".myqcloud.com/"); + if(datas.length ==1){ + getObjectRequest = new GetObjectRequest(bucketName, datas[0]); + }else if(datas.length ==2){ + getObjectRequest = new GetObjectRequest(bucketName, datas[1]); + }else{ + throw new TipsException("鏂囦欢璺緞閿欒銆恔ey銆�"); + } + + ////鐢熸垚涓存椂鏂囦欢 + //鑾峰彇鍚庣紑鍚嶇О + String suffix = key.substring(key.lastIndexOf(".")); + downloadFile = File.createTempFile("temp", suffix); + + // 杩斿洖涓�涓紓姝ョ粨鏋� Donload, 鍙悓姝ョ殑璋冪敤 waitForCompletion 绛夊緟涓嬭浇缁撴潫, 鎴愬姛杩斿洖 void, 澶辫触鎶涘嚭寮傚父 + Download download = transferManager.download(getObjectRequest, downloadFile); + download.waitForCompletion(); + } catch (CosServiceException e) { + e.printStackTrace(); + } catch (CosClientException e) { + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + }catch (IOException e){ + e.printStackTrace(); + }finally { + // 纭畾鏈繘绋嬩笉鍐嶄娇鐢� transferManager 瀹炰緥涔嬪悗锛屽叧闂箣 + // 璇︾粏浠g爜鍙傝鏈〉锛氶珮绾ф帴鍙� -> 鍏抽棴 TransferManager + shutdownTransferManager(transferManager); + } + + return downloadFile; + } + + /** + * 鍒涘缓 TransferManager 瀹炰緥锛岃繖涓疄渚嬬敤鏉ュ悗缁皟鐢ㄩ珮绾ф帴鍙� + * @param secretId + * @param secretKey + * @return + */ + public static TransferManager createTransferManager(String secretId, String secretKey,String regionName) { + // 鍒涘缓涓�涓� COSClient 瀹炰緥锛岃繖鏄闂� COS 鏈嶅姟鐨勫熀纭�瀹炰緥銆� + // 璇︾粏浠g爜鍙傝鏈〉: 绠�鍗曟搷浣� -> 鍒涘缓 COSClient + COSClient cosClient = createCOSClient( secretId, secretKey,regionName); + + // 鑷畾涔夌嚎绋嬫睜澶у皬锛屽缓璁湪瀹㈡埛绔笌 COS 缃戠粶鍏呰冻锛堜緥濡備娇鐢ㄨ吘璁簯鐨� CVM锛屽悓鍦板煙涓婁紶 COS锛夌殑鎯呭喌涓嬶紝璁剧疆鎴�16鎴�32鍗冲彲锛屽彲杈冨厖鍒嗙殑鍒╃敤缃戠粶璧勬簮 + // 瀵逛簬浣跨敤鍏綉浼犺緭涓旂綉缁滃甫瀹借川閲忎笉楂樼殑鎯呭喌锛屽缓璁噺灏忚鍊硷紝閬垮厤鍥犵綉閫熻繃鎱紝閫犳垚璇锋眰瓒呮椂銆� + ExecutorService threadPool = Executors.newFixedThreadPool(32); + + // 浼犲叆涓�涓� threadpool, 鑻ヤ笉浼犲叆绾跨▼姹狅紝榛樿 TransferManager 涓細鐢熸垚涓�涓崟绾跨▼鐨勭嚎绋嬫睜銆� + TransferManager transferManager = new TransferManager(cosClient, threadPool); + + return transferManager; + } + + /** + * 鍏抽棴绠$悊 + * @param transferManager + */ + public static void shutdownTransferManager(TransferManager transferManager) { + // 鎸囧畾鍙傛暟涓� true, 鍒欏悓鏃朵細鍏抽棴 transferManager 鍐呴儴鐨� COSClient 瀹炰緥銆� + // 鎸囧畾鍙傛暟涓� false, 鍒欎笉浼氬叧闂� transferManager 鍐呴儴鐨� COSClient 瀹炰緥銆� + transferManager.shutdownNow(true); + } + + /** + * 鍒涘缓 COSClient 瀹炰緥锛岃繖涓疄渚嬬敤鏉ュ悗缁皟鐢ㄨ姹� + * @param secretId + * @param secretKey + * @return + */ + public static COSClient createCOSClient(String secretId, String secretKey,String regionName) { + // 璁剧疆鐢ㄦ埛韬唤淇℃伅銆� + // SECRETID 鍜� SECRETKEY 璇风櫥褰曡闂鐞嗘帶鍒跺彴 https://console.cloud.tencent.com/cam/capi 杩涜鏌ョ湅鍜岀鐞� + COSCredentials cred = new BasicCOSCredentials(secretId, secretKey); + + // ClientConfig 涓寘鍚簡鍚庣画璇锋眰 COS 鐨勫鎴风璁剧疆锛� + ClientConfig clientConfig = new ClientConfig(); + + // 璁剧疆 bucket 鐨勫湴鍩� + // COS_REGION 璇峰弬鐓� https://cloud.tencent.com/document/product/436/6224 + clientConfig.setRegion(new Region(regionName)); + + // 璁剧疆璇锋眰鍗忚, http 鎴栬�� https + // 5.6.53 鍙婃洿浣庣殑鐗堟湰锛屽缓璁缃娇鐢� https 鍗忚 + // 5.6.54 鍙婃洿楂樼増鏈紝榛樿浣跨敤浜� https + clientConfig.setHttpProtocol(HttpProtocol.https); + + // 浠ヤ笅鐨勮缃紝鏄彲閫夌殑锛� + + // 璁剧疆 socket 璇诲彇瓒呮椂锛岄粯璁� 30s + clientConfig.setSocketTimeout(300*1000); + // 璁剧疆寤虹珛杩炴帴瓒呮椂锛岄粯璁� 30s + clientConfig.setConnectionTimeout(30*1000); + + // 濡傛灉闇�瑕佺殑璇濓紝璁剧疆 http 浠g悊锛宨p 浠ュ強 port + //clientConfig.setHttpProxyIp("httpProxyIp"); + //clientConfig.setHttpProxyPort(80); + + // 鐢熸垚 cos 瀹㈡埛绔�� + return new COSClient(cred, clientConfig); + } + + +} diff --git a/hx_common/src/main/java/com/hx/util/CVSUtil.java b/hx_common/src/main/java/com/hx/util/CVSUtil.java new file mode 100644 index 0000000..3a71f6c --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/CVSUtil.java @@ -0,0 +1,56 @@ +package com.hx.util; + +import java.io.FileOutputStream; +import java.io.OutputStreamWriter; +import java.util.List; + +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVPrinter; + +/** + * CVS宸ュ叿绫� + * + * @author mgchen + * + */ +public class CVSUtil { + + public void writeToCVS() throws Exception { + FileOutputStream fos = new FileOutputStream("E:/cjsworkspace/cjs-excel-demo/target/abc.csv"); + OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK"); + + CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader("濮撳悕", "骞撮緞", "瀹朵埂"); + // CSVFormat.DEFAULT.withHeader(header) + CSVPrinter csvPrinter = new CSVPrinter(osw, csvFormat); + + // csvPrinter = CSVFormat.DEFAULT.withHeader("濮撳悕", "骞撮緞", "瀹朵埂").print(osw); + + for (int i = 0; i < 10; i++) { + csvPrinter.printRecord("寮犱笁", 20, "婀栧寳"); + } + + csvPrinter.flush(); + csvPrinter.close(); + + } + + public static void writeToCVS(String path, String[] headers, List<List<Object>> data) throws Exception { + FileOutputStream fos = new FileOutputStream(path); + byte[] uft8bom = { (byte) 0xef, (byte) 0xbb, (byte) 0xbf }; + fos.write(uft8bom); + OutputStreamWriter osw = new OutputStreamWriter(fos, "utf-8"); + + CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(headers); + CSVPrinter csvPrinter = new CSVPrinter(osw, csvFormat); + + for (int i = 0; i < data.size(); i++) { + csvPrinter.printRecord(data.get(i)); + } + + csvPrinter.flush(); + csvPrinter.close(); + osw.close(); + fos.close(); + + } +} diff --git a/hx_common/src/main/java/com/hx/util/CheckCodeImageUtil.java b/hx_common/src/main/java/com/hx/util/CheckCodeImageUtil.java new file mode 100644 index 0000000..e934a4d --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/CheckCodeImageUtil.java @@ -0,0 +1,96 @@ +package com.hx.util; + +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Base64; + +import javax.imageio.ImageIO; + +/** + * 楠岃瘉鐮佺敓鎴愬櫒 + * @author ChenJiaHe + * @Date 2020-06-17 + */ +public class CheckCodeImageUtil { + + private final static int WIDTH = 60; + private final static int HEIGHT = 20; + + private static char[] generateCheckCode() { + // 锟斤拷锟斤拷锟斤拷证锟斤拷锟斤拷址锟斤拷 + String chars = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + char[] rands = new char[4]; + for (int i = 0; i < 4; i++) { + int rand = (int) (Math.random() * 35); + rands[i] = chars.charAt(rand); + } + return rands; + } + + private static void drawRands(Graphics g, char[] rands) { + g.setColor(Color.BLACK); + g.setFont(new Font(null, Font.ITALIC | Font.BOLD, 18)); + // 锟节诧拷同锟侥高讹拷锟斤拷锟斤拷锟斤拷锟街わ拷锟斤拷每锟斤拷锟街凤拷 + g.drawString("" + rands[0], 1, 17); + g.drawString("" + rands[1], 16, 15); + g.drawString("" + rands[2], 31, 18); + g.drawString("" + rands[3], 46, 16); + } + + private static void drawBackground(Graphics g) { + // 锟斤拷锟斤拷锟斤拷 + g.setColor(new Color(0xDCDCDC)); + g.fillRect(0, 0, WIDTH, HEIGHT); + // 锟斤拷锟斤拷锟斤拷120锟斤拷锟斤拷锟脚碉拷 + for (int i = 0; i < 120; i++) { + int x = (int) (Math.random() * WIDTH); + int y = (int) (Math.random() * HEIGHT); + int red = (int) (Math.random() * 255); + int green = (int) (Math.random() * 255); + int blue = (int) (Math.random() * 255); + g.setColor(new Color(red, green, blue)); + g.drawOval(x, y, 1, 0); + } + } + + public static String[] createImage(String id) + { + ByteArrayOutputStream bos = null; + String reStr = ""; + char[] rands = null; + try { + BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); + Graphics g = image.getGraphics(); + + rands = generateCheckCode(); + + drawBackground(g); + drawRands(g, rands); + + g.dispose(); + + bos = new ByteArrayOutputStream(); + ImageIO.write(image, "JPEG", bos); + byte[] buf = bos.toByteArray(); + reStr = Base64.getEncoder().encodeToString(buf); + + }catch (Exception e) { + e.printStackTrace(); + }finally { + if(bos != null) + { + try { + bos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + bos = null; + } + } + return new String[] {new String(rands),reStr}; + } +} diff --git a/hx_common/src/main/java/com/hx/util/CreateNoTool.java b/hx_common/src/main/java/com/hx/util/CreateNoTool.java new file mode 100644 index 0000000..93ac0c6 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/CreateNoTool.java @@ -0,0 +1,46 @@ +package com.hx.util; + +import java.util.Random; + +public class CreateNoTool { + + /**鑾峰彇闅忔満绉橀挜(鏁板瓧涓庡ぇ鍐欏瓧姣嶇粍鍚�) + * + * @param y + * 闅忔満鏁颁綅鏁� + * @return + */ + public static String randomKey(Integer y) { + String[] data = new String[] { + "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","S","Y","Z" + }; + String no = ""; + Random r = new Random(); + for (int i = 0; i < y; i++) { + no += data[r.nextInt(data.length-1)]; + } + return no; + } + + /**鑾峰彇闅忔満绉橀挜(鏁板瓧) + * + * @param y + * 闅忔満鏁颁綅鏁� + * @return + */ + public static String randomKeyNumber(Integer y) { + String[] data = new String[] { + "0","1","2","3","4","5","6","7","8","9" + }; + String no = ""; + Random r = new Random(); + for (int i = 0; i < y; i++) { + no += data[r.nextInt(data.length-1)]; + } + return no; + } + +} diff --git a/hx_common/src/main/java/com/hx/util/DateUtil.java b/hx_common/src/main/java/com/hx/util/DateUtil.java new file mode 100644 index 0000000..1ae3c6b --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/DateUtil.java @@ -0,0 +1,918 @@ +package com.hx.util; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; + +public class DateUtil { + + private static SimpleDateFormat Format_1 = new SimpleDateFormat("yyyyMMdd"); + private static SimpleDateFormat Format_2 = new SimpleDateFormat("yyyyMMddHHmmss"); + private static SimpleDateFormat Format_3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + private static SimpleDateFormat Format_4 = new SimpleDateFormat("yyyy-MM-dd"); + private static SimpleDateFormat Format_5 = new SimpleDateFormat("HH:mm:ss"); + private static SimpleDateFormat Format_6 = new SimpleDateFormat("yyyyMM"); + private static SimpleDateFormat Format_7 = new SimpleDateFormat("MM鏈坉d鏃� HH:mm"); + private static SimpleDateFormat Format_8 = new SimpleDateFormat("yyyy骞碝M鏈�"); + private static SimpleDateFormat Format_9 = new SimpleDateFormat("MM-dd"); + private static SimpleDateFormat Format_10 = new SimpleDateFormat("yyyy骞碝M鏈坉d鏃�"); + private static SimpleDateFormat Format_11 = new SimpleDateFormat("yyyy骞碝M鏈坉d鏃� HH:mm:ss"); + private static SimpleDateFormat Format_12 = new SimpleDateFormat("yyyyMMddHHmm"); + private static SimpleDateFormat Format_13 = new SimpleDateFormat("yyyy/MM/dd"); + private static SimpleDateFormat Format_14 = new SimpleDateFormat("yyyy-MM"); + private static SimpleDateFormat Format_15 = new SimpleDateFormat("yyyyMMddHHmmssSSS"); + private static SimpleDateFormat Format_16 = new SimpleDateFormat("yyyy/MM/dd HH:mm"); + private static SimpleDateFormat Format_17 = new SimpleDateFormat("HH:mm"); + + /**鏃堕棿鏍煎紡杞寲iso8601 + * @param date 鏃堕棿 + * @return 杩斿洖鐨勬椂闂存牸寮忓瓧绗︿覆 + */ + public static String dateFormatISO8601(Date date) { + if(!SimpleTool.checkNotNull(date)){ + return ""; + } + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");//璁剧疆鏃ユ湡鏍煎紡 + return df.format(date); + } + + /**鏃堕棿鏍煎紡杞寲 + * @param date 鏃堕棿 + * @param format 鏃堕棿鏍煎紡 + * @return 杩斿洖鐨勬椂闂存牸寮忓瓧绗︿覆 + */ + public static String dateFormat(Date date, String format) { + if(!SimpleTool.checkNotNull(date)){ + return ""; + } + SimpleDateFormat df = new SimpleDateFormat(format);//璁剧疆鏃ユ湡鏍煎紡 + return df.format(date); + } + + /**鏃堕棿鎴宠浆鏃堕棿 + * @param timestamp 鏃堕棿鎴� + * @param format 鏃堕棿鏍煎紡 + * @return 杩斿洖鐨勬椂闂存牸寮忓瓧绗︿覆 + */ + public static Date timestampToDate(long timestamp, String format) { + SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String sd = sdf.format(new Date(timestamp)); // 鏃堕棿鎴宠浆鎹㈡垚鏃堕棿 + return DateUtil.parseString(sd,"yyyy-MM-dd HH:mm:ss"); + } + + /** + * 杞崲鎴恲yyyMMdd鏍煎紡鐨勬棩鏈熷瓧绗︿覆 + * + * @param date + * @return + */ + public static String formatDate(Date date) { + return Format_1.format(date); + } + + /** + * 杞崲鎴恲yyyMMddHHmmss鏍煎紡鐨勬棩鏈熷瓧绗︿覆 + * + * @param date + * @return + */ + public static String formatDate_1(Date date) { + return Format_2.format(date); + } + + /** + * 杞崲鎴恲yyy-MM-dd HH:mm:ss鏍煎紡鐨勬棩鏈熷瓧绗︿覆 + * + * @param date + * @return + */ + public static String formatDate_2(Date date) { + return date == null ? null : Format_3.format(date); + } + + /** + * 杞崲鎴恲yyy-MM-dd鏍煎紡鐨勬棩鏈熷瓧绗︿覆 + * + * @param date + * @return + */ + public static String formatDate_3(Date date) { + return date != null ? Format_4.format(date) : null; + } + + /** + * 杞崲鎴怘H:mm:ss鏍煎紡鐨勬棩鏈熷瓧绗︿覆 + * + * @param date + * @return + */ + public static String formatDate_4(Date date) { + return Format_5.format(date); + } + + /** + * 杞崲鎴恲yyyMM鏍煎紡鐨勬棩鏈熷瓧绗︿覆 + * + * @param date + * @return + */ + public static String formatDate_5(Date date) { + return Format_6.format(date); + } + + /** + * 杞崲鎴恗m鏈坉d鏃� HH:mm鏍煎紡鐨勬棩鏈熷瓧绗︿覆 + * + * @param date + * @return + */ + public static String formatDate_6(Date date) { + return Format_7.format(date); + } + + /** + * 杞崲鎴恲yyy骞磎m鏈堟牸寮忕殑鏃ユ湡瀛楃涓� + * + * @param date + * @return + */ + public static String formatDate_7(Date date) { + return Format_8.format(date); + } + + /** + * 杞崲鎴恗m-dd鏍煎紡鐨勬棩鏈熷瓧绗︿覆 + * + * @param date + * @return + */ + public static String formatDate_8(Date date) { + return Format_9.format(date); + } + + /** + * 杞崲鎴恲yyy骞碝M鏈坉d鏃ユ牸寮忕殑鏃ユ湡瀛楃涓� + * + * @param date + * @return + */ + public static String formatDate_9(Date date) { + return Format_10.format(date); + } + + /** + * 杞崲鎴恲yyyMMddHHmm鏍煎紡鐨勬棩鏈熷瓧绗︿覆 + * + * @param date + * @return + */ + public static String formatDate_11(Date date) { + return Format_12.format(date); + } + + /** + * 杞崲鎴恲yyy骞碝M鏈坉d鏃� HH:mm:ss鏍煎紡鐨勬棩鏈熷瓧绗︿覆 + * + * @param date + * @return + */ + public static String formatDate_10(Date date) { + return Format_11.format(date); + } + + /** + * 杞崲鎴恲yyy/MM/dd 鏍煎紡鐨勬棩鏈熷瓧绗︿覆 + * + * @param date + * @return + */ + public static String formatDate_13(Date date) { + return Format_13.format(date); + } + + /** + * 杞崲鎴恲yyy-MM 鏍煎紡鐨勬棩鏈熷瓧绗︿覆 + * + * @param date + * @return + */ + public static String formatDate_14(Date date) { + return Format_14.format(date); + } + + + /** + * 褰撳墠鏃堕棿涔嬪墠鐨勬椂闂翠笌褰撳墠鏃堕棿鐩稿樊澶氬皯绉� + * @param startDate 褰撳墠鏃堕棿涔嬪墠鐨勬椂闂� + * @return + */ + public static int calLastedTime(Date startDate) { + long nowDate = new Date().getTime(); + long startDateTime = startDate.getTime(); + int diffSeconds = (int) ((nowDate - startDateTime) / 1000); + return diffSeconds; + } + + + /** + * 杞崲鎴恲yyyMMddHHmmssSSS鏍煎紡鐨勬棩鏈熷瓧绗︿覆 + * + * @param date + * @return + */ + public static String formatDate_15(Date date) { + return Format_15.format(date); + } + + /** + * 杞崲鎴恲yyy/MM/dd HH:mm鏍煎紡鐨勬棩鏈熷瓧绗︿覆 + * + * @param date + * @return + */ + public static String formatDate_16(Date date) { + return Format_16.format(date); + } + + /** + * 杞崲鎴怘H:mm鏍煎紡鐨勬棩鏈熷瓧绗︿覆 + * + * @param date + * @return + */ + public static String formatDate_17(Date date) { + return Format_17.format(date); + } + + /** + * 杞崲鎴愬瓧绗︿覆yyyyMMddHHmmss鎴愭棩锟�? + * + * @param str + * @return + * @throws Exception + */ + public static Date parseString(String str) { + try { + return Format_2.parse(str); + }catch (Exception e) + { + return null; + } + } + + /** + * 杞崲鎴愬瓧绗︿覆鍒版寚瀹氱殑鏃ユ湡 + * + * @param str + * @param format + * @return + * @throws Exception + */ + public static Date parseString(String str, String format) { + SimpleDateFormat sdf = new SimpleDateFormat(format); + try{ + return sdf.parse(str); + }catch (Exception e) + { + return null; + } + } + + /**瀛楃涓茶浆鎴愭椂闂磞yyy-MM-dd HH:mm:ss*/ + public static Date parseString_1(String str) + { + try{ + return Format_3.parse(str); + }catch (Exception e) + { + return null; + } + } + + /**瀛楃涓茶浆鎴愭椂闂磞yyy-MM-dd*/ + public static Date parseString_2(String str) + { + try{ + return Format_4.parse(str); + }catch (Exception e) + { + return null; + } + } + + /**鏃堕棿涓婄鍙犲姞 + * @Author: ChenJiaHe + * @param dateTime 鏃堕棿 + * @param second 绉� + * @return + */ + public static Date addSecond(Date dateTime,int second){ + Calendar c = Calendar.getInstance(); + c.setTime(dateTime); + c.add(Calendar.SECOND, second); + return c.getTime(); + } + + /**鏃堕棿涓婂垎閽熷彔鍔� + * @Author: ChenJiaHe + * @param dateTime 鏃堕棿 + * @param min 鍒嗛挓 + * @return + */ + public static Date addMin(Date dateTime,int min){ + Calendar c = Calendar.getInstance(); + c.setTime(dateTime); + c.add(Calendar.MINUTE, min); + return c.getTime(); + } + + /**鏃堕棿涓婂皬鏃跺彔鍔� + * @Author: ChenJiaHe + * @param dateTime 鏃堕棿 + * @param hour 灏忔椂 + * @return + */ + public static Date addhour(Date dateTime,int hour){ + Calendar c = Calendar.getInstance(); + c.setTime(dateTime); + c.add(Calendar.HOUR, hour); + return c.getTime(); + } + + /**鏃堕棿涓婂ぉ鏁板彔鍔� + * @Author: ChenJiaHe + * @param dateTime 鏃堕棿 + * @param dayNum 澶╂暟 + * @return + */ + public static Date addDay(Date dateTime,int dayNum){ + Calendar c = Calendar.getInstance(); + c.setTime(dateTime); + c.add(Calendar.DATE, dayNum); + return c.getTime(); + } + + /**鏃堕棿涓婃湀鏁板彔鍔� + * @Author: ChenJiaHe + * @param dateTime 鏃堕棿 + * @param dayNum 澶╂暟 + * @return + */ + public static Date addMonth(Date dateTime,int dayNum){ + Calendar c = Calendar.getInstance(); + c.setTime(dateTime); + c.add(Calendar.MONTH, dayNum); + return c.getTime(); + } + + /**鏃堕棿涓婂勾鏁板彔鍔� + * @Author: ChenJiaHe + * @param dateTime 鏃堕棿 + * @param dayNum 澶╂暟 + * @return + */ + public static Date addYear(Date dateTime,int dayNum){ + Calendar c = Calendar.getInstance(); + c.setTime(dateTime); + c.add(Calendar.YEAR, dayNum); + return c.getTime(); + } + + /** + * 杞崲鎴愬瓧绗︿覆鍒版寚瀹氱殑鏃ユ湡 + * + * @param date + * @param format + * @return + * @throws Exception + */ + public static String formatDate(Date date, String format) { + if (date == null) { + return null; + } + + SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.CHINA); + return sdf.format(date); + } + + /**鏃ユ湡杞槦鏈� + * @param dateTime 瀛楃涓叉椂闂� + * @param format 瀛楃涓叉椂闂存牸寮� + * @param returnType 杩斿洖绫诲瀷 0鏄熸湡鍑�1鍛ㄥ嚑 + * @return 鏁版嵁 + */ + public static String dateToWeek(String dateTime,String format,Integer returnType) throws ParseException { + SimpleDateFormat f = new SimpleDateFormat(format); + String[] weekDays = { "鏄熸湡鏃�", "鏄熸湡涓�", "鏄熸湡浜�", "鏄熸湡涓�", "鏄熸湡鍥�", "鏄熸湡浜�", "鏄熸湡鍏�" }; + if(SimpleTool.checkNotNull(returnType)&&returnType==1){ + weekDays = new String[]{"鍛ㄦ棩", "鍛ㄤ竴", "鍛ㄤ簩", "鍛ㄤ笁", "鍛ㄥ洓", "鍛ㄤ簲", "鍛ㄥ叚"}; + } + Calendar cal = Calendar.getInstance(); // 鑾峰緱涓�涓棩鍘� + Date datet = null; + datet = f.parse(dateTime); + cal.setTime(datet); + + int w = cal.get(Calendar.DAY_OF_WEEK) - 1; // 鎸囩ず涓�涓槦鏈熶腑鐨勬煇澶┿�� + if (w < 0) + w = 0; + return weekDays[w]; + } + + /**鏃ユ湡杞槦鏈� + * @param dateTime 鏃堕棿 + * @param returnType 杩斿洖绫诲瀷 0鏄熸湡鍑�1鍛ㄥ嚑 + * @return 鏁版嵁 + */ + public static String dateToWeek(Date dateTime,Integer returnType) { + String[] weekDays = { "鏄熸湡鏃�", "鏄熸湡涓�", "鏄熸湡浜�", "鏄熸湡涓�", "鏄熸湡鍥�", "鏄熸湡浜�", "鏄熸湡鍏�" }; + if(SimpleTool.checkNotNull(returnType)&&returnType==1){ + weekDays = new String[]{"鍛ㄦ棩", "鍛ㄤ竴", "鍛ㄤ簩", "鍛ㄤ笁", "鍛ㄥ洓", "鍛ㄤ簲", "鍛ㄥ叚"}; + } + Calendar cal = Calendar.getInstance(); // 鑾峰緱涓�涓棩鍘� + cal.setTime(dateTime); + + int w = cal.get(Calendar.DAY_OF_WEEK) - 1; // 鎸囩ず涓�涓槦鏈熶腑鐨勬煇澶┿�� + if (w < 0) + w = 0; + return weekDays[w]; + } + + /** + * 鑾峰彇涓や釜鏃堕棿鐩稿樊鍒嗛挓鏁� + * @param startTime 寮�濮嬫椂闂� + * @param endTime 缁撴潫鏃堕棿 + * @return 鍒嗛挓 + */ + public static long differMinute(Date startTime, Date endTime) { + long NTime = startTime.getTime(); + long OTime = endTime.getTime(); + return (NTime - OTime) / 1000 / 60; + } + + /** + * 鑾峰彇涓や釜鏃堕棿鐩稿樊鍒嗛挓鏁� + * @param startTime 寮�濮嬫椂闂� + * @param endTime 缁撴潫鏃堕棿 + * @param remainder 浣欐暟杩�1 + * @return 鍒嗛挓 + */ + public static int differMinute(Date startTime, Date endTime,boolean remainder) { + BigDecimal sTime = new BigDecimal(startTime.getTime()); + BigDecimal eTime = new BigDecimal(endTime.getTime()); + eTime = eTime.subtract(sTime).setScale(0,RoundingMode.HALF_UP); + if(remainder){ + eTime = eTime.divide(BigDecimal.valueOf(60000.0)).setScale(0, RoundingMode.UP); + }else{ + eTime = eTime.divide(BigDecimal.valueOf(60000.0)).setScale(0, RoundingMode.DOWN); + } + return eTime.intValue(); + } + + /** + * endTime姣攕tartTime澶氱殑澶╂暟 + * @param startTime 鏈�灏忔椂闂� + * @param endTime 鏈�澶ф椂闂� + * @return 杩斿洖 + */ + public static Integer differDay(Date startTime,Date endTime){ + Calendar cal1 = Calendar.getInstance(); + cal1.setTime(startTime); + + Calendar cal2 = Calendar.getInstance(); + cal2.setTime(endTime); + int day1= cal1.get(Calendar.DAY_OF_YEAR); + int day2 = cal2.get(Calendar.DAY_OF_YEAR); + + int year1 = cal1.get(Calendar.YEAR); + int year2 = cal2.get(Calendar.YEAR); + if(year1 != year2) { //鍚屼竴骞� + int timeDistance = 0 ; + for(int i = year1 ; i < year2 ; i ++) { + if(i%4==0 && i%100!=0 || i%400==0) {//闂板勾 + timeDistance += 366; + } + else {//涓嶆槸闂板勾 + timeDistance += 365; + } + } + + return timeDistance + (day2-day1) ; + } + else { //涓嶅悓骞� + System.out.println("鍒ゆ柇day2 - day1 : " + (day2-day1)); + return day2-day1; + } + } + + /**鍒ゆ柇涓や釜鏃堕棿鏄笉鏄悓涓�澶�*/ + public static boolean timeEqual(Date startTime,Date endTime){ + if(startTime == null || endTime==null){ + return false; + } + boolean status = false; + if(formatDate(startTime,"yyyyMMdd").equals(formatDate(endTime,"yyyyMMdd"))){ + status = true; + } + return status; + } + + /**鎶婄杞崲鎴怷澶鏃禭鍒哫绉�*/ + public static String getChineseStr(Integer second) { + int day = 24 * 60 * 60; + int hour = 60 * 60; + int min = 60; + + int dayNum = second / day; + int hourNum = second % day / hour; + int minNum = second % day % hour / min; + second = second % day % hour % min; + + String str = dayNum > 0 ? dayNum + "澶�" : ""; + str += hourNum > 0 ? hourNum + "鏃�" : ""; + str += minNum > 0 ? minNum + "鍒�" : ""; + str += second + "绉�"; + + return str; + } + + /** + * 閽堝str鏍煎紡鐨勬椂闂村仛杞崲 鏍煎紡涓�"xx:xx" + * @param time 浼犲叆鐨勬椂闂� + * @return 杩斿洖鍒嗛挓濡傛灉10锛�25,鍒欒繑鍥�625 + */ + public static int getMinuteNum(String time){ + + if(!StringUtils.isEmpty(time)) + { + String[] arr = time.split(":"); + if(arr != null && arr.length == 2) + { + return Integer.parseInt(arr[0]) * 60 + Integer.parseInt(arr[1]); + } + } + + return 0; + } + + /** + * 鑾峰彇褰撳墠鏈堢殑寮�濮嬫椂闂� + * @param time 鏃堕棿 + * @return 杩斿洖鏃堕棿 鏍煎紡yyyy-MM-dd 00:00:00 + */ + public static Date getMonthStart(Date time) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(time); + calendar.set(Calendar.DAY_OF_MONTH, 1); + calendar.set(Calendar.HOUR_OF_DAY, 0); + calendar.set(Calendar.MINUTE, 0); + calendar.set(Calendar.SECOND, 0); + calendar.set(Calendar.MILLISECOND,0); + return calendar.getTime(); + } + + /** + * 鑾峰彇褰撳墠鏈堢殑寮�濮嬫椂闂� + * + * @param num 0鎷垮彇褰撴湀锛屾浠h〃鍚庯紝璐熶唬琛ㄥ墠锛屽�间负鍑犱釜锛堟湀锛� + * @return 杩斿洖鏃堕棿 鏍煎紡yyyy-MM-dd 00:00:00 + */ + public static String getMonthStart(Integer num) { + Calendar calendar = Calendar.getInstance(); + calendar.add(Calendar.MONTH, num); + calendar.set(Calendar.DAY_OF_MONTH, 1); + calendar.set(Calendar.HOUR_OF_DAY, 0); + calendar.set(Calendar.MINUTE, 0); + calendar.set(Calendar.SECOND, 0); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA); + return sdf.format(calendar.getTime()); + } + + /** + * 鑾峰彇褰撳墠鏈堢殑缁撴潫鏃堕棿 + * @param date 鐐瑰墠鏃堕棿 + * @return 杩斿洖鏃堕棿 鏍煎紡yyyy-MM-dd 23:59:59999 + */ + public static Date getMonthEnd(Date date) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); + calendar.set(Calendar.HOUR_OF_DAY, 23); + calendar.set(Calendar.MINUTE, 59); + calendar.set(Calendar.SECOND, 59); + calendar.set(Calendar.MILLISECOND,999); + return calendar.getTime(); + } + + /** + * 鑾峰彇褰撳墠鏈堢殑缁撴潫鏃堕棿锛屾病鏈夋绉� + * @param date 鐐瑰墠鏃堕棿 + * @return 杩斿洖鏃堕棿 鏍煎紡yyyy-MM-dd 23:59:59 + */ + public static Date getMonthEndNoMillisecond(Date date) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); + calendar.set(Calendar.HOUR_OF_DAY, 23); + calendar.set(Calendar.MINUTE, 59); + calendar.set(Calendar.SECOND, 59); + return calendar.getTime(); + } + + /** + * 鑾峰彇褰撳墠鏈堢殑缁撴潫鏃堕棿 + * @param num 0鎷垮彇褰撴湀锛屾浠h〃鍚庯紝璐熶唬琛ㄥ墠锛屽�间负鍑犱釜锛堟湀锛� + * @return 杩斿洖鏃堕棿 鏍煎紡yyyy-MM-dd 23:59:59 + */ + public static String getMonthEnd(Integer num) { + Calendar calendar = Calendar.getInstance(); + calendar.add(Calendar.MONTH, num); + calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); + calendar.set(Calendar.HOUR_OF_DAY, 23); + calendar.set(Calendar.MINUTE, 59); + calendar.set(Calendar.SECOND, 59); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA); + return sdf.format(calendar.getTime()); + } + + /** + * 鑾峰彇褰撳墠骞寸殑寮�濮嬫椂闂� + * @param time 鏃堕棿 + * @return 杩斿洖鏃堕棿 鏍煎紡yyyy-MM-dd 00:00:00 + */ + public static Date getYearStart(Date time) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(time); + calendar.set(Calendar.MONTH, 0); + calendar.set(Calendar.DAY_OF_MONTH, 1); + calendar.set(Calendar.HOUR_OF_DAY, 0); + calendar.set(Calendar.MINUTE, 0); + calendar.set(Calendar.SECOND, 0); + calendar.set(Calendar.MILLISECOND,0); + return calendar.getTime(); + } + + /** + * 鑾峰彇褰撳墠骞寸殑缁撴潫鏃堕棿 + * @param time 鏃堕棿 + * @return 杩斿洖鏃堕棿 鏍煎紡yyyy-MM-dd 23:59:59999 + */ + public static Date getYearEnd(Date time) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(time); + calendar.set(Calendar.MONTH, 11); + calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DATE)); + calendar.set(Calendar.HOUR_OF_DAY, 23); + calendar.set(Calendar.MINUTE, 59); + calendar.set(Calendar.SECOND, 59); + calendar.set(Calendar.MILLISECOND,999); + return calendar.getTime(); + } + + /** + * 鑾峰彇褰撳墠骞寸殑缁撴潫鏃堕棿锛屾病鏈夋绉� + * @param time 鏃堕棿 + * @return 杩斿洖鏃堕棿 鏍煎紡yyyy-MM-dd 23:59:59 + */ + public static Date getYearEndNoMillisecond(Date time) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(time); + calendar.set(Calendar.MONTH, 11); + calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DATE)); + calendar.set(Calendar.HOUR_OF_DAY, 23); + calendar.set(Calendar.MINUTE, 59); + calendar.set(Calendar.SECOND, 59); + return calendar.getTime(); + } + + + /**杩欏ぉ鐨勫紑濮嬫椂闂� + * 鏃ユ湡2000-01-01鍙�2000-01-01 00:00:00 + */ + public static String dayToStart(Date date) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + calendar.set(Calendar.HOUR_OF_DAY, 0); + calendar.set(Calendar.MINUTE, 0); + calendar.set(Calendar.SECOND, 0); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA); + return sdf.format(calendar.getTime()); + } + + /**杩欏ぉ鐨勬渶鍚庢椂闂� + * 鏃ユ湡2000-01-01鍙�2000-01-01 23:59:59 + */ + public static String dayToEnd(Date date) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + calendar.set(Calendar.HOUR_OF_DAY, 23); + calendar.set(Calendar.MINUTE, 59); + calendar.set(Calendar.SECOND, 59); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA); + return sdf.format(calendar.getTime()); + } + + /**杩欏ぉ鐨勫紑濮嬫椂闂� + * 鏃ユ湡2000-01-01鍙�2000-01-01 00:00:00 + */ + public static Date dayToStartDate(Date date) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + calendar.set(Calendar.HOUR_OF_DAY, 0); + calendar.set(Calendar.MINUTE, 0); + calendar.set(Calendar.SECOND, 0); + calendar.set(Calendar.MILLISECOND, 0); + return calendar.getTime(); + } + + /**杩欏ぉ鐨勬渶鍚庢椂闂� + * 鏃ユ湡2000-01-01鍙�2000-01-01 23:59:59999 + */ + public static Date dayToEndDate(Date date) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + calendar.set(Calendar.HOUR_OF_DAY, 23); + calendar.set(Calendar.MINUTE, 59); + calendar.set(Calendar.SECOND, 59); + calendar.set(Calendar.MILLISECOND, 999); + return calendar.getTime(); + } + + /**杩欏ぉ鐨勬渶鍚庢椂闂达紝娌℃湁姣 + * 鏃ユ湡2000-01-01鍙�2000-01-01 23:59:59 + */ + public static Date dayToEndDateNoMillisecond(Date date) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + calendar.set(Calendar.HOUR_OF_DAY, 23); + calendar.set(Calendar.MINUTE, 59); + calendar.set(Calendar.SECOND, 59); + return calendar.getTime(); + } + + /**鑾峰彇鏈堜唤鐨勫ぉ鏁� + * @param date 鏃堕棿 + * @return 鏈堜唤鐨勫ぉ鏁� + */ + public static int getMonthDays(Date date) { + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + cal.set(Calendar.DATE, 1); + cal.roll(Calendar.DATE, -1); + return cal.getActualMaximum(Calendar.DATE); + } + + /**鑾峰彇鏈堜唤鐨勫ぉ鏁� + * @param year 骞翠唤 + * @param month 鏈堜唤 + * @return 鏈堜唤鐨勫ぉ鏁� + */ + public static int getMonthDays(int year, int month) { + Calendar cal = Calendar.getInstance(); + cal.set(Calendar.YEAR, year); + cal.set(Calendar.MONTH, (month - 1)); + cal.set(Calendar.DATE, 1); + cal.roll(Calendar.DATE, -1); + return cal.getActualMaximum(Calendar.DATE); + } + + /**鑾峰彇鏈堜唤鐨勫ぉ鏁� + * @param yearMonth 骞存湀 + * @param format 鏃堕棿鏍煎紡 + * @return 杩斿洖 + */ + public static int getMonthDays(String yearMonth,String format) { + SimpleDateFormat sdf = new SimpleDateFormat(format); + Calendar calendar = Calendar.getInstance(); + try { + calendar.setTime(sdf.parse(yearMonth)); + } catch (ParseException e) { + e.printStackTrace(); + } + calendar.getActualMaximum(Calendar.DAY_OF_MONTH); + return calendar.getActualMaximum(Calendar.DAY_OF_MONTH); + } + + /**褰撳ぉ澶氬皯鐐瑰墠 + * @param date 鏃堕棿 + * @param num 澶氬皯鐐瑰墠锛屼笉鍚綋鐐瑰墠锛�24灏忔椂鍒� + * @return 鏈堜唤鐨勫ぉ鏁� + */ + public static boolean getFrontMinute(Date date,int num) { + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + cal.set(Calendar.HOUR_OF_DAY, num-1); + cal.set(Calendar.MINUTE, 59); + cal.set(Calendar.SECOND, 59); + + return date.compareTo(cal.getTime()) < 1; + } + + /** + * 鑾峰緱鏌愪釜鏃ユ湡鐨勫綋澶╂煇鐐� + * 渚嬪:2022-12-26 11:20:00 -> 2022-12-26 13:00:00 + * @param num 24灏忔椂 + */ + public static String getHourDayTime(Date date,int num) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + calendar.set(Calendar.HOUR_OF_DAY, num); + calendar.set(Calendar.MINUTE, 0); + calendar.set(Calendar.SECOND, 0); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA); + return sdf.format(calendar.getTime()); + } + + /** + * 鑾峰彇鏃堕棿褰撴湀鍓╀綑澶╂暟 + * */ + public static Integer getMonthSurplus(Date date) { + Calendar month = Calendar.getInstance(); + month.setTime(new Date()); + month.set(Calendar.DATE, 1); + month.roll(Calendar.DATE, -1); + return month.getActualMaximum(Calendar.DATE) - Calendar.getInstance().get(Calendar.DAY_OF_MONTH); + } + + /**鑾峰彇褰撳墠鏃堕棿鎵�鍦ㄥ懆鐨勫懆涓�00:00:00*/ + public static Date getMonday(Date date) { + Calendar calendar = Calendar.getInstance(Locale.CHINA); + calendar.setTime(date); + //浠ュ懆涓�涓洪鏃� + calendar.setFirstDayOfWeek(Calendar.MONDAY); + calendar.set(Calendar.HOUR_OF_DAY, 0); + calendar.set(Calendar.MINUTE, 0); + calendar.set(Calendar.SECOND, 0); + //鍛ㄤ竴 + calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); + return calendar.getTime(); + } + + /** + * 鏍规嵁鍑虹敓骞存湀鏃ヨ绠楀勾榫� + * @param birth + * @return + */ + public static int getAge(Date birth) { + Calendar cal = Calendar.getInstance(); + int thisYear = cal.get(Calendar.YEAR); + int thisMonth = cal.get(Calendar.MONTH); + int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH); + + cal.setTime(birth); + int birthYear = cal.get(Calendar.YEAR); + int birthMonth = cal.get(Calendar.MONTH); + int birthdayOfMonth = cal.get(Calendar.DAY_OF_MONTH); + + int age = thisYear - birthYear; + + // 鏈冻鏈� + if (thisMonth <= birthMonth) { + // 褰撴湀 + if (thisMonth == birthMonth) { + // 鏈冻鏃� + if (dayOfMonth < birthdayOfMonth) { + age--; + } + } else { + age--; + } + } + return age; + } + + /** + * 鑾峰彇鏌愬ぉ缁撴潫绉掓暟 + * @param dateTime 鏃ユ湡 + * @param lateSecond 寤惰繜绉掓暟 + * @return + */ + public static long todayEndSecond(Date dateTime, Long lateSecond) { + if(dateTime == null){ + dateTime = new Date(); + } + if(lateSecond == null){ + lateSecond = 0L; + } + Date endTime = DateUtil.dayToEndDate(dateTime); + return differSecond(dateTime, endTime) + lateSecond; + } + + /** + * 璁$畻2涓疄闄呯浉宸鏁� + * @param startTime 寮�濮嬫椂闂� + * @param endTime 缁撴潫鏃堕棿 + * @return + */ + public static long differSecond(Date startTime, Date endTime) { + if(startTime == null || endTime == null){ + return 0L; + } + long sTime = startTime.getTime(); + long eTime = endTime.getTime(); + return (eTime - sTime) / 1000L; + } +} diff --git a/hx_common/src/main/java/com/hx/util/DownFileUtil.java b/hx_common/src/main/java/com/hx/util/DownFileUtil.java new file mode 100644 index 0000000..a6535b0 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/DownFileUtil.java @@ -0,0 +1,225 @@ +package com.hx.util; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.*; +import java.net.URLEncoder; + +public class DownFileUtil { + + /** + * 涓嬭浇鏂囦欢宸ュ叿 + * + * @param path + * 瀹屾暣璺緞锛堝彲鐢╯impleToof宸ュ叿鑾峰彇锛� + */ + public static void DownFile(HttpServletRequest request,HttpServletResponse response,String path) { + final String userAgent = request.getHeader("USER-AGENT"); + try { + // AdminUpload adminUpload = dm.find(AdminUpload.class, fileName); + // String str =adminUpload.getPath(); + String filePath = path; + // System.out.println("path"+ServletActionContext.getRequest().getRealPath("/") + // + filePath); + // File downfile = new + // File(ServletActionContext.getRequest().getRealPath("/") + + // filePath); + File downfile = new File(filePath); + String filename = ""; + if(userAgent.equals("MSIE")){//IE娴忚鍣� + filename = URLEncoder.encode(downfile.getName(),"UTF8"); + }else if(userAgent.equals("Mozilla")){//google,鐏嫄娴忚鍣� + filename = new String(downfile.getName().getBytes(), "ISO8859-1"); + }else{ + filename = URLEncoder.encode(downfile.getName(),"UTF8");//鍏朵粬娴忚鍣� + } + InputStream fis = new BufferedInputStream(new FileInputStream( + downfile)); + byte[] buffer = new byte[fis.available()]; + fis.read(buffer); + fis.close(); + response.reset(); + response.addHeader("Content-Disposition", + "attachment;filename=" + filename); + response.addHeader("Content-Length", + "" + downfile.length()); + OutputStream toClient = new BufferedOutputStream( + response.getOutputStream()); + response.setContentType( + "application/octet-stream"); + toClient.write(buffer); + toClient.flush(); + toClient.close(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * 涓嬭浇鏂囦欢宸ュ叿锛堟彁绀洪�夋嫨璺緞锛� + * + * @param path + * 瀹屾暣璺緞锛堝彲鐢╯impleToof宸ュ叿鑾峰彇锛� + */ + public static void DownFileTips(HttpServletRequest request,HttpServletResponse response,String path) { + final String userAgent = request.getHeader("USER-AGENT"); + try { + // AdminUpload adminUpload = dm.find(AdminUpload.class, fileName); + // String str =adminUpload.getPath(); + String filePath = path; + // System.out.println("path"+ServletActionContext.getRequest().getRealPath("/") + // + filePath); + // File downfile = new + // File(ServletActionContext.getRequest().getRealPath("/") + + // filePath); + File downfile = new File(filePath); + + String filename = ""; + if(userAgent.equals("MSIE")){//IE娴忚鍣� + filename = URLEncoder.encode(downfile.getName(),"UTF8"); + }else if(userAgent.equals("Mozilla")){//google,鐏嫄娴忚鍣� + filename = new String(downfile.getName().getBytes(), "ISO8859-1"); + }else{ + filename = URLEncoder.encode(downfile.getName(),"UTF8");//鍏朵粬娴忚鍣� + } + InputStream fis = new BufferedInputStream(new FileInputStream( + downfile)); + byte[] buffer = new byte[fis.available()]; + fis.read(buffer); + fis.close(); + + response.addHeader("Content-Disposition", "attachment;filename="+ new String(filename.getBytes())); + OutputStream toClient= new BufferedOutputStream(response.getOutputStream()); + response.setContentType("application/vnd.ms-excel;charset=utf-8"); + + toClient.write(buffer); + toClient.flush(); + toClient.close(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * 涓嬭浇鏂囦欢宸ュ叿锛堟彁绀洪�夋嫨璺緞锛� + * + * @param downfile + * 瀵煎嚭鐨勬枃浠� + * @param fileName + * 瀵煎嚭鐨勬枃浠跺悕绉� + */ + public static void DownFileTips(HttpServletRequest request, HttpServletResponse response, File downfile, String fileName) { + final String userAgent = request.getHeader("USER-AGENT"); + try { + if(StringUtils.isEmpty(fileName)){ + fileName = downfile.getName(); + } + String filename = ""; + if(userAgent.equals("MSIE")){//IE娴忚鍣� + filename = URLEncoder.encode(fileName,"UTF8"); + }else if(userAgent.equals("Mozilla")){//google,鐏嫄娴忚鍣� + filename = new String(fileName.getBytes(), "ISO8859-1"); + }else{ + filename = URLEncoder.encode(fileName,"UTF8");//鍏朵粬娴忚鍣� + } + InputStream fis = new BufferedInputStream(new FileInputStream( + downfile)); + byte[] buffer = new byte[fis.available()]; + fis.read(buffer); + fis.close(); + + response.addHeader("Content-Disposition", "attachment;filename="+ filename); + OutputStream toClient= new BufferedOutputStream(response.getOutputStream()); + response.setContentType("application/vnd.ms-excel;charset=utf-8"); + + toClient.write(buffer); + toClient.flush(); + toClient.close(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * 涓嬭浇鏂囦欢宸ュ叿锛堟彁绀洪�夋嫨璺緞锛� + * + * @param inputStream + * 瀵煎嚭鐨勬枃浠舵祦 + * @param fileName + * 瀵煎嚭鐨勬枃浠跺悕绉� + */ + public static void DownFileTips(HttpServletRequest request, HttpServletResponse response, InputStream inputStream , String fileName) { + final String userAgent = request.getHeader("USER-AGENT"); + try { + if(StringUtils.isEmpty(fileName)){ + throw new RuntimeException("璇疯緭鍏ユ枃浠跺悕绉�"); + } + String filename = ""; + if(userAgent.equals("MSIE")){//IE娴忚鍣� + filename = URLEncoder.encode(fileName,"UTF8"); + }else if(userAgent.equals("Mozilla")){//google,鐏嫄娴忚鍣� + filename = new String(fileName.getBytes(), "ISO8859-1"); + }else{ + filename = URLEncoder.encode(fileName,"UTF8");//鍏朵粬娴忚鍣� + } + InputStream fis = new BufferedInputStream(inputStream); + byte[] buffer = new byte[fis.available()]; + fis.read(buffer); + fis.close(); + + response.addHeader("Content-Disposition", "attachment;filename="+ filename); + OutputStream toClient= new BufferedOutputStream(response.getOutputStream()); + response.setContentType("application/vnd.ms-excel;charset=utf-8"); + + toClient.write(buffer); + toClient.flush(); + toClient.close(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * 涓嬭浇鏂囦欢宸ュ叿锛堟彁绀洪�夋嫨璺緞锛� + * + * @param downfile + * 瀵煎嚭鐨勬枃浠� + * @param fileName + * 瀵煎嚭鐨勬枃浠跺悕绉� + */ + public static void DownFileTips( HttpServletResponse response, File downfile, String fileName) { + try { + if(StringUtils.isEmpty(fileName)){ + fileName = downfile.getName(); + } + String filename = ""; + filename = URLEncoder.encode(fileName,"UTF8");//鍏朵粬娴忚鍣� + InputStream fis = new BufferedInputStream(new FileInputStream( + downfile)); + byte[] buffer = new byte[fis.available()]; + fis.read(buffer); + fis.close(); + + response.addHeader("Content-Disposition", "attachment;filename="+ filename); + OutputStream toClient= new BufferedOutputStream(response.getOutputStream()); + response.setContentType("application/vnd.ms-excel;charset=utf-8"); + + toClient.write(buffer); + toClient.flush(); + toClient.close(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/hx_common/src/main/java/com/hx/util/EmailUtil.java b/hx_common/src/main/java/com/hx/util/EmailUtil.java new file mode 100644 index 0000000..4434af5 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/EmailUtil.java @@ -0,0 +1,120 @@ +package com.hx.util; + +import com.sun.mail.util.MailSSLSocketFactory; + +import javax.activation.DataHandler; +import javax.activation.DataSource; +import javax.activation.FileDataSource; +import javax.mail.*; +import javax.mail.internet.*; +import java.io.UnsupportedEncodingException; +import java.security.GeneralSecurityException; +import java.util.Properties; + +/**閭欢澶勭悊宸ュ叿 + * @author ChenJiaHe + * @Date 2020-07-06 + */ +public class EmailUtil { + /** + * 鍙戦�佸甫闄勪欢鐨勯偖浠� + * + * @param receive + * 鏀朵欢浜� + * @param subject + * 閭欢涓婚 + * @param msg + * 閭欢鍐呭 + * @param filename + * 闄勪欢鍦板潃 + * @param from + * 鍙戜欢浜虹數瀛愰偖绠� + * @param pass + * 鍙戜欢浜虹數瀛愰偖绠卞瘑鐮� + * @return + * @throws GeneralSecurityException + */ + public static boolean sendMail(String receive, String subject, String msg, String filename, + String from,String pass) + throws GeneralSecurityException { + if (StringUtils.isEmpty(receive)) { + return false; + } + + // 鎸囧畾鍙戦�侀偖浠剁殑涓绘満涓� smtp.qq.com smtp.163.com + String host = "smtp.qq.com"; // 閭欢鏈嶅姟鍣� + + // 鑾峰彇绯荤粺灞炴�� + Properties properties = System.getProperties(); + + // 璁剧疆閭欢鏈嶅姟鍣� + properties.setProperty("mail.smtp.host", host); + + properties.put("mail.smtp.auth", "true"); + MailSSLSocketFactory sf = new MailSSLSocketFactory(); + sf.setTrustAllHosts(true); + properties.put("mail.smtp.ssl.enable", "true"); + properties.put("mail.smtp.ssl.socketFactory", sf); + // 鑾峰彇榛樿session瀵硅薄 + Session session = Session.getDefaultInstance(properties, new Authenticator() { + public PasswordAuthentication getPasswordAuthentication() { // qq閭鏈嶅姟鍣ㄨ处鎴枫�佺涓夋柟鐧诲綍鎺堟潈鐮� + return new PasswordAuthentication(from, pass); // 鍙戜欢浜洪偖浠剁敤鎴峰悕銆佸瘑鐮� + } + }); + + try { + // 鍒涘缓榛樿鐨� MimeMessage 瀵硅薄 + MimeMessage message = new MimeMessage(session); + + // Set From: 澶撮儴澶村瓧娈� + message.setFrom(new InternetAddress(from)); + + // Set To: 澶撮儴澶村瓧娈� + message.addRecipient(Message.RecipientType.TO, new InternetAddress(receive)); + + // Set Subject: 涓婚鏂囧瓧 + message.setSubject(subject); + + // 鍒涘缓娑堟伅閮ㄥ垎 + BodyPart messageBodyPart = new MimeBodyPart(); + + // 娑堟伅 + messageBodyPart.setText(msg); + + // 鍒涘缓澶氶噸娑堟伅 + Multipart multipart = new MimeMultipart(); + + // 璁剧疆鏂囨湰娑堟伅閮ㄥ垎 + multipart.addBodyPart(messageBodyPart); + + // 闄勪欢閮ㄥ垎 + messageBodyPart = new MimeBodyPart(); + // 璁剧疆瑕佸彂閫侀檮浠剁殑鏂囦欢璺緞 + if(SimpleTool.checkNotNull(filename)){ + DataSource source = new FileDataSource(filename); + if(!SimpleTool.checkNotNull(source)){ + throw new RuntimeException("鑾峰彇闄勪欢澶辫触锛�"); + } + messageBodyPart.setDataHandler(new DataHandler(source)); + // messageBodyPart.setFileName(filename); + // 澶勭悊闄勪欢鍚嶇О涓枃锛堥檮甯︽枃浠惰矾寰勶級涔辩爜闂 + //messageBodyPart.setFileName(MimeUtility.encodeText(source.getName())); + messageBodyPart.setFileName(new String(source.getName().toString().getBytes("UTF-8"))); + multipart.addBodyPart(messageBodyPart); + } + + // 鍙戦�佸畬鏁存秷鎭� + message.setContent(multipart); + + // 鍙戦�佹秷鎭� + Transport.send(message); + // System.out.println("Sent message successfully...."); + return true; + } catch (MessagingException e) { + e.printStackTrace(); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + return false; + } +} diff --git a/hx_common/src/main/java/com/hx/util/ExcelFileUtil.java b/hx_common/src/main/java/com/hx/util/ExcelFileUtil.java new file mode 100644 index 0000000..2b28c71 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/ExcelFileUtil.java @@ -0,0 +1,129 @@ +package com.hx.util; + + +import com.hx.exception.TipsException; +import jxl.CellType; +import org.apache.poi.hssf.usermodel.*; +import org.apache.poi.ss.usermodel.*; +import org.springframework.web.multipart.MultipartFile; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; + +/** + * Excel宸ュ叿绫伙紙鍏煎poi4.0+锛� + */ +public class ExcelFileUtil { + + /** + * 璇诲彇 Excel鏂囦欢鍐呭 + * + * @param file + * @param header 鏄惁鍖呮嫭琛ㄥご + * @return + * @throws Exception + */ + public static List<List<String>> readExcelByeFileData(MultipartFile file, boolean header) throws Exception { + // 缁撴灉闆� + List<List<String>> list = new ArrayList<>(); + if (file == null){ + return list; + } + String fileName = file.getOriginalFilename(); + if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) { + throw new TipsException("涓婁紶鏂囦欢鏍煎紡涓嶆纭�"); + } + + Workbook hssfworkbook = WorkbookFactory.create(file.getInputStream()); + + int num = hssfworkbook.getNumberOfSheets(); + if (num == 0){ + return list; + } + List<String> rowList; + for (int k = 0; k< num ; k++) { + Sheet sheet = hssfworkbook.getSheetAt(k); + + for (int i = 0; i <= sheet.getLastRowNum(); i++) { + rowList = new ArrayList<>(); + // 鑾峰彇绗琲琛岀殑鏁版嵁 + Row row = sheet.getRow(i); + // getLastCellNum() 鑾峰彇杩欎竴琛屼腑鍗曞厓鏍肩殑鏁伴噺 + for (int j = 0; j < row.getLastCellNum(); j++) { + // 鑾峰彇绗琲琛岀j鍒楃殑鍗曞厓鏍兼暟鎹� + rowList.add(row.getCell(j).toString()); + } + list.add(rowList); + } + } + return list; + } + + + /** + * 璇诲彇 Excel鏂囦欢鍐呭 + * + * @param file + * @param header 鏄惁鍖呮嫭琛ㄥご + * @return + * @throws Exception + */ + public static List<List<String>> readExcelByeFileData(File file, boolean header) throws Exception { + // 缁撴灉闆� + List<List<String>> list = new ArrayList<>(); + if (file == null){ + return list; + } + String fileName = file.getName(); + if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) { + throw new TipsException("涓婁紶鏂囦欢鏍煎紡涓嶆纭�"); + } + + Workbook hssfworkbook = WorkbookFactory.create(new FileInputStream(file)); + + int num = hssfworkbook.getNumberOfSheets(); + if (num == 0){ + return list; + } + List<String> rowList; + for (int k = 0; k< num ; k++) { + Sheet sheet = hssfworkbook.getSheetAt(k); + + for (int i = 0; i <= sheet.getLastRowNum(); i++) { + rowList = new ArrayList<>(); + // 鑾峰彇绗琲琛岀殑鏁版嵁 + Row row = sheet.getRow(i); + // getLastCellNum() 鑾峰彇杩欎竴琛屼腑鍗曞厓鏍肩殑鏁伴噺 + for (int j = 0; j < row.getLastCellNum(); j++) { + // 鑾峰彇绗琲琛岀j鍒楃殑鍗曞厓鏍兼暟鎹� + rowList.add(row.getCell(j).toString()); + } + list.add(rowList); + } + } + return list; + } + + + + private static String objToString(Object obj) { + if (obj == null) { + return ""; + } else { + if (obj instanceof String) { + return (String) obj; + } else if (obj instanceof Date) { + return null; + } else { + return obj.toString(); + } + } + } + + +} diff --git a/hx_common/src/main/java/com/hx/util/ExcelUtil.java b/hx_common/src/main/java/com/hx/util/ExcelUtil.java new file mode 100644 index 0000000..da09b9b --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/ExcelUtil.java @@ -0,0 +1,1133 @@ +package com.hx.util; + +import com.hx.exception.TipsException; +import com.monitorjbl.xlsx.StreamingReader; +import org.apache.poi.hssf.usermodel.*; +import org.apache.poi.openxml4j.exceptions.OLE2NotOfficeXmlFileException; +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.xssf.streaming.SXSSFWorkbook; +import org.apache.poi.xssf.usermodel.XSSFCell; +import org.apache.poi.xssf.usermodel.XSSFRow; +import org.apache.poi.xssf.usermodel.XSSFSheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.springframework.web.multipart.MultipartFile; + +import javax.imageio.ImageIO; +import java.awt.image.BufferedImage; +import java.io.*; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; + + +/** + * + * @author hjr + */ +public final class ExcelUtil { + + /** + * @param excelName + * 鏂囦欢鍚嶇О + * @param outPath + * 淇濆瓨璺緞 + * @param headList + * Excel鏂囦欢Head鏍囬闆嗗悎 + * @param fieldList + * Excel鏂囦欢Field鏍囬闆嗗悎 鏍规嵁field鏉ュ鎵句綅缃~鍏呰〃鏍� + * @param dataList + * Excel鏂囦欢鏁版嵁鍐呭閮ㄥ垎 + * @throws Exception + */ + public static String createExcel(String outPath, String excelName, + String[] headList, String[] fieldList, + List<Map<String, Object>> dataList) throws Exception { + + String filePath = null; + // 鍒涘缓鏂扮殑Excel 宸ヤ綔绨� + HSSFWorkbook workbook = new HSSFWorkbook(); + + // 鍦‥xcel宸ヤ綔绨夸腑寤轰竴宸ヤ綔琛紝鍏跺悕涓虹己鐪佸�� + // 濡傝鏂板缓涓�鍚嶄负"鏁堢泭鎸囨爣"鐨勫伐浣滆〃锛屽叾璇彞涓猴細 + // HSSFSheet sheet = workbook.createSheet("鏁堢泭鎸囨爣"); + HSSFSheet sheet = workbook.createSheet(); + // 鍦ㄧ储寮�0鐨勪綅缃垱寤鸿锛堟渶椤剁鐨勮锛� + HSSFRow row = sheet.createRow(0); + // =============================================================== + + HSSFCell cell; + for (int i = 0; i < headList.length; i++) { + // 鍦ㄧ储寮�0鐨勪綅缃垱寤哄崟鍏冩牸锛堝乏涓婄锛� + cell = row.createCell(i); + // 瀹氫箟鍗曞厓鏍间负瀛楃涓茬被鍨� + //cell.setCellType(HSSFCell.CELL_TYPE_STRING); + // 鍦ㄥ崟鍏冩牸涓緭鍏ヤ竴浜涘唴瀹� + cell.setCellValue(headList[i]); + } + // =============================================================== + if (dataList != null) { + HSSFRow row_value; + Map<String, Object> dataMap; + for (int n = 0; n < dataList.size(); n++) { + // 鍦ㄧ储寮�1鐨勪綅缃垱寤鸿 + row_value = sheet.createRow(n + 1); + dataMap = dataList.get(n); + // =============================================================== + for (int i = 0; i < fieldList.length; i++) { + // 鍦ㄧ储寮�0鐨勪綅缃垱寤哄崟鍏冩牸锛堝乏涓婄锛� + cell = row_value.createCell(i); + // 瀹氫箟鍗曞厓鏍间负瀛楃涓茬被鍨� + //cell.setCellType(HSSFCell.CELL_TYPE_STRING); + // 鍦ㄥ崟鍏冩牸涓緭鍏ヤ竴浜涘唴瀹� + cell.setCellValue(objToString(dataMap.get(fieldList[i]))); + } + // =============================================================== + } + } + + // 鏂板缓涓�杈撳嚭鏂囦欢娴� + File file = SimpleTool.createFile(outPath, excelName); + FileOutputStream fOut = new FileOutputStream(file); + // 鎶婄浉搴旂殑Excel 宸ヤ綔绨垮瓨鐩� + workbook.write(fOut); + fOut.flush(); + // 鎿嶄綔缁撴潫锛屽叧闂枃浠� + fOut.close(); + + if(outPath.endsWith("/")){ + filePath = outPath + excelName; + }else{ + filePath = outPath +"/"+ excelName; + } + return filePath; + } + + /**鐢熸垚涓存椂鏂囦欢 + * @param headList + * Excel鏂囦欢Head鏍囬闆嗗悎 + * @param fieldList + * Excel鏂囦欢Field鏍囬闆嗗悎 鏍规嵁field鏉ュ鎵句綅缃~鍏呰〃鏍� + * @param dataList + * Excel鏂囦欢鏁版嵁鍐呭閮ㄥ垎 + * @throws Exception + */ + public static File createExcel(String[] headList, String[] fieldList, + List<Map<String, Object>> dataList) throws Exception { + File file = File.createTempFile("temp", ".xlsx"); + try{ + // 鍒涘缓鏂扮殑Excel 宸ヤ綔绨� + HSSFWorkbook workbook = new HSSFWorkbook(); + + // 鍦‥xcel宸ヤ綔绨夸腑寤轰竴宸ヤ綔琛紝鍏跺悕涓虹己鐪佸�� + // 濡傝鏂板缓涓�鍚嶄负"鏁堢泭鎸囨爣"鐨勫伐浣滆〃锛屽叾璇彞涓猴細 + // HSSFSheet sheet = workbook.createSheet("鏁堢泭鎸囨爣"); + HSSFSheet sheet = workbook.createSheet(); + // 鍦ㄧ储寮�0鐨勪綅缃垱寤鸿锛堟渶椤剁鐨勮锛� + HSSFRow row = sheet.createRow(0); + // =============================================================== + HSSFCell cell; + for (int i = 0; i < headList.length; i++) { + // 鍦ㄧ储寮�0鐨勪綅缃垱寤哄崟鍏冩牸锛堝乏涓婄锛� + cell = row.createCell(i); + // 瀹氫箟鍗曞厓鏍间负瀛楃涓茬被鍨� + //cell.setCellType(HSSFCell.CELL_TYPE_STRING); + // 鍦ㄥ崟鍏冩牸涓緭鍏ヤ竴浜涘唴瀹� + cell.setCellValue(headList[i]); + } + // =============================================================== + if (dataList != null) { + HSSFRow row_value; + Map<String, Object> dataMap; + for (int n = 0; n < dataList.size(); n++) { + // 鍦ㄧ储寮�1鐨勪綅缃垱寤鸿 + row_value = sheet.createRow(n + 1); + dataMap = dataList.get(n); + // =============================================================== + for (int i = 0; i < fieldList.length; i++) { + // 鍦ㄧ储寮�0鐨勪綅缃垱寤哄崟鍏冩牸锛堝乏涓婄锛� + cell = row_value.createCell(i); + // 瀹氫箟鍗曞厓鏍间负瀛楃涓茬被鍨� + //cell.setCellType(HSSFCell.CELL_TYPE_STRING); + // 鍦ㄥ崟鍏冩牸涓緭鍏ヤ竴浜涘唴瀹� + cell.setCellValue(objToString(dataMap.get(fieldList[i]))); + } + // =============================================================== + } + } + + // 鏂板缓涓�杈撳嚭鏂囦欢娴� + FileOutputStream fOut = new FileOutputStream(file); + // 鎶婄浉搴旂殑Excel 宸ヤ綔绨垮瓨鐩� + workbook.write(fOut); + fOut.flush(); + // 鎿嶄綔缁撴潫锛屽叧闂枃浠� + fOut.close(); + }catch (Exception e){ + + }finally { + file.deleteOnExit(); + } + return file; + } + + /**鐢熸垚涓存椂鏂囦欢 + * @param headList + * Excel鏂囦欢Head鏍囬闆嗗悎 + * @param fieldList + * Excel鏂囦欢Field鏍囬闆嗗悎 鏍规嵁field鏉ュ鎵句綅缃~鍏呰〃鏍� + * @param dataList + * Excel鏂囦欢鏁版嵁鍐呭閮ㄥ垎 + * @throws Exception + */ + public static File createExcel(String[] headList, String[] fieldList, List<Map<String, Object>> dataList + ,Integer height,Integer width) throws Exception { + File file = File.createTempFile("temp", ".xls"); + try{ + + if(height == null){ + height = 450; + } + if(width == null){ + width = 5000; + } + // 鍒涘缓鏂扮殑Excel 宸ヤ綔绨� + HSSFWorkbook workbook = new HSSFWorkbook(); + + //鍚堝苟鐨勫崟鍏冩牸鏍峰紡 + HSSFCellStyle boderStyle = workbook.createCellStyle(); + //鍨傜洿灞呬腑 + boderStyle.setVerticalAlignment(VerticalAlignment.CENTER); + boderStyle.setAlignment(HorizontalAlignment.CENTER); // 鍒涘缓涓�涓眳涓牸寮� + + // 鍦‥xcel宸ヤ綔绨夸腑寤轰竴宸ヤ綔琛紝鍏跺悕涓虹己鐪佸�� + // 濡傝鏂板缓涓�鍚嶄负"鏁堢泭鎸囨爣"鐨勫伐浣滆〃锛屽叾璇彞涓猴細 + // HSSFSheet sheet = workbook.createSheet("鏁堢泭鎸囨爣"); + HSSFSheet sheet = workbook.createSheet(); + // 鍦ㄧ储寮�0鐨勪綅缃垱寤鸿锛堟渶椤剁鐨勮锛� + HSSFRow row = sheet.createRow(0); + // =============================================================== + HSSFCell cell; + for (int i = 0; i < headList.length; i++) { + //楂樺害 + row.setHeight(height.shortValue()); + sheet.setColumnWidth(i,width); + // 鍦ㄧ储寮�0鐨勪綅缃垱寤哄崟鍏冩牸锛堝乏涓婄锛� + cell = row.createCell(i); + // 瀹氫箟鍗曞厓鏍间负瀛楃涓茬被鍨� + //cell.setCellType(HSSFCell.CELL_TYPE_STRING); + // 鍦ㄥ崟鍏冩牸涓緭鍏ヤ竴浜涘唴瀹� + cell.setCellValue(headList[i]); + cell.setCellStyle(boderStyle); + } + // =============================================================== + if (dataList != null) { + HSSFRow row_value; + Map<String, Object> dataMap; + for (int n = 0; n < dataList.size(); n++) { + // 鍦ㄧ储寮�1鐨勪綅缃垱寤鸿 + row_value = sheet.createRow(n + 1); + row_value.setHeight(height.shortValue()); + dataMap = dataList.get(n); + // =============================================================== + for (int i = 0; i < fieldList.length; i++) { + // 鍦ㄧ储寮�0鐨勪綅缃垱寤哄崟鍏冩牸锛堝乏涓婄锛� + sheet.setColumnWidth(i,width); + cell = row_value.createCell(i); + // 瀹氫箟鍗曞厓鏍间负瀛楃涓茬被鍨� + //cell.setCellType(HSSFCell.CELL_TYPE_STRING); + // 鍦ㄥ崟鍏冩牸涓緭鍏ヤ竴浜涘唴瀹� + cell.setCellValue(objToString(dataMap.get(fieldList[i]))); + cell.setCellStyle(boderStyle); + } + // =============================================================== + } + } + + // 鏂板缓涓�杈撳嚭鏂囦欢娴� + FileOutputStream fOut = new FileOutputStream(file); + // 鎶婄浉搴旂殑Excel 宸ヤ綔绨垮瓨鐩� + workbook.write(fOut); + fOut.flush(); + // 鎿嶄綔缁撴潫锛屽叧闂枃浠� + fOut.close(); + }catch (Exception e){ + + }finally { + file.deleteOnExit(); + } + return file; + } + + /**鏃犻檺鍒惰鏁扮敓鎴恊cxel锛岀敓鎴愪复鏃舵枃浠� + * @param headList + * Excel鏂囦欢Head鏍囬闆嗗悎 + * @param fieldList + * Excel鏂囦欢Field鏍囬闆嗗悎 鏍规嵁field鏉ュ鎵句綅缃~鍏呰〃鏍� + * @param dataList + * Excel鏂囦欢鏁版嵁鍐呭閮ㄥ垎 + * @param height 鍗曞厓鏍奸珮搴︼紝榛樿450 + * @param width 鍗曞厓鏍煎搴︼紝榛樿5000 + * @throws Exception + */ + public static File createXSSExcel(String[] headList, String[] fieldList, List<Map<String, Object>> dataList + ,Integer height,Integer width) throws Exception { + File file = File.createTempFile("temp", ".xls"); + try{ + + if(height == null){ + height = 450; + } + if(width == null){ + width = 5000; + } + // 鍒涘缓鏂扮殑Excel 宸ヤ綔绨� + //XSSFWorkbook workbook = new XSSFWorkbook(); + SXSSFWorkbook workbook = new SXSSFWorkbook(1000); + + //鍚堝苟鐨勫崟鍏冩牸鏍峰紡 + CellStyle boderStyle = workbook.createCellStyle(); + //鍨傜洿灞呬腑 + boderStyle.setVerticalAlignment(VerticalAlignment.CENTER); + boderStyle.setAlignment(HorizontalAlignment.CENTER); // 鍒涘缓涓�涓眳涓牸寮� + + // 鍦‥xcel宸ヤ綔绨夸腑寤轰竴宸ヤ綔琛紝鍏跺悕涓虹己鐪佸�� + // 濡傝鏂板缓涓�鍚嶄负"鏁堢泭鎸囨爣"鐨勫伐浣滆〃锛屽叾璇彞涓猴細 + // HSSFSheet sheet = workbook.createSheet("鏁堢泭鎸囨爣"); + Sheet sheet = workbook.createSheet(); + // 鍦ㄧ储寮�0鐨勪綅缃垱寤鸿锛堟渶椤剁鐨勮锛� + Row row = sheet.createRow(0); + // =============================================================== + Cell cell; + for (int i = 0; i < headList.length; i++) { + //楂樺害 + row.setHeight(height.shortValue()); + sheet.setColumnWidth(i,width); + // 鍦ㄧ储寮�0鐨勪綅缃垱寤哄崟鍏冩牸锛堝乏涓婄锛� + cell = row.createCell(i); + // 瀹氫箟鍗曞厓鏍间负瀛楃涓茬被鍨� + //cell.setCellType(HSSFCell.CELL_TYPE_STRING); + // 鍦ㄥ崟鍏冩牸涓緭鍏ヤ竴浜涘唴瀹� + cell.setCellValue(headList[i]); + cell.setCellStyle(boderStyle); + } + // =============================================================== + if (dataList != null) { + Row row_value; + Map<String, Object> dataMap; + for (int n = 0; n < dataList.size(); n++) { + // 鍦ㄧ储寮�1鐨勪綅缃垱寤鸿 + row_value = sheet.createRow(n + 1); + row_value.setHeight(height.shortValue()); + dataMap = dataList.get(n); + // =============================================================== + for (int i = 0; i < fieldList.length; i++) { + // 鍦ㄧ储寮�0鐨勪綅缃垱寤哄崟鍏冩牸锛堝乏涓婄锛� + sheet.setColumnWidth(i,width); + cell = row_value.createCell(i); + // 瀹氫箟鍗曞厓鏍间负瀛楃涓茬被鍨� + //cell.setCellType(HSSFCell.CELL_TYPE_STRING); + // 鍦ㄥ崟鍏冩牸涓緭鍏ヤ竴浜涘唴瀹� + cell.setCellValue(objToString(dataMap.get(fieldList[i]))); + cell.setCellStyle(boderStyle); + } + // =============================================================== + } + } + + // 鏂板缓涓�杈撳嚭鏂囦欢娴� + FileOutputStream fOut = new FileOutputStream(file); + // 鎶婄浉搴旂殑Excel 宸ヤ綔绨垮瓨鐩� + workbook.write(fOut); + fOut.flush(); + // 鎿嶄綔缁撴潫锛屽叧闂枃浠� + fOut.close(); + }catch (Exception e){ + + }finally { + file.deleteOnExit(); + } + return file; + } + + + private static String objToString(Object obj) { + if (obj == null) { + return ""; + } else { + if (obj instanceof String) { + return (String) obj; + } else if (obj instanceof Date) { + return null;// DateUtil.dateToString((Date) + // obj,DateUtil.DATESTYLE_SHORT_EX); + } else { + return obj.toString(); + } + } + } + + /** + * 璇诲彇Excel鏁版嵁 + * @param file + * @param header + * @return + * @throws Exception + */ + public static List<List<String>> readExcelData(MultipartFile file, boolean header) throws Exception { + + String fileName = file.getOriginalFilename(); + if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) { + throw new TipsException("涓婁紶鏂囦欢鏍煎紡涓嶆纭�"); + } + + //鍒ゆ柇涓嶅悓鏍煎紡澶勭悊鏂规硶涓嶅悓 + if(fileName.matches("^.+\\.(?i)(xls)$")){ + //xls鏍煎紡浣跨敤HSSF + return readExcelByeFileData(file, header); + }else{ + //xlsx鏍煎紡浣跨敤XSSF + return readExcelByeFileDataToXSSF(file, header); + } + } + + /** + * 璇诲彇 Excel鏂囦欢鍐呭 + * + * @param file + * @param header 鏄惁鍖呮嫭琛ㄥご + * @return + * @throws Exception + */ + public static List<List<String>> readExcelByeFileData(MultipartFile file, boolean header) throws Exception { + + String fileName = file.getOriginalFilename(); + if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) { + throw new TipsException("涓婁紶鏂囦欢鏍煎紡涓嶆纭�"); + } + + // 缁撴灉闆� + List<List<String>> list = new ArrayList<>(); + + HSSFWorkbook hssfworkbook = new HSSFWorkbook(file.getInputStream()); + + // 閬嶅巻璇ヨ〃鏍间腑鎵�鏈夌殑宸ヤ綔琛紝i琛ㄧず宸ヤ綔琛ㄧ殑鏁伴噺 getNumberOfSheets琛ㄧず宸ヤ綔琛ㄧ殑鎬绘暟 + for(int s=0;s<hssfworkbook.getNumberOfSheets();s++) { + HSSFSheet hssfsheet = hssfworkbook.getSheetAt(s); + int col = 0; + // 閬嶅巻璇ヨ鎵�鏈夌殑琛�,j琛ㄧず琛屾暟 getPhysicalNumberOfRows琛岀殑鎬绘暟 鍘婚櫎鏍囬 + for (int j = 0; j < hssfsheet.getPhysicalNumberOfRows(); j++) { + HSSFRow hssfrow = hssfsheet.getRow(j); + if(hssfrow!=null){ + if(j == 0) { + col = hssfrow.getPhysicalNumberOfCells(); + if(!header) { + //涓嶅寘鎷〃澶� + continue; + } + } + // 鍗曡鏁版嵁 + List<String> arrayString = new ArrayList<>(); + for (int i = 0; i < col; i++) { + HSSFCell cell = hssfrow.getCell(i); + if (cell == null) { + arrayString.add(""); + } else if (cell.getCellType() == CellType.NUMERIC) { + // arrayString[i] = new Double(cell.getNumericCellValue()).toString(); + if (CellType.NUMERIC == cell.getCellType()) { + short format = cell.getCellStyle().getDataFormat(); + if(format == 14 || format == 31 || format == 57 || format == 58){ + //鏃ユ湡锛堜腑鏂囨椂闂存牸寮忕殑锛� + Date d = cell.getDateCellValue(); + DateFormat formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + // DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + arrayString.add(formater.format(d)); + //arrayString[i] = formater.format(d); + }else if (HSSFDateUtil.isCellDateFormatted(cell)) { + Date d = cell.getDateCellValue(); + //DateFormat formater = new SimpleDateFormat("yyyy骞碝M鏈坉d鏃� HH鏃秏m鍒唖s绉�"); + DateFormat formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + arrayString.add(formater.format(d)); + //arrayString[i] = formater.format(d); + } else { + if(CellType.STRING == cell.getCellType()){ + arrayString.add(cell.getStringCellValue()); + //arrayString[i] =cell.getStringCellValue(); + }else if(CellType.FORMULA==cell.getCellType()){ + arrayString.add(cell.getCellFormula()); + //arrayString[i] =cell.getCellFormula(); + }else if(CellType.NUMERIC== cell.getCellType()){ + HSSFDataFormatter dataFormatter = new HSSFDataFormatter(); + arrayString.add(dataFormatter.formatCellValue(cell)); + //arrayString[i] =dataFormatter.formatCellValue(cell); + } + } + } + } else if(cell.getCellType() == CellType.BLANK){ + arrayString.add(""); + //arrayString[i] = ""; + } else { // 濡傛灉EXCEL琛ㄦ牸涓殑鏁版嵁绫诲瀷涓哄瓧绗︿覆鍨� + if(cell.getCellType() != CellType.BOOLEAN){ + arrayString.add(cell.getStringCellValue().trim()); + }else{ + arrayString.add(cell.getBooleanCellValue() ? "TRUE" : "FALSE"); + } + //arrayString[i] = cell.getStringCellValue().trim(); + } + } + list.add(arrayString); + } + } + } + return list; + } + + /** + * 璇诲彇 Excel鏂囦欢鍐呭 + * + * @param file + * @param header 鏄惁鍖呮嫭琛ㄥご + * @return + * @throws Exception + */ + public static List<List<String>> readExcelByeFileDataToXSSF(MultipartFile file, boolean header) throws Exception { + + String fileName = file.getOriginalFilename(); + if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) { + throw new TipsException("涓婁紶鏂囦欢鏍煎紡涓嶆纭�"); + } + + // 缁撴灉闆� + List<List<String>> list = new ArrayList<>(); + + XSSFWorkbook xssfWorkbook = new XSSFWorkbook(file.getInputStream()); + + // 閬嶅巻璇ヨ〃鏍间腑鎵�鏈夌殑宸ヤ綔琛紝i琛ㄧず宸ヤ綔琛ㄧ殑鏁伴噺 getNumberOfSheets琛ㄧず宸ヤ綔琛ㄧ殑鎬绘暟 + for(int s=0;s<xssfWorkbook.getNumberOfSheets();s++) { + XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(s); + int col = 0; + // 閬嶅巻璇ヨ鎵�鏈夌殑琛�,j琛ㄧず琛屾暟 getPhysicalNumberOfRows琛岀殑鎬绘暟 鍘婚櫎鏍囬 + for (int j = 0; j < xssfSheet.getPhysicalNumberOfRows(); j++) { + XSSFRow xssfrow = xssfSheet.getRow(j); + if(xssfrow!=null){ + if(j == 0) { + col = xssfrow.getPhysicalNumberOfCells(); + if(!header) { + //涓嶅寘鎷〃澶� + continue; + } + } + // 鍗曡鏁版嵁 + List<String> arrayString = new ArrayList<>(); + for (int i = 0; i < col; i++) { + XSSFCell cell = xssfrow.getCell(i); + if (cell == null) { + arrayString.add(""); + } else if (cell.getCellType() == CellType.NUMERIC) { + // arrayString[i] = new Double(cell.getNumericCellValue()).toString(); + if (CellType.NUMERIC == cell.getCellType()) { + short format = cell.getCellStyle().getDataFormat(); + if(format == 14 || format == 31 || format == 57 || format == 58){ + //鏃ユ湡锛堜腑鏂囨椂闂存牸寮忕殑锛� + Date d = cell.getDateCellValue(); + DateFormat formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + // DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + arrayString.add(formater.format(d)); + //arrayString[i] = formater.format(d); + }else if (HSSFDateUtil.isCellDateFormatted(cell)) { + Date d = cell.getDateCellValue(); + //DateFormat formater = new SimpleDateFormat("yyyy骞碝M鏈坉d鏃� HH鏃秏m鍒唖s绉�"); + DateFormat formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + arrayString.add(formater.format(d)); + //arrayString[i] = formater.format(d); + } else { + if(CellType.STRING == cell.getCellType()){ + arrayString.add(cell.getStringCellValue()); + //arrayString[i] =cell.getStringCellValue(); + }else if(CellType.FORMULA==cell.getCellType()){ + arrayString.add(cell.getCellFormula()); + //arrayString[i] =cell.getCellFormula(); + }else if(CellType.NUMERIC== cell.getCellType()){ + HSSFDataFormatter dataFormatter = new HSSFDataFormatter(); + arrayString.add(dataFormatter.formatCellValue(cell)); + //arrayString[i] =dataFormatter.formatCellValue(cell); + } + } + } + } else if(cell.getCellType() == CellType.BLANK){ + arrayString.add(""); + //arrayString[i] = ""; + } else { // 濡傛灉EXCEL琛ㄦ牸涓殑鏁版嵁绫诲瀷涓哄瓧绗︿覆鍨� + if(cell.getCellType() != CellType.BOOLEAN){ + arrayString.add(cell.getStringCellValue().trim()); + }else{ + arrayString.add(cell.getBooleanCellValue() ? "TRUE" : "FALSE"); + } + + + //arrayString[i] = cell.getStringCellValue().trim(); + } + } + list.add(arrayString); + } + } + } + return list; + } + + + /**鍒ゆ柇excel鐨勭増鏈�*/ + public static Workbook create(InputStream inp) throws IOException { + //杩欐牱鍐� excel 鑳藉吋瀹�03鍜�07 + return WorkbookFactory.create(inp); + } + + /**璇诲彇excel鏂囦欢锛屽吋瀹�2003鍜�2007 + * 閫氳繃娴佽鍙朎xcel鏂囦欢 + * @return + * @throws Exception + */ + public static List<List<String>> getExcelDataCompatible(File file,boolean header) throws Exception { + try { + + String fileName = file.getName(); + if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) { + throw new TipsException("涓婁紶鏂囦欢鏍煎紡涓嶆纭�"); + } + + // 缁撴灉闆� + List<List<String>> list = new ArrayList<>(); + Workbook book = create(new BufferedInputStream(new FileInputStream(file))); + + // 閬嶅巻璇ヨ〃鏍间腑鎵�鏈夌殑宸ヤ綔琛紝i琛ㄧず宸ヤ綔琛ㄧ殑鏁伴噺 getNumberOfSheets琛ㄧず宸ヤ綔琛ㄧ殑鎬绘暟 + Sheet hssfsheet; + Row hssfrow; + List<String> arrayString; + Cell cell; + short format; + Date d; + DateFormat formater; + HSSFDataFormatter dataFormatter; + for(int s=0;s<book.getNumberOfSheets();s++) { + hssfsheet = book.getSheetAt(s); + int col = 0; + // 閬嶅巻璇ヨ鎵�鏈夌殑琛�,j琛ㄧず琛屾暟 getPhysicalNumberOfRows琛岀殑鎬绘暟 鍘婚櫎鏍囬 + for (int j = 0; j < hssfsheet.getPhysicalNumberOfRows(); j++) { + hssfrow = hssfsheet.getRow(j); + if(hssfrow!=null){ + if(j == 0) { + col = hssfrow.getPhysicalNumberOfCells(); + if(!header) { + //涓嶅寘鎷〃澶� + continue; + } + } + // 鍗曡鏁版嵁 + arrayString = new ArrayList<>(); + for (int i = 0; i < col; i++) { + cell = hssfrow.getCell(i); + if (cell == null) { + arrayString.add(""); + } else if (cell.getCellType() == CellType.NUMERIC) { + // arrayString[i] = new Double(cell.getNumericCellValue()).toString(); + if (CellType.NUMERIC == cell.getCellType()) { + format = cell.getCellStyle().getDataFormat(); + if(format == 14 || format == 31 || format == 57 || format == 58){ + //鏃ユ湡锛堜腑鏂囨椂闂存牸寮忕殑锛� + d = cell.getDateCellValue(); + formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + // DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + arrayString.add(formater.format(d)); + //arrayString[i] = formater.format(d); + }else if (HSSFDateUtil.isCellDateFormatted(cell)) { + d = cell.getDateCellValue(); + //DateFormat formater = new SimpleDateFormat("yyyy骞碝M鏈坉d鏃� HH鏃秏m鍒唖s绉�"); + formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + arrayString.add(formater.format(d)); + //arrayString[i] = formater.format(d); + } else { + if(CellType.STRING == cell.getCellType()){ + arrayString.add(cell.getStringCellValue()); + //arrayString[i] =cell.getStringCellValue(); + }else if(CellType.FORMULA==cell.getCellType()){ + arrayString.add(cell.getCellFormula()); + //arrayString[i] =cell.getCellFormula(); + }else if(CellType.NUMERIC== cell.getCellType()){ + dataFormatter = new HSSFDataFormatter(); + arrayString.add(dataFormatter.formatCellValue(cell)); + //arrayString[i] =dataFormatter.formatCellValue(cell); + } + } + } + } else if(cell.getCellType() == CellType.BLANK){ + arrayString.add(""); + //arrayString[i] = ""; + } else { // 濡傛灉EXCEL琛ㄦ牸涓殑鏁版嵁绫诲瀷涓哄瓧绗︿覆鍨� + arrayString.add(cell.getStringCellValue().trim()); + //arrayString[i] = cell.getStringCellValue().trim(); + } + } + list.add(arrayString); + } + } + } + return list; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /**璇诲彇excel鏂囦欢锛屽吋瀹�2003鍜�2007 + * 閫氳繃娴佽鍙朎xcel鏂囦欢 + * @return + * @throws Exception + */ + public static List<List<String>> getExcelDataCompatible(MultipartFile file,boolean header) throws Exception { + try { + + String fileName = file.getOriginalFilename(); + if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) { + throw new TipsException("涓婁紶鏂囦欢鏍煎紡涓嶆纭�"); + } + + // 缁撴灉闆� + List<List<String>> list = new ArrayList<>(); + Workbook book = create(new BufferedInputStream(file.getInputStream())); + + Sheet hssfsheet; + Row hssfrow; + List<String> arrayString; + Cell cell; + short format; + Date d; + DateFormat formater; + HSSFDataFormatter dataFormatter; + // 閬嶅巻璇ヨ〃鏍间腑鎵�鏈夌殑宸ヤ綔琛紝i琛ㄧず宸ヤ綔琛ㄧ殑鏁伴噺 getNumberOfSheets琛ㄧず宸ヤ綔琛ㄧ殑鎬绘暟 + for(int s=0;s<book.getNumberOfSheets();s++) { + hssfsheet = book.getSheetAt(s); + int col = 0; + // 閬嶅巻璇ヨ鎵�鏈夌殑琛�,j琛ㄧず琛屾暟 getPhysicalNumberOfRows琛岀殑鎬绘暟 鍘婚櫎鏍囬 + for (int j = 0; j < hssfsheet.getPhysicalNumberOfRows(); j++) { + hssfrow = hssfsheet.getRow(j); + if(hssfrow!=null){ + if(j == 0) { + col = hssfrow.getPhysicalNumberOfCells(); + if(!header) { + //涓嶅寘鎷〃澶� + continue; + } + } + // 鍗曡鏁版嵁 + arrayString = new ArrayList<>(); + for (int i = 0; i < col; i++) { + cell = hssfrow.getCell(i); + if (cell == null) { + arrayString.add(""); + } else if (cell.getCellType() == CellType.NUMERIC) { + // arrayString[i] = new Double(cell.getNumericCellValue()).toString(); + if (CellType.NUMERIC == cell.getCellType()) { + format = cell.getCellStyle().getDataFormat(); + if(format == 14 || format == 31 || format == 57 || format == 58){ + //鏃ユ湡锛堜腑鏂囨椂闂存牸寮忕殑锛� + d = cell.getDateCellValue(); + formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + // DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + arrayString.add(formater.format(d)); + //arrayString[i] = formater.format(d); + }else if (HSSFDateUtil.isCellDateFormatted(cell)) { + d = cell.getDateCellValue(); + //DateFormat formater = new SimpleDateFormat("yyyy骞碝M鏈坉d鏃� HH鏃秏m鍒唖s绉�"); + formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + arrayString.add(formater.format(d)); + //arrayString[i] = formater.format(d); + } else { + if(CellType.STRING == cell.getCellType()){ + arrayString.add(cell.getStringCellValue()); + //arrayString[i] =cell.getStringCellValue(); + }else if(CellType.FORMULA==cell.getCellType()){ + arrayString.add(cell.getCellFormula()); + //arrayString[i] =cell.getCellFormula(); + }else if(CellType.NUMERIC== cell.getCellType()){ + dataFormatter = new HSSFDataFormatter(); + arrayString.add(dataFormatter.formatCellValue(cell)); + //arrayString[i] =dataFormatter.formatCellValue(cell); + } + } + } + } else if(cell.getCellType() == CellType.BLANK){ + arrayString.add(""); + //arrayString[i] = ""; + } else { // 濡傛灉EXCEL琛ㄦ牸涓殑鏁版嵁绫诲瀷涓哄瓧绗︿覆鍨� + arrayString.add(cell.getStringCellValue().trim()); + //arrayString[i] = cell.getStringCellValue().trim(); + } + } + list.add(arrayString); + } + } + } + return list; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /**璇诲彇excel鏂囦欢锛屽吋瀹�2003鍜�2007 + * 閫氳繃娴佽鍙朎xcel鏂囦欢 + * @return + * @throws Exception + */ + public static List<List<String>> getExcelDataCompatible(InputStream inputStream,boolean header) throws Exception { + try { + // 缁撴灉闆� + List<List<String>> list = new ArrayList<>(); + Workbook book = create(new BufferedInputStream(inputStream)); + + Sheet hssfsheet; + Row hssfrow; + List<String> arrayString; + Cell cell; + short format; + Date d; + DateFormat formater; + HSSFDataFormatter dataFormatter; + // 閬嶅巻璇ヨ〃鏍间腑鎵�鏈夌殑宸ヤ綔琛紝i琛ㄧず宸ヤ綔琛ㄧ殑鏁伴噺 getNumberOfSheets琛ㄧず宸ヤ綔琛ㄧ殑鎬绘暟 + for(int s=0;s<book.getNumberOfSheets();s++) { + hssfsheet = book.getSheetAt(s); + int col = 0; + // 閬嶅巻璇ヨ鎵�鏈夌殑琛�,j琛ㄧず琛屾暟 getPhysicalNumberOfRows琛岀殑鎬绘暟 鍘婚櫎鏍囬 + for (int j = 0; j < hssfsheet.getPhysicalNumberOfRows(); j++) { + hssfrow = hssfsheet.getRow(j); + if(hssfrow!=null){ + if(j == 0) { + col = hssfrow.getPhysicalNumberOfCells(); + if(!header) { + //涓嶅寘鎷〃澶� + continue; + } + } + // 鍗曡鏁版嵁 + arrayString = new ArrayList<>(); + for (int i = 0; i < col; i++) { + cell = hssfrow.getCell(i); + if (cell == null) { + arrayString.add(""); + } else if (cell.getCellType() == CellType.NUMERIC) { + // arrayString[i] = new Double(cell.getNumericCellValue()).toString(); + if (CellType.NUMERIC == cell.getCellType()) { + format = cell.getCellStyle().getDataFormat(); + if(format == 14 || format == 31 || format == 57 || format == 58){ + //鏃ユ湡锛堜腑鏂囨椂闂存牸寮忕殑锛� + d = cell.getDateCellValue(); + formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + // DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + arrayString.add(formater.format(d)); + //arrayString[i] = formater.format(d); + }else if (HSSFDateUtil.isCellDateFormatted(cell)) { + d = cell.getDateCellValue(); + //DateFormat formater = new SimpleDateFormat("yyyy骞碝M鏈坉d鏃� HH鏃秏m鍒唖s绉�"); + formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + arrayString.add(formater.format(d)); + //arrayString[i] = formater.format(d); + } else { + if(CellType.STRING == cell.getCellType()){ + arrayString.add(cell.getStringCellValue()); + //arrayString[i] =cell.getStringCellValue(); + }else if(CellType.FORMULA==cell.getCellType()){ + arrayString.add(cell.getCellFormula()); + //arrayString[i] =cell.getCellFormula(); + }else if(CellType.NUMERIC== cell.getCellType()){ + dataFormatter = new HSSFDataFormatter(); + arrayString.add(dataFormatter.formatCellValue(cell)); + //arrayString[i] =dataFormatter.formatCellValue(cell); + } + } + } + } else if(cell.getCellType() == CellType.BLANK){ + arrayString.add(""); + //arrayString[i] = ""; + } else { // 濡傛灉EXCEL琛ㄦ牸涓殑鏁版嵁绫诲瀷涓哄瓧绗︿覆鍨� + arrayString.add(cell.getStringCellValue().trim()); + //arrayString[i] = cell.getStringCellValue().trim(); + } + } + list.add(arrayString); + } + } + } + return list; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** + * 鏂扮増璇诲彇Excel锛屽彧鏀寔2007浠ヤ笂鐗堟湰锛屼篃灏辨槸xslx鏍煎紡 + * 鏀寔澶ф暟鎹噺 + * @param file 鏂囦欢 + * @return 鏁版嵁 + */ + public static List<List<String>> readExcelData(File file){ + if(!isExcel(file)){ + throw new TipsException("璇蜂笂浼爀xcel鐨勬枃浠舵牸寮忥紒"); + } + List<List<String>> listData = new ArrayList<>(); + try{ + //rowCacheSize 缂撳瓨鍒板唴瀛樹腑鐨勮鏁�(榛樿鏄�10) + //bufferSize 璇诲彇璧勬簮鏃讹紝缂撳瓨鍒板唴瀛樼殑瀛楄妭澶у皬(榛樿鏄�1024) + //open InputStream鎴栬�匵LSX鏍煎紡鐨凢ile(蹇呴』) + Workbook book = StreamingReader.builder() + .rowCacheSize(100) + .bufferSize(10240) + .open(new FileInputStream(file)); + listData =readhandle(book); + }catch (OLE2NotOfficeXmlFileException ex){ + ex.printStackTrace(); + throw new RuntimeException("excel鐗堟湰涓嶄负2007鍙婁互涓�"); + } catch (Exception e){ + e.printStackTrace(); + throw new RuntimeException(e.getMessage()); + } + return listData; + } + + /** + * 鏂扮増璇诲彇Excel锛屽彧鏀寔2007浠ヤ笂鐗堟湰锛屼篃灏辨槸xslx鏍煎紡 + * 鏀寔澶ф暟鎹噺 + * @param file 鏂囦欢 + * @return 鏁版嵁 + */ + public static List<List<String>> readExcelData(MultipartFile file){ + if(!isExcel(file)){ + throw new TipsException("璇蜂笂浼爀xcel鐨勬枃浠舵牸寮忥紒"); + } + List<List<String>> listData = new ArrayList<>(); + try{ + //rowCacheSize 缂撳瓨鍒板唴瀛樹腑鐨勮鏁�(榛樿鏄�10) + //bufferSize 璇诲彇璧勬簮鏃讹紝缂撳瓨鍒板唴瀛樼殑瀛楄妭澶у皬(榛樿鏄�1024) + //open InputStream鎴栬�匵LSX鏍煎紡鐨凢ile(蹇呴』) + Workbook book = StreamingReader.builder() + .rowCacheSize(100) + .bufferSize(10240) + .open(new BufferedInputStream(file.getInputStream())); + + listData =readhandle(book); + }catch (OLE2NotOfficeXmlFileException ex){ + ex.printStackTrace(); + throw new RuntimeException("excel鐗堟湰涓嶄负2007鍙婁互涓�"); + } catch (Exception e){ + e.printStackTrace(); + throw new RuntimeException(e.getMessage()); + } + return listData; + } + + /** + * 鏂扮増璇诲彇Excel锛屽彧鏀寔2007浠ヤ笂鐗堟湰锛屼篃灏辨槸xslx鏍煎紡 + * 鏀寔澶ф暟鎹噺 + * @param file 鏂囦欢 + * @return 鏁版嵁 + */ + public static List<List<String>> readExcelData(InputStream file){ + List<List<String>> listData = new ArrayList<>(); + try{ + //rowCacheSize 缂撳瓨鍒板唴瀛樹腑鐨勮鏁�(榛樿鏄�10) + //bufferSize 璇诲彇璧勬簮鏃讹紝缂撳瓨鍒板唴瀛樼殑瀛楄妭澶у皬(榛樿鏄�1024) + //open InputStream鎴栬�匵LSX鏍煎紡鐨凢ile(蹇呴』) + Workbook book = StreamingReader.builder() + .rowCacheSize(100) + .bufferSize(10240) + .open(file); + + listData =readhandle(book); + }catch (OLE2NotOfficeXmlFileException ex){ + ex.printStackTrace(); + throw new RuntimeException("excel鐗堟湰涓嶄负2007鍙婁互涓�"); + }catch (Exception e){ + e.printStackTrace(); + throw new RuntimeException(e.getMessage()); + } + return listData; + } + + /**澶勭悊鏁版嵁*/ + public static List<List<String>> readhandle(Workbook book){ + List<List<String>> listData = new ArrayList<>(); + + //鏄惁瀛樺湪鏁版嵁 + boolean isData; + List<String> arrayString; + short format; + Date d; + DateFormat formater; + Sheet sheet; + Cell cell; + //閬嶅巻鎵�鏈夌殑sheet + for(int i=0;i<book.getNumberOfSheets();i++) { + sheet = book.getSheetAt(i); + //鍒楁暟 + Integer arrange = null; + //閬嶅巻鎵�鏈夌殑琛� + for (Row row : sheet) { + if(row == null){ + continue; + } + isData = false; + arrayString = new ArrayList<>(); + if(arrange == null){ + arrange = row.getPhysicalNumberOfCells(); + } + //閬嶅巻鎵�鏈夌殑鍒� + for (int j = 0;j<arrange;j++) { + cell = row.getCell(j); + if (cell == null) { + arrayString.add(""); + }else{ + if (cell.getCellType() == CellType.NUMERIC) { + isData = true; + format = cell.getCellStyle().getDataFormat(); + if (format == 14 || format == 31 || format == 57 || format == 58) { + //鏃ユ湡锛堜腑鏂囨椂闂存牸寮忕殑锛� + d = cell.getDateCellValue(); + formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + arrayString.add(formater.format(d)); + } else if (HSSFDateUtil.isCellDateFormatted(cell)) { + d = cell.getDateCellValue(); + formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + arrayString.add(formater.format(d)); + } else { + if (CellType.STRING == cell.getCellType()) { + arrayString.add(cell.getStringCellValue()); + } else if (CellType.FORMULA == cell.getCellType()) { + arrayString.add(cell.getCellFormula()); + } else { + arrayString.add(cell.getStringCellValue().trim()); + } + } + } else if (cell.getCellType() == CellType.BLANK) { + arrayString.add(""); + } else { // 濡傛灉EXCEL琛ㄦ牸涓殑鏁版嵁绫诲瀷涓哄瓧绗︿覆鍨� + isData = true; + arrayString.add(cell.getStringCellValue().trim()); + } + } + } + if (isData) { + listData.add(arrayString); + } + } + } + return listData; + } + + + /** + * p鍒ゆ柇鏄惁excel鏂囦欢 + * @param file + * @return + */ + public static boolean isExcel(MultipartFile file){ + return isExcel(file.getOriginalFilename()); + } + + + /** + * p鍒ゆ柇鏄惁excel鏂囦欢 + * @param file + * @return + */ + public static boolean isExcel(File file){ + return isExcel(file.getName()); + } + + + /**鍒ゆ柇鏂囦欢鏍煎紡鏄笉鏄痚xcel*/ + public static boolean isExcel(String fileName){ + if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) { + return false; + } + return true; + } + + public static File createExcelByImg(String[] headList, String[] fieldList, List<Map<String, Object>> dataList, Integer height, Integer width) throws Exception { + File file = File.createTempFile("temp", ".xls"); + FileOutputStream fileOut = null; + BufferedImage bufferImg = null; + + try { + ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream(); + if (height == null) { + height = 450; + } + + if (width == null) { + width = 1000; + } + + HSSFWorkbook workbook = new HSSFWorkbook(); + HSSFCellStyle boderStyle = workbook.createCellStyle(); + boderStyle.setVerticalAlignment(VerticalAlignment.CENTER); + boderStyle.setAlignment(HorizontalAlignment.CENTER); + HSSFSheet sheet = workbook.createSheet(); + HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); + HSSFRow row = sheet.createRow(0); + + HSSFCell anchor; + for(int i = 0; i < headList.length; ++i) { + row.setHeight(height.shortValue()); + sheet.setColumnWidth(i, width); + anchor = row.createCell(i); + anchor.setCellValue(headList[i]); + anchor.setCellStyle(boderStyle); + } + + HSSFRow row_value = null; + anchor = null; + HSSFCell cell = null; + if (dataList != null) { + for(int n = 0; n < dataList.size(); ++n) { + row_value = sheet.createRow(n + 1); + row_value.setHeight(height.shortValue()); + Map<String, Object> dataMap = (Map)dataList.get(n); + + for(int i = 0; i < fieldList.length; ++i) { + sheet.setColumnWidth(i, width); + cell = row_value.createCell(i); + Object value = dataMap.get(fieldList[i]); + if (value != null && "class java.io.File".equals(value.getClass().toString())) { + File file2 = (File)value; + if (file2 == null) { + cell.setCellValue(""); + } else { + bufferImg = ImageIO.read(file2); + ImageIO.write(bufferImg, "jpg", byteArrayOut); + HSSFClientAnchor anchor1 = new HSSFClientAnchor(0, 0, 1023, 255, (short)i, n + 1, (short)i, n + 1); + anchor1.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE); + patriarch.createPicture(anchor1, workbook.addPicture(byteArrayOut.toByteArray(), 5)); + } + } else { + cell.setCellValue(objToString(dataMap.get(fieldList[i]))); + cell.setCellStyle(boderStyle); + } + } + } + } + + FileOutputStream fOut = new FileOutputStream(file); + workbook.write(fOut); + fOut.flush(); + fOut.close(); + } catch (Exception var25) { + var25.printStackTrace(); + } finally { + file.deleteOnExit(); + } + + return file; + } + +} \ No newline at end of file diff --git a/hx_common/src/main/java/com/hx/util/FileConvertTool.java b/hx_common/src/main/java/com/hx/util/FileConvertTool.java new file mode 100644 index 0000000..da21ef8 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/FileConvertTool.java @@ -0,0 +1,351 @@ +package com.hx.util; + +import com.hx.exception.TipsException; +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; +import org.apache.commons.io.IOUtils; +import org.springframework.http.MediaType; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.multipart.commons.CommonsMultipartFile; +import sun.misc.BASE64Decoder; +import sun.misc.BASE64Encoder; + +import java.io.*; +import java.net.URL; +import java.net.URLConnection; +import java.util.Base64; + +/** + * 鏂囦欢杞崲宸ュ叿绫� + * @USER: fhx + * @DATE: 2022/3/2 + **/ +public class FileConvertTool { + + private static final int BUFFER_SIZE = 2 * 1024; + + + /** 鑾峰彇缃戠粶璺緞鏂囦欢娴� */ + public static InputStream getUrlFile(String urlPath) throws IOException { + if(StringUtils.isEmpty(urlPath)){ + return null; + } + // 鏋勯�燯RL + URL url = new URL(urlPath); + // 鎵撳紑杩炴帴 + URLConnection con = url.openConnection(); + //璁剧疆璇锋眰瓒呮椂涓�5s + con.setConnectTimeout(5*1000); + // 杈撳叆娴� + InputStream is = con.getInputStream(); + return is; + } + + /** + * 鑾峰彇鏂囦欢base64瀛楃涓� + * @param urlPath 鏂囦欢璺緞 + * @return 杩斿洖base64缂栫爜 + */ + public static String getFileBaseStrByUrl(String urlPath) throws IOException { + InputStream is = getUrlFile(urlPath); + byte[] bytes = IOUtils.toByteArray(is); + String encoded = Base64.getEncoder().encodeToString(bytes); + return encoded; + } + + // inputStream杞琽utputStream + public static ByteArrayOutputStream parse(final InputStream in) throws Exception { + final ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); + int ch; + while ((ch = in.read()) != -1) { + swapStream.write(ch); + } + return swapStream; + } + + // outputStream杞琲nputStream + public static ByteArrayInputStream parse(final OutputStream out) throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + baos = (ByteArrayOutputStream) out; + final ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray()); + return swapStream; + } + + // inputStream杞琒tring + public static String parse_String(final InputStream in) throws Exception { + final ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); + int ch; + while ((ch = in.read()) != -1) { + swapStream.write(ch); + } + return swapStream.toString(); + } + + // OutputStream 杞琒tring + public static String parse_String(final OutputStream out) throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + baos = (ByteArrayOutputStream) out; + final ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray()); + return swapStream.toString(); + } + + // String杞琲nputStream + public static ByteArrayInputStream parse_inputStream(final String in) throws Exception { + final ByteArrayInputStream input = new ByteArrayInputStream(in.getBytes()); + return input; + } + + // String 杞琽utputStream + public static ByteArrayOutputStream parse_outputStream(final String in) throws Exception { + return parse(parse_inputStream(in)); + } + + /** + * 鏍规嵁byte鏁扮粍锛岀敓鎴愭枃浠� + */ + public static File getFile(byte[] bfile, String filePath,String fileName) { + BufferedOutputStream bos = null; + FileOutputStream fos = null; + File file = null; + try { + File dir = new File(filePath); + if(!dir.exists()){//鍒ゆ柇鏂囦欢鐩綍鏄惁瀛樺湪 + dir.mkdirs(); + } + file = new File(filePath+"/"+fileName); + fos = new FileOutputStream(file); + bos = new BufferedOutputStream(fos); + bos.write(bfile); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (bos != null) { + try { + bos.close(); + } catch (IOException e1) { + e1.printStackTrace(); + } + } + if (fos != null) { + try { + fos.close(); + } catch (IOException e1) { + e1.printStackTrace(); + } + } + } + return file; + } + + /** + * 鏍规嵁byte鏁扮粍锛岀敓鎴愭枃浠� + */ + public static File getFile(InputStream in, String filePath, String fileName) { + if(in == null){ + return null; + } + BufferedOutputStream bos = null; + FileOutputStream fos = null; + File file = null; + try { + File dir = new File(filePath); + //鍒ゆ柇鏂囦欢鐩綍鏄惁瀛樺湪 + if(!dir.exists()){ + dir.mkdirs(); + } + file = new File(filePath+"/"+fileName); + fos = new FileOutputStream(file); + byte[] b = new byte[BUFFER_SIZE]; +// while ((in.read(b)) != -1) { +// fos.write(b); // 鍐欏叆鏁版嵁 +// } + int len; + while ((len = in.read(b)) != -1){ + fos.write(b, 0, len); + } + in.close(); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (bos != null) { + try { + bos.close(); + } catch (IOException e1) { + e1.printStackTrace(); + } + } + if (fos != null) { + try { + fos.close(); + } catch (IOException e1) { + e1.printStackTrace(); + } + } + } + return file; + } + + /** + * 鑾峰緱鎸囧畾鏂囦欢鐨刡yte鏁扮粍 + */ + private static byte[] getBytes(String filePath){ + byte[] buffer = null; + try { + File file = new File(filePath); + FileInputStream fis = new FileInputStream(file); + ByteArrayOutputStream bos = new ByteArrayOutputStream(1000); + byte[] b = new byte[1000]; + int n; + while ((n = fis.read(b)) != -1) { + bos.write(b, 0, n); + } + fis.close(); + bos.close(); + buffer = bos.toByteArray(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + return buffer; + } + + public static MultipartFile getMultipartFile(File file) { + FileItem item = new DiskFileItemFactory().createItem("file" + , MediaType.MULTIPART_FORM_DATA_VALUE + , true + , file.getName()); + try (InputStream input = new FileInputStream(file); + OutputStream os = item.getOutputStream()) { + // 娴佽浆绉� + IOUtils.copy(input, os); + } catch (Exception e) { + throw new IllegalArgumentException("Invalid file: " + e, e); + } + + return new CommonsMultipartFile(item); + } + + /** + * 鏍规嵁璺緞鍒犻櫎鎸囧畾鐨勭洰褰曟垨鏂囦欢锛屾棤璁哄瓨鍦ㄤ笌鍚� + *@param sPath 瑕佸垹闄ょ殑鐩綍鎴栨枃浠� + *@return 鍒犻櫎鎴愬姛杩斿洖 true锛屽惁鍒欒繑鍥� false銆� + */ + public static boolean deleteFolder(String sPath) { + File file = new File(sPath); + // 鍒ゆ柇鐩綍鎴栨枃浠舵槸鍚﹀瓨鍦� + if (!file.exists()) { + // 涓嶅瓨鍦ㄨ繑鍥� true + return true; + } else { + // 鍒ゆ柇鏄惁涓烘枃浠� + if (file.isFile()) { // 涓烘枃浠舵椂璋冪敤鍒犻櫎鏂囦欢鏂规硶 + return deleteFile(sPath); + } else { // 涓虹洰褰曟椂璋冪敤鍒犻櫎鐩綍鏂规硶 + return deleteDirectory(sPath); + } + } + } + + /** + * 鍒犻櫎鍗曚釜鏂囦欢 + * @param sPath 琚垹闄ゆ枃浠剁殑鏂囦欢鍚� + * @return 鍗曚釜鏂囦欢鍒犻櫎鎴愬姛杩斿洖true锛屽惁鍒欒繑鍥瀎alse + */ + public static boolean deleteFile(String sPath) { + File file = new File(sPath); + // 璺緞涓烘枃浠朵笖涓嶄负绌哄垯杩涜鍒犻櫎 + if (file.isFile() && file.exists()) { + file.delete(); + return true; + } + return false; + } + + /** + * 鍒犻櫎鍗曚釜鏂囦欢 + * @param file 琚垹闄ゆ枃浠� + * @return 鍗曚釜鏂囦欢鍒犻櫎鎴愬姛杩斿洖true锛屽惁鍒欒繑鍥瀎alse + */ + public static boolean deleteFile(File file) { + if(file == null){ + return true; + } + // 璺緞涓烘枃浠朵笖涓嶄负绌哄垯杩涜鍒犻櫎 + if (file.isFile() && file.exists()) { + file.delete(); + return true; + } + return false; + } + + /** + * 鍒犻櫎鐩綍锛堟枃浠跺す锛変互鍙婄洰褰曚笅鐨勬枃浠� + * @param sPath 琚垹闄ょ洰褰曠殑鏂囦欢璺緞 + * @return 鐩綍鍒犻櫎鎴愬姛杩斿洖true锛屽惁鍒欒繑鍥瀎alse + */ + public static boolean deleteDirectory(String sPath) { + //濡傛灉sPath涓嶄互鏂囦欢鍒嗛殧绗︾粨灏撅紝鑷姩娣诲姞鏂囦欢鍒嗛殧绗� + if (!sPath.endsWith(File.separator)) { + sPath = sPath + File.separator; + } + File dirFile = new File(sPath); + //濡傛灉dir瀵瑰簲鐨勬枃浠朵笉瀛樺湪锛屾垨鑰呬笉鏄竴涓洰褰曪紝鍒欓��鍑� + if (!dirFile.exists() || !dirFile.isDirectory()) { + return false; + } + boolean flag = true; + //鍒犻櫎鏂囦欢澶逛笅鐨勬墍鏈夋枃浠�(鍖呮嫭瀛愮洰褰�) + File[] files = dirFile.listFiles(); + for (int i = 0; i < files.length; i++) { + //鍒犻櫎瀛愭枃浠� + if (files[i].isFile()) { + flag = deleteFile(files[i].getAbsolutePath()); + if (!flag) break; + } //鍒犻櫎瀛愮洰褰� + else { + flag = deleteDirectory(files[i].getAbsolutePath()); + if (!flag) break; + } + } + if (!flag) return false; + //鍒犻櫎褰撳墠鐩綍 + if (dirFile.delete()) { + return true; + } else { + return false; + } + } + + public static String encodeBase64File(File file) throws Exception { + FileInputStream fileInputStream = new FileInputStream(file); + byte[] bytes = new byte[fileInputStream.available()]; + // 璇诲彇鍒� byte 閲岄潰 + fileInputStream.read(bytes); + fileInputStream.close(); + BASE64Encoder base64Encoder = new BASE64Encoder(); + // 寰楀埌鏂囦欢 涔嬪悗杞垚beye 鐒跺悗浣跨敤base64杞爜 + // 杞爜 + String encode = base64Encoder.encode(bytes); + return encode; + } + + public static String encodeBase64File(MultipartFile multipartFile) throws Exception { + if (multipartFile == null) { + throw new TipsException("鏈鏌ュ埌涓婁紶鐨勬枃浠讹紒"); + } + String imageBaseStr = null; + try { + String contentType = multipartFile.getContentType(); + byte[] imageBytes = multipartFile.getBytes(); + BASE64Encoder base64Encoder = new BASE64Encoder(); +// imageBaseStr = "data:" + contentType + ";base64," + base64Encoder.encode(imageBytes); + imageBaseStr = base64Encoder.encode(imageBytes); + imageBaseStr = imageBaseStr.replaceAll("[\\s*\t\n\r]", ""); + } catch (IOException e) { + throw new TipsException("鏂囦欢杞崲base64寮傚父"); + } + //杩斿洖鐢熸垚鐨勭紪鐮� + return imageBaseStr; + } +} diff --git a/hx_common/src/main/java/com/hx/util/FileUtil.java b/hx_common/src/main/java/com/hx/util/FileUtil.java new file mode 100644 index 0000000..69a7d41 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/FileUtil.java @@ -0,0 +1,94 @@ +package com.hx.util; + +import org.apache.commons.io.FileUtils; + +import java.io.*; +import java.net.URL; + +/** + * 鏂囦欢璇诲彇宸ュ叿绫� + * @author ChenJiaHe + * @Date 2020-06-17 + */ +public class FileUtil { + + /** + * @param pathUrl 缃戠粶璺緞 + * @return 鏂囦欢 + */ + public static File getUrlFile(String pathUrl){ + File temp = null; + try{ + URL url = new URL(pathUrl); + temp = File.createTempFile("temp", ".xls"); + FileUtils.copyURLToFile(url, temp); + temp.deleteOnExit(); + }catch (Exception e){ + throw new RuntimeException("閫氳繃URL鑾峰彇鏂囦欢鍑洪敊",e); + } + return temp; + } + + /** + * 璇诲彇鏂囦欢鍐呭锛屼綔涓哄瓧绗︿覆杩斿洖 + */ + public static String readFileAsString(String filePath) throws IOException { + File file = new File(filePath); + if (!file.exists()) { + throw new FileNotFoundException(filePath); + } + + if (file.length() > 1024 * 1024 * 1024) { + throw new IOException("File is too large"); + } + + StringBuilder sb = new StringBuilder((int) (file.length())); + // 鍒涘缓瀛楄妭杈撳叆娴� + FileInputStream fis = new FileInputStream(filePath); + // 鍒涘缓涓�涓暱搴︿负10240鐨凚uffer + byte[] bbuf = new byte[10240]; + // 鐢ㄤ簬淇濆瓨瀹為檯璇诲彇鐨勫瓧鑺傛暟 + int hasRead = 0; + while ( (hasRead = fis.read(bbuf)) > 0 ) { + sb.append(new String(bbuf, 0, hasRead)); + } + fis.close(); + return sb.toString(); + } + + /** + * 鏍规嵁鏂囦欢璺緞璇诲彇byte[] 鏁扮粍 + */ + public static byte[] readFileByBytes(String filePath) throws IOException { + File file = new File(filePath); + if (!file.exists()) { + throw new FileNotFoundException(filePath); + } else { + ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length()); + BufferedInputStream in = null; + + try { + in = new BufferedInputStream(new FileInputStream(file)); + short bufSize = 1024; + byte[] buffer = new byte[bufSize]; + int len1; + while (-1 != (len1 = in.read(buffer, 0, bufSize))) { + bos.write(buffer, 0, len1); + } + + byte[] var7 = bos.toByteArray(); + return var7; + } finally { + try { + if (in != null) { + in.close(); + } + } catch (IOException var14) { + var14.printStackTrace(); + } + + bos.close(); + } + } + } +} diff --git a/hx_common/src/main/java/com/hx/util/FileUtils.java b/hx_common/src/main/java/com/hx/util/FileUtils.java new file mode 100644 index 0000000..7da1769 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/FileUtils.java @@ -0,0 +1,666 @@ +package com.hx.util; + +import com.hx.exception.TipsException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.multipart.MultipartFile; + +import java.io.*; +import java.net.FileNameMap; +import java.net.URL; +import java.net.URLConnection; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.List; + +/** 鏂囦欢澶勭悊宸ュ叿 + * @author ChenJiaHe + * @Date 2020-06-17 + */ +public class FileUtils { + + private final static Logger logger = LoggerFactory.getLogger(FileUtils.class); + + private static int BUFFER_SIZE = 1024; + + /** + * @param path + * @MethodName fileIsExists + * @Description 鏂囦欢鏄惁瀛樺湪 + * @Author ChenJiaHe + * @Date 2019/9/7 9:13 + * @Since JDK 1.8 + */ + public static boolean fileIsExists(String path) { + File file = new File(path); + if (file.exists()) { + return true; + } else { + return false; + } + } + + /** + * @param sourceFile + * @param targetFile + * @MethodName copyFile + * @Description 澶嶅埗鏂囦欢 + * @Author ChenJiaHe + * @Date 2019/9/7 9:36 + * @Since JDK 1.8 + */ + public static void copyFile(File sourceFile, File targetFile) throws IOException { + BufferedInputStream inputStream = null; + BufferedOutputStream outputStream = null; + try { + inputStream = new BufferedInputStream(new FileInputStream(sourceFile)); + outputStream = new BufferedOutputStream(new FileOutputStream(targetFile)); + byte[] b = new byte[BUFFER_SIZE]; + int len; + while ((len = inputStream.read(b)) != -1) { + outputStream.write(b, 0, len); + } + outputStream.flush(); + } catch (Exception e) { + logger.error("copy file error", e); + } finally { + if (inputStream != null) { + inputStream.close(); + } + if (outputStream != null) { + outputStream.close(); + } + } + } + + /** + * @param path + * @param fileType 鏂囦欢绫诲瀷锛�0 = 鏂囦欢澶� 1 = 鏂囦欢 + * @MethodName getAllFiles + * @Description 璁�鍙栨枃浠跺す涓嬬殑锛屼笉鍖呮嫭瀛愭枃浠跺す鍐� + * @Author ChenJiaHe + * @Date 2019/9/17 15:56 + * @Since JDK 1.8 + */ + public static List<String> getAllFiles(String path, String fileType) { + List<String> fileList = new ArrayList<>(); + File fileDic = new File(path); + File[] files = fileDic.listFiles(); + for (File file : files) { + if ("1".equals(fileType)) { + if (file.isFile()) { + fileList.add(file.toString()); + } + } + if ("0".equals(fileType)) { + if (file.isDirectory()) { + fileList.add(file.toString()); + } + } + } + return fileList; + } + + /** + * @param path + * @MethodName getFolderFiles + * @Description 閫掑綊鑾峰彇鎵�鏈夊寘鎷瓙鏂囦欢澶圭殑鏂囦欢 + * @Author ChenJiaHe + * @Date 2019/9/17 16:11 + * @Since JDK 1.8 + */ + public static void getAllFileName(String path, List<String> listFileName) { + try { + File file = new File(path); + File[] files = file.listFiles(); + String[] names = file.list(); + if (names != null) { + String[] completNames = new String[names.length]; + for (int i = 0; i < names.length; i++) { + completNames[i] = path + names[i]; + } + listFileName.addAll(Arrays.asList(completNames)); + } + for (File a : files) { + // 濡傛灉鏂囦欢澶逛笅鏈夊瓙鏂囦欢澶癸紝鑾峰彇瀛愭枃浠跺す涓嬬殑鎵�鏈夋枃浠跺叏璺緞銆� + if (a.isDirectory()) { + getAllFileName(a.getAbsolutePath() + "\\", listFileName); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * 璇诲彇鏂囦欢鍐呭锛屼綔涓哄瓧绗︿覆杩斿洖 + */ + public static String readFileAsString(String filePath) throws IOException { + File file = new File(filePath); + if (!file.exists()) { + throw new FileNotFoundException(filePath); + } + + if (file.length() > 1024 * 1024 * 1024) { + throw new IOException("File is too large"); + } + + StringBuilder sb = new StringBuilder((int) (file.length())); + // 鍒涘缓瀛楄妭杈撳叆娴� + FileInputStream fis = new FileInputStream(filePath); + // 鍒涘缓涓�涓暱搴︿负10240鐨凚uffer + byte[] bbuf = new byte[10240]; + // 鐢ㄤ簬淇濆瓨瀹為檯璇诲彇鐨勫瓧鑺傛暟 + int hasRead = 0; + while ( (hasRead = fis.read(bbuf)) > 0 ) { + sb.append(new String(bbuf, 0, hasRead)); + } + fis.close(); + return sb.toString(); + } + + /** + * 鏍规嵁鏂囦欢璺緞璇诲彇byte[] 鏁扮粍 + */ + public static byte[] readFileByBytes(String filePath) throws IOException { + File file = new File(filePath); + if (!file.exists()) { + throw new FileNotFoundException(filePath); + } else { + ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length()); + BufferedInputStream in = null; + + try { + in = new BufferedInputStream(new FileInputStream(file)); + short bufSize = 1024; + byte[] buffer = new byte[bufSize]; + int len1; + while (-1 != (len1 = in.read(buffer, 0, bufSize))) { + bos.write(buffer, 0, len1); + } + + byte[] var7 = bos.toByteArray(); + return var7; + } finally { + try { + if (in != null) { + in.close(); + } + } catch (IOException var14) { + var14.printStackTrace(); + } + + bos.close(); + } + } + } + + + /** + * 2020-06-29 + * cjh + * 鍥剧墖鏍煎紡鍒ゆ柇 + * */ + public static boolean imageFormatJudge(MultipartFile firs) { + String imageName = firs.getOriginalFilename(); + //鎴彇鏍煎紡 + String suffix =imageName.substring(imageName.lastIndexOf(".") + 1); + //鏍煎紡瀛楁瘝杞皬鍐� + suffix = suffix.toLowerCase(); + //杩涜鍒ゆ柇 + if(suffix.equals("png")) { + return true; + }else if(suffix.equals("jpg")){ + return true; + }else if(suffix.equals("jpeg")){ + return true; + }else { + return false; + } + } + + /** + * 2020-06-29 + * cjh + * 鍥剧墖鏍煎紡鍒ゆ柇 + * */ + public static boolean imageFormatJudge(File firs) { + String imageName = firs.getName(); + //鎴彇鏍煎紡 + String suffix =imageName.substring(imageName.lastIndexOf(".") + 1); + //鏍煎紡瀛楁瘝杞皬鍐� + suffix = suffix.toLowerCase(); + //杩涜鍒ゆ柇 + if(suffix.equals("png")) { + return true; + }else if(suffix.equals("jpg")){ + return true; + }else if(suffix.equals("jpeg")){ + return true; + }else { + return false; + } + } + + /**瑙嗛涓婁紶鐨勬柟娉� + * 淇濆瓨鍒版湇鍔″櫒閲岄潰鐨� + * @param platformIconFile 瑙嗛鏂囦欢 + * @param unifiedFolder NG鎸囧悜鐨勫墠绔枃浠跺す(缁熶竴鏂囦欢澶�)锛屽锛歶ser/local/images/ + * @param saveFolder 淇濆瓨鍒扮殑鏂囦欢澶�,濡傦細/bananer/ + * @param autoDateFolder 鏄惁鐢熸垚鏃ユ湡鏂囦欢澶� + * @return 鍥剧墖璺緞 + * 2020-06-29 ChenJiaHe + */ + public static String videoFileUpload(MultipartFile platformIconFile,String unifiedFolder,String saveFolder + ,boolean autoDateFolder) { + String fileName = ""; + try { + if(platformIconFile == null) { + throw new TipsException("璇蜂笂浼犺棰戞枃浠讹紒"); + } + if(!getMimeType(platformIconFile.getOriginalFilename())){ + throw new TipsException("璇蜂笂浼犺棰戞牸寮忕殑鏂囦欢锛�"); + } + + //璁剧疆鍥剧墖澶у皬 + // String.format("%.1f",platformIconFile.getSize()/1024.0); + if(autoDateFolder){ + if(saveFolder.endsWith("/")){ + saveFolder = saveFolder+dateFormat(new Date(),"yyyyMM")+"/"; + }else{ + saveFolder = saveFolder+"/"+dateFormat(new Date(),"yyyyMM")+"/"; + } + } + fileName = dateFormat(new Date(),"yyyyMMddHHmmssSSS"); + if(unifiedFolder.endsWith("/")){ + if(saveFolder.startsWith("/")){ + saveFolder = saveFolder.replaceFirst("/",""); + unifiedFolder = unifiedFolder + saveFolder; + }else{ + unifiedFolder = unifiedFolder+saveFolder; + } + }else{ + if(saveFolder.startsWith("/")){ + unifiedFolder = unifiedFolder + saveFolder; + }else{ + unifiedFolder = unifiedFolder+"/"+saveFolder; + } + } + fileName = saveFolder+fileUp(platformIconFile,unifiedFolder,fileName); + } catch (RuntimeException e) { + e.printStackTrace(); + } + return fileName; + } + + /**鍥剧墖涓婁紶鐨勬柟娉� + * 淇濆瓨鍒版湇鍔″櫒閲岄潰鐨� + * @param platformIconFile 鍥剧墖鏂囦欢 + * @param unifiedFolder NG鎸囧悜鐨勫墠绔枃浠跺す(缁熶竴鏂囦欢澶�)锛屽锛歶ser/local/images/ + * @param saveFolder 淇濆瓨鍒扮殑鏂囦欢澶�,濡傦細/bananer/ + * @param autoDateFolder 鏄惁鐢熸垚鏃ユ湡鏂囦欢澶� + * @return 鍥剧墖璺緞 + * 2020-06-29 ChenJiaHe + */ + public static String handleFileUpload(File platformIconFile,String unifiedFolder,String saveFolder + ,boolean autoDateFolder) { + String fileName = ""; + try { + if(platformIconFile == null) { + throw new TipsException("璇蜂笂浼犲浘鐗囷紒"); + } + if(!imageFormatJudge(platformIconFile)) { + throw new TipsException("璇蜂笂浼爌ng銆乯pg鍜宩peg鏍煎紡鐨勫浘鐗囷紒"); + } + + //璁剧疆鍥剧墖澶у皬 + // String.format("%.1f",platformIconFile.getSize()/1024.0); + if(autoDateFolder){ + if(saveFolder.endsWith("/")){ + saveFolder = saveFolder+dateFormat(new Date(),"yyyyMM")+"/"; + }else{ + saveFolder = saveFolder+"/"+dateFormat(new Date(),"yyyyMM")+"/"; + } + } + fileName = dateFormat(new Date(),"yyyyMMddHHmmssSSS"); + if(unifiedFolder.endsWith("/")){ + if(saveFolder.startsWith("/")){ + saveFolder = saveFolder.replaceFirst("/",""); + unifiedFolder = unifiedFolder + saveFolder; + }else{ + unifiedFolder = unifiedFolder+saveFolder; + } + }else{ + if(saveFolder.startsWith("/")){ + unifiedFolder = unifiedFolder + saveFolder; + }else{ + unifiedFolder = unifiedFolder+"/"+saveFolder; + } + } + fileName = saveFolder+fileUp(platformIconFile,unifiedFolder,fileName); + } catch (RuntimeException e) { + e.printStackTrace(); + } + return fileName; + } + + /**鍥剧墖涓婁紶鐨勬柟娉� + * 淇濆瓨鍒版湇鍔″櫒閲岄潰鐨� + * @param platformIconFile 鍥剧墖鏂囦欢 + * @param unifiedFolder NG鎸囧悜鐨勫墠绔枃浠跺す(缁熶竴鏂囦欢澶�)锛屽锛歶ser/local/images/ + * @param saveFolder 淇濆瓨鍒扮殑鏂囦欢澶�,濡傦細/bananer/ + * @param autoDateFolder 鏄惁鐢熸垚鏃ユ湡鏂囦欢澶� + * @return 鍥剧墖璺緞 + * 2020-06-29 ChenJiaHe + */ + public static String handleFileUpload(MultipartFile platformIconFile,String unifiedFolder,String saveFolder + ,boolean autoDateFolder) { + String fileName = ""; + try { + if(platformIconFile == null) { + throw new TipsException("璇蜂笂浼犲浘鐗囷紒"); + } + if(!imageFormatJudge(platformIconFile)) { + throw new TipsException("璇蜂笂浼爌ng銆乯pg鍜宩peg鏍煎紡鐨勫浘鐗囷紒"); + } + + //璁剧疆鍥剧墖澶у皬 + // String.format("%.1f",platformIconFile.getSize()/1024.0); + if(autoDateFolder){ + if(saveFolder.endsWith("/")){ + saveFolder = saveFolder+dateFormat(new Date(),"yyyyMM")+"/"; + }else{ + saveFolder = saveFolder+"/"+dateFormat(new Date(),"yyyyMM")+"/"; + } + } + fileName = dateFormat(new Date(),"yyyyMMddHHmmssSSS"); + if(unifiedFolder.endsWith("/")){ + if(saveFolder.startsWith("/")){ + saveFolder = saveFolder.replaceFirst("/",""); + unifiedFolder = unifiedFolder + saveFolder; + }else{ + unifiedFolder = unifiedFolder+saveFolder; + } + }else{ + if(saveFolder.startsWith("/")){ + unifiedFolder = unifiedFolder + saveFolder; + }else{ + unifiedFolder = unifiedFolder+"/"+saveFolder; + } + } + fileName = saveFolder+fileUp(platformIconFile,unifiedFolder,fileName); + } catch (RuntimeException e) { + e.printStackTrace(); + } + return fileName; + } + + /** + * 闊抽涓婁紶 + * @param platformIconFile + * @param unifiedFolder + * @param saveFolder + * @param autoDateFolder + * @return + */ + public static String handleAudioUpload(MultipartFile platformIconFile,String unifiedFolder,String saveFolder + ,boolean autoDateFolder) { + String fileName = ""; + try { + if(platformIconFile == null) { + throw new TipsException("璇蜂笂浼犻煶棰戯紒"); + } + + if(autoDateFolder){ + if(saveFolder.endsWith("/")){ + saveFolder = saveFolder+dateFormat(new Date(),"yyyyMM")+"/"; + }else{ + saveFolder = saveFolder+"/"+dateFormat(new Date(),"yyyyMM")+"/"; + } + } + + fileName = dateFormat(new Date(),"yyyyMMddHHmmssSSS"); + if(unifiedFolder.endsWith("/")){ + if(saveFolder.startsWith("/")){ + saveFolder = saveFolder.replaceFirst("/",""); + unifiedFolder = unifiedFolder + saveFolder; + }else{ + unifiedFolder = unifiedFolder+saveFolder; + } + }else{ + if(saveFolder.startsWith("/")){ + unifiedFolder = unifiedFolder + saveFolder; + }else{ + unifiedFolder = unifiedFolder+"/"+saveFolder; + } + } + fileName = saveFolder+fileUp(platformIconFile,unifiedFolder,fileName); + } catch (RuntimeException e) { + e.printStackTrace(); + } + return fileName; + } + + /** + * 鏂囦欢涓婁紶 + * @param platformIconFile + * @param unifiedFolder + * @param saveFolder + * @param autoDateFolder + * @return + */ + public static String handleOtherFileUpload(MultipartFile platformIconFile,String unifiedFolder,String saveFolder + ,boolean autoDateFolder) { + String fileName = ""; + try { + if(platformIconFile == null) { + throw new TipsException("璇蜂笂浼犳枃浠讹紒"); + } + + if(autoDateFolder){ + if(saveFolder.endsWith("/")){ + saveFolder = saveFolder+dateFormat(new Date(),"yyyyMM")+"/"; + }else{ + saveFolder = saveFolder+"/"+dateFormat(new Date(),"yyyyMM")+"/"; + } + } + + fileName = dateFormat(new Date(),"yyyyMMddHHmmssSSS"); + if(unifiedFolder.endsWith("/")){ + if(saveFolder.startsWith("/")){ + saveFolder = saveFolder.replaceFirst("/",""); + unifiedFolder = unifiedFolder + saveFolder; + }else{ + unifiedFolder = unifiedFolder+saveFolder; + } + }else{ + if(saveFolder.startsWith("/")){ + unifiedFolder = unifiedFolder + saveFolder; + }else{ + unifiedFolder = unifiedFolder+"/"+saveFolder; + } + } + fileName = saveFolder+fileUp(platformIconFile,unifiedFolder,fileName); + } catch (RuntimeException e) { + e.printStackTrace(); + } + return fileName; + } + + /** + * 2020-06-29 ChenJiaHe + 聽聽 聽 * @param file 聽聽 聽聽聽 聽聽聽 聽//鏂囦欢瀵硅薄 + 聽聽 聽 * @param filePath聽聽 聽聽聽 聽//涓婁紶璺緞 + 聽聽 聽 * @param fileName聽聽 聽聽聽 聽//鏂囦欢鍚� + 聽聽 聽 * @return聽 鏂囦欢鍚� + 聽聽 聽 */ + public static String fileUp(MultipartFile file, String filePath, String fileName){ + String extName = ""; // 鎵╁睍鍚嶆牸寮忥細 + try { + if (file.getOriginalFilename().lastIndexOf(".") >= 0){ + extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); + } + copyFile(file.getInputStream(), filePath, fileName+extName).replaceAll("-", ""); + } catch (IOException e) { + System.out.println(e); + } + return fileName+extName; + } + + + /** + * 2020-06-29 ChenJiaHe + 聽聽 聽 * @param file 聽聽 聽聽聽 聽聽聽 聽//鏂囦欢瀵硅薄 + 聽聽 聽 * @param filePath聽聽 聽聽聽 聽//涓婁紶璺緞 + 聽聽 聽 * @param fileName聽聽 聽聽聽 聽//鏂囦欢鍚� + 聽聽 聽 * @return聽 鏂囦欢鍚� + 聽聽 聽 */ + public static String fileUp(File file, String filePath, String fileName){ + String extName = ""; // 鎵╁睍鍚嶆牸寮忥細 + try { + if (file.getName().lastIndexOf(".") >= 0){ + extName = file.getName().substring(file.getName().lastIndexOf(".")); + } + copyFile(file, filePath, fileName+extName).replaceAll("-", ""); + } catch (IOException e) { + System.out.println(e); + } + return fileName+extName; + } + + /** + 聽聽 聽 * 鍐欐枃浠跺埌褰撳墠鐩綍鐨剈pload鐩綍涓� + 聽聽 聽 * + 聽聽 聽 * @param in + 聽聽 聽 * @param fileName + 聽聽 聽 * @throws IOException + 聽聽 聽 */ + private static String copyFile(InputStream in, String dir, String realName)throws IOException { + File file = new File(dir, realName); + file.setWritable(true); + if (!file.exists()) { + if (!file.getParentFile().exists()) { + file.getParentFile().mkdirs(); + } + file.createNewFile(); + } + org.apache.commons.io.FileUtils.copyInputStreamToFile(in, file); + return realName; + } + + /** + 聽聽 聽 * 鍐欐枃浠跺埌褰撳墠鐩綍鐨剈pload鐩綍涓� + 聽聽 聽 * + 聽聽 聽 * @param in + 聽聽 聽 * @param fileName + 聽聽 聽 * @throws IOException + 聽聽 聽 */ + private static String copyFile(File fileIn, String dir, String realName)throws IOException { + File file = new File(dir, realName); + file.setWritable(true); + if (!file.exists()) { + if (!file.getParentFile().exists()) { + file.getParentFile().mkdirs(); + } + file.createNewFile(); + } + org.apache.commons.io.FileUtils.copyFile(fileIn,file); + return realName; + } + + /** + * + * @param date 鏃堕棿 + * @param format 鏃堕棿鏍煎紡 + * @return 杩斿洖鐨勬椂闂存牸寮忓瓧绗︿覆 + */ + public static String dateFormat(Date date,String format) { + SimpleDateFormat df = new SimpleDateFormat(format);//璁剧疆鏃ユ湡鏍煎紡 + return df.format(date); + } + + + /** + * @param stream 鏂囦欢娴� + * @param saveUrl 淇濆瓨鍒扮殑鏂囦欢澶� + * @param fileName 鏂囦欢鍥剧墖 + * @return + * @throws IOException + */ + public static File inputStreamToFile(InputStream stream,String saveUrl,String fileName) throws IOException { + if(saveUrl.endsWith("/")){ + saveUrl = saveUrl + fileName; + }else{ + saveUrl = saveUrl +"/"+ fileName; + } + File targetFile = new File(saveUrl); + org.apache.commons.io.FileUtils.copyInputStreamToFile(stream, targetFile); + return targetFile; + } + + /**鍒ゆ柇鏄笉鏄棰戞枃浠� + * @param fileName 鏂囦欢鍚嶇О + * @return boolean true鏄棰戞枃浠� + */ + public static boolean getMimeType(String fileName) { + boolean b = false; + FileNameMap fileNameMap = URLConnection.getFileNameMap(); + String type = fileNameMap.getContentTypeFor(fileName); + //鏄棰憈ype鏄负绌虹殑 + if(StringUtils.isEmpty(type)) { + b = true; + } + return b; + } + + /** + * 鍒ゆ柇鏄惁涓鸿棰� + * @param fileName + * @return + */ + public static String isVideo(String fileName) { + FileNameMap fileNameMap = URLConnection.getFileNameMap(); + String type = fileNameMap.getContentTypeFor(fileName); + return type; + } + + public static File httpUrlFile(String netUrl) throws IOException { + File file = File.createTempFile("temp123", ".xls"); + InputStream inStream = null; + FileOutputStream os = null; + + try { + file = File.createTempFile("net_url", ".jpg"); + URL urlfile = new URL(netUrl); + inStream = urlfile.openStream(); + os = new FileOutputStream(file); + + byte[] buffer = new byte[8192]; + + int bytesRead; + while((bytesRead = inStream.read(buffer, 0, 8192)) != -1) { + os.write(buffer, 0, bytesRead); + } + } catch (Exception var15) { + var15.printStackTrace(); + } finally { + try { + if (null != os) { + os.close(); + } + + if (null != inStream) { + inStream.close(); + } + } catch (Exception var14) { + var14.printStackTrace(); + } + + } + + return file; + } + +} diff --git a/hx_common/src/main/java/com/hx/util/GsonUtils.java b/hx_common/src/main/java/com/hx/util/GsonUtils.java new file mode 100644 index 0000000..3d725b4 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/GsonUtils.java @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2017 Baidu, Inc. All Rights Reserved. + */ +package com.hx.util; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; + +import java.lang.reflect.Type; + +/** + * Json宸ュ叿绫�. + */ +public class GsonUtils { + private static Gson gson = new GsonBuilder().create(); + + public static String toJson(Object value) { + return gson.toJson(value); + } + + public static <T> T fromJson(String json, Class<T> classOfT) throws JsonParseException { + return gson.fromJson(json, classOfT); + } + + public static <T> T fromJson(String json, Type typeOfT) throws JsonParseException { + return (T) gson.fromJson(json, typeOfT); + } +} diff --git a/hx_common/src/main/java/com/hx/util/HttpMethodUtil.java b/hx_common/src/main/java/com/hx/util/HttpMethodUtil.java new file mode 100644 index 0000000..8bdd6a3 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/HttpMethodUtil.java @@ -0,0 +1,151 @@ +package com.hx.util; + +import com.alibaba.fastjson.JSONObject; +import org.apache.commons.io.IOUtils; + +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; + +/** + * http 宸ュ叿绫� + */ +public class HttpMethodUtil { + + /** 璇锋眰http鍗忚 鑾峰彇淇℃伅宸ュ叿 + * @param url 璇锋眰閾炬帴 + * @param data 璇锋眰鏁版嵁(body) + * @param keyValues form琛ㄥ崟鏁版嵁 key鍙傛暟鍚嶇О锛寁alue鍙傛暟鍊� + * @param header 璇锋眰澶� + * @param requestMethod 璇锋眰澶存柟娉曪紝榛樿POST + * @return + */ + public static String HttpURLUtilJson(String url, String data,Map<String,Object> keyValues,Map<String,String> header,String requestMethod) { + HttpURLConnection con = null; + URL u = null; + String wxMsgXml = null; + try { + StringBuilder dataP = new StringBuilder(); + if (keyValues != null && !keyValues.isEmpty()) { + for (Map.Entry<String, Object> entry : keyValues.entrySet()) { + dataP.append((String)entry.getKey()).append("="); + dataP.append(entry.getValue()); + dataP.append("&"); + } + System.out.println("dataP:"+dataP.toString()); + dataP.deleteCharAt(dataP.length() - 1); + url = url+"?"+dataP; + } + + if(StringUtils.isEmpty(requestMethod)){ + requestMethod = "POST"; + } + u = new URL(url); + con = (HttpURLConnection) u.openConnection(); + con.setRequestMethod(requestMethod); + con.setDoOutput(true); + con.setDoInput(true); + con.setUseCaches(false); + con.setReadTimeout(300000); + con.setRequestProperty("Charset", "UTF-8"); + con.setRequestProperty("Content-Type", "application/json"); + if(header != null){ + for (Map.Entry<String, String> entry : header.entrySet()) { + con.setRequestProperty(entry.getKey(),entry.getValue()); + } + } + + if (data != null) { + OutputStream os = con.getOutputStream(); + os.write(data.getBytes("utf-8")); + } + + if(HttpURLConnection.HTTP_OK != con.getResponseCode() && HttpURLConnection.HTTP_CREATED != con.getResponseCode()){ + throw new RuntimeException("璇锋眰url澶辫触:"+con.getResponseCode()); + } + // 璇诲彇杩斿洖鍐呭 + wxMsgXml = IOUtils.toString(con.getInputStream(), "utf-8"); + // //System.out.println("HttpURLUtil:"+wxMsgXml); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (con != null) { + con.disconnect(); + } + } + return wxMsgXml; + } + + /** + * 璇锋眰http鍗忚 鑾峰彇淇℃伅宸ュ叿 + * @param url 璇锋眰閾炬帴 + * @param data 璇锋眰鏁版嵁(body) + * @param keyValues form琛ㄥ崟鏁版嵁 key鍙傛暟鍚嶇О锛寁alue鍙傛暟鍊� + * @param header 璇锋眰澶� + * @param requestMethod 璇锋眰澶存柟娉曪紝榛樿POST + * @return + */ + public static String request(String url, String data,Map<String,Object> keyValues,Map<String,String> header,String requestMethod, String contentType) { + HttpURLConnection con = null; + URL u = null; + String wxMsgXml = null; + try { + StringBuilder dataP = new StringBuilder(); + if (keyValues != null && !keyValues.isEmpty()) { + for (Map.Entry<String, Object> entry : keyValues.entrySet()) { + dataP.append((String)entry.getKey()).append("="); + dataP.append(entry.getValue()); + dataP.append("&"); + } + System.out.println("dataP:"+dataP.toString()); + dataP.deleteCharAt(dataP.length() - 1); + url = url+"?"+dataP; + } + + if(StringUtils.isEmpty(requestMethod)){ + requestMethod = "POST"; + } + + if(StringUtils.isEmpty(contentType)){ + contentType = "application/json"; + } + + u = new URL(url); + con = (HttpURLConnection) u.openConnection(); + con.setRequestMethod(requestMethod); + con.setDoOutput(true); + con.setDoInput(true); + con.setUseCaches(false); + con.setReadTimeout(300000); + con.setRequestProperty("Charset", "UTF-8"); + con.setRequestProperty("Content-Type", contentType); + if(header != null){ + for (Map.Entry<String, String> entry : header.entrySet()) { + con.setRequestProperty(entry.getKey(),entry.getValue()); + } + } + + if (data != null) { + OutputStream os = con.getOutputStream(); + os.write(data.getBytes("utf-8")); + } + + if(HttpURLConnection.HTTP_OK != con.getResponseCode() && HttpURLConnection.HTTP_CREATED != con.getResponseCode()){ + throw new RuntimeException("璇锋眰url澶辫触:"+con.getResponseCode()); + } + // 璇诲彇杩斿洖鍐呭 + wxMsgXml = IOUtils.toString(con.getInputStream(), "utf-8"); + // //System.out.println("HttpURLUtil:"+wxMsgXml); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (con != null) { + con.disconnect(); + } + } + return wxMsgXml; + } + +} diff --git a/hx_common/src/main/java/com/hx/util/HttpResponse.java b/hx_common/src/main/java/com/hx/util/HttpResponse.java new file mode 100644 index 0000000..3edd3c2 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/HttpResponse.java @@ -0,0 +1,32 @@ +package com.hx.util; + +public class HttpResponse { + private int code; + private String content; + + public HttpResponse(int status, String content) { + this.code = status; + this.content = content; + } + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + + public String toString(){ + return new StringBuilder("[ code = ").append(code) + .append(" , content = ").append(content).append(" ]").toString(); + } +} diff --git a/hx_common/src/main/java/com/hx/util/HttpServletRequestUtil.java b/hx_common/src/main/java/com/hx/util/HttpServletRequestUtil.java new file mode 100644 index 0000000..ded443f --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/HttpServletRequestUtil.java @@ -0,0 +1,53 @@ +package com.hx.util; + +import org.apache.commons.io.IOUtils; + +import javax.servlet.http.HttpServletRequest; +import java.io.BufferedReader; +import java.io.IOException; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; + +/** HttpServletRequestUtil 鑾峰彇璇锋眰涓殑body + * @author wangrenhuang + * @Date 2021-10-19 + */ +public class HttpServletRequestUtil { + + /** + * 鑾峰彇bady + * */ + public static String getBody(HttpServletRequest request) { + String wxMsgXml = null; + if(request == null){ + return wxMsgXml; + } + try{ + wxMsgXml = IOUtils.toString(request.getInputStream(), + "utf-8"); + return wxMsgXml; + }catch (Exception e){ + wxMsgXml = null; + } + return wxMsgXml; + } + + + /** + * + * 鑾峰彇璇锋眰澶� + * */ + public static Map<String,String> getHeader(HttpServletRequest request) { + Enumeration<String> enumeration = request.getHeaderNames(); + Map<String,String> map = new HashMap<>(16); + StringBuffer headers = new StringBuffer(); + while (enumeration.hasMoreElements()) { + String name = enumeration.nextElement(); + String value = request.getHeader(name); + map.put(name,value); + } + + return map; + } +} diff --git a/hx_common/src/main/java/com/hx/util/HttpUtil.java b/hx_common/src/main/java/com/hx/util/HttpUtil.java new file mode 100644 index 0000000..64b77f6 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/HttpUtil.java @@ -0,0 +1,658 @@ +package com.hx.util; + +import net.sf.json.JSONException; +import net.sf.json.JSONObject; +import org.apache.commons.io.IOUtils; +import org.bouncycastle.util.encoders.UTF8; +import org.springframework.web.multipart.MultipartFile; + +import javax.activation.MimetypesFileTypeMap; +import javax.servlet.ServletInputStream; +import javax.servlet.http.HttpServletRequest; +import java.io.*; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.Charset; +import java.nio.charset.CharsetEncoder; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +/** + * http 宸ュ叿绫� + */ +public class HttpUtil { + + /**multipart/form-data 鏍煎紡鍙戦�佹暟鎹椂鍚勪釜閮ㄥ垎鍒嗛殧绗︾殑鍓嶇紑,蹇呴』涓� --*/ + private static final String BOUNDARY_PREFIX = "--"; + /**鍥炶溅鎹㈣,鐢ㄤ簬涓�琛岀殑缁撳熬*/ + private static final String LINE_END = "\r\n"; + + public static String getInputStream(HttpServletRequest request) throws Exception { + ServletInputStream stream = null; + BufferedReader reader = null; + StringBuffer sb = new StringBuffer(); + try { + stream = request.getInputStream(); + // 鑾峰彇鍝嶅簲 + reader = new BufferedReader(new InputStreamReader(stream)); + String line; + while ((line = reader.readLine()) != null) { + sb.append(line); + } + } catch (IOException e) { + //logger.error(e); + throw new RuntimeException("璇诲彇杩斿洖鏀粯鎺ュ彛鏁版嵁娴佸嚭鐜板紓甯革紒"); + } finally { + reader.close(); + } + //logger.info("杈撳叆娴佽繑鍥炵殑鍐呭锛�" + sb.toString()); + return sb.toString(); + } + + public static String post(String requestUrl, String accessToken, String params) + throws Exception { + String contentType = "application/x-www-form-urlencoded"; + return HttpUtil.post(requestUrl, accessToken, contentType, params); + } + + public static String post(String requestUrl, String accessToken, String contentType, String params) + throws Exception { + String encoding = "UTF-8"; + if (requestUrl.contains("nlp")) { + encoding = "GBK"; + } + return HttpUtil.post(requestUrl, accessToken, contentType, params, encoding); + } + + public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding) + throws Exception { + String url = requestUrl + "?access_token=" + accessToken; + return HttpUtil.postGeneralUrl(url, contentType, params, encoding); + } + + public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding) + throws Exception { + URL url = new URL(generalUrl); + // 鎵撳紑鍜孶RL涔嬮棿鐨勮繛鎺� + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("POST"); + // 璁剧疆閫氱敤鐨勮姹傚睘鎬� + connection.setRequestProperty("Content-Type", contentType); + connection.setRequestProperty("Connection", "Keep-Alive"); + connection.setUseCaches(false); + connection.setDoOutput(true); + connection.setDoInput(true); + + // 寰楀埌璇锋眰鐨勮緭鍑烘祦瀵硅薄 + DataOutputStream out = new DataOutputStream(connection.getOutputStream()); + out.write(params.getBytes(encoding)); + out.flush(); + out.close(); + + // 寤虹珛瀹為檯鐨勮繛鎺� + connection.connect(); + // 鑾峰彇鎵�鏈夊搷搴斿ご瀛楁 + Map<String, List<String>> headers = connection.getHeaderFields(); + // 閬嶅巻鎵�鏈夌殑鍝嶅簲澶村瓧娈� + for (String key : headers.keySet()) { + System.err.println(key + "--->" + headers.get(key)); + } + // 瀹氫箟 BufferedReader杈撳叆娴佹潵璇诲彇URL鐨勫搷搴� + BufferedReader in = null; + in = new BufferedReader( + new InputStreamReader(connection.getInputStream(), encoding)); + String result = ""; + String getLine; + while ((getLine = in.readLine()) != null) { + result += getLine; + } + in.close(); + System.err.println("result:" + result); + return result; + } + + /** + * 甯eader鐨刾ost璇锋眰 + * @param generalUrl + * @param header + * @param params + * @return + * @throws Exception + */ + public static String post(String generalUrl, Map<String, String> header, String params) + throws Exception { + URL url = new URL(generalUrl); + // 鎵撳紑鍜孶RL涔嬮棿鐨勮繛鎺� + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("POST"); + // 璁剧疆閫氱敤鐨勮姹傚睘鎬� + connection.setRequestProperty("Connection", "Keep-Alive"); + if(header != null) + { + for(String key : header.keySet()) + { + connection.setRequestProperty(key, header.get(key)); + } + } + + connection.setUseCaches(false); + connection.setDoOutput(true); + connection.setDoInput(true); + + // 寰楀埌璇锋眰鐨勮緭鍑烘祦瀵硅薄 + DataOutputStream out = new DataOutputStream(connection.getOutputStream()); + out.write(params.getBytes("UTF-8")); + out.flush(); + out.close(); + + // 寤虹珛瀹為檯鐨勮繛鎺� + connection.connect(); + // 瀹氫箟 BufferedReader杈撳叆娴佹潵璇诲彇URL鐨勫搷搴� + BufferedReader in = null; + in = new BufferedReader( + new InputStreamReader(connection.getInputStream(), "UTF-8")); + String result = ""; + String getLine; + while ((getLine = in.readLine()) != null) { + result += getLine; + } + in.close(); + + return result; + } + + /** + * 甯eader鐨刧et璇锋眰 + * @param generalUrl + * @param header + * @return + * @throws Exception + */ + public static String get(String generalUrl, Map<String, String> header) + throws Exception { + URL url = new URL(generalUrl); + // 鎵撳紑鍜孶RL涔嬮棿鐨勮繛鎺� + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("GET"); + // 璁剧疆閫氱敤鐨勮姹傚睘鎬� + connection.setRequestProperty("Connection", "Keep-Alive"); + if(header != null) + { + for(String key : header.keySet()) + { + connection.setRequestProperty(key, header.get(key)); + } + } + + connection.setUseCaches(false); + connection.setDoOutput(true); + connection.setDoInput(true); + + // 寤虹珛瀹為檯鐨勮繛鎺� + connection.connect(); + // 瀹氫箟 BufferedReader杈撳叆娴佹潵璇诲彇URL鐨勫搷搴� + BufferedReader in = null; + in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); + String result = ""; + String getLine; + while ((getLine = in.readLine()) != null) { + result += getLine; + } + in.close(); + + return result; + } + + /** 璇锋眰http鍗忚 鑾峰彇淇℃伅宸ュ叿 **/ + public static JSONObject HttpURLUtil(String url, String data) { + HttpURLConnection con = null; + URL u = null; + String wxMsgXml = null; + JSONObject obj = null; + try { + u = new URL(url); + con = (HttpURLConnection) u.openConnection(); + con.setRequestMethod("POST"); + con.setDoOutput(true); + con.setDoInput(true); + con.setUseCaches(false); + con.setReadTimeout(5000); + con.setRequestProperty("Charset", "UTF-8"); + con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); + + if (data != null) { + OutputStream os = con.getOutputStream(); + os.write(data.getBytes("utf-8")); + } + + if (con.getResponseCode() != 200) + throw new RuntimeException("璇锋眰url澶辫触"); + // 璇诲彇杩斿洖鍐呭 + wxMsgXml = IOUtils.toString(con.getInputStream(), "utf-8"); + obj = JSONObject.fromObject(wxMsgXml); + // //System.out.println("HttpURLUtil:"+wxMsgXml); + } catch (Exception e) { + e.printStackTrace(); + obj = new JSONObject(); + try { + obj.put("status", 1); + obj.put("errMsg", e.getMessage()); + } catch (JSONException e1) { + e1.printStackTrace(); + } + } finally { + if (con != null) { + con.disconnect(); + } + } + return obj; + } + + + /** 璇锋眰http鍗忚 鑾峰彇淇℃伅宸ュ叿 **/ + public static JSONObject HttpURLUtilJson(String url, String data) { + HttpURLConnection con = null; + URL u = null; + String wxMsgXml = null; + JSONObject obj = null; + try { + u = new URL(url); + con = (HttpURLConnection) u.openConnection(); + con.setRequestMethod("POST"); + con.setDoOutput(true); + con.setDoInput(true); + con.setUseCaches(false); + con.setReadTimeout(5000); + con.setRequestProperty("Charset", "UTF-8"); + con.setRequestProperty("Content-Type", "application/json"); + + if (data != null) { + OutputStream os = con.getOutputStream(); + os.write(data.getBytes("utf-8")); + } + + if (con.getResponseCode() != 200) + throw new RuntimeException("璇锋眰url澶辫触"); + // 璇诲彇杩斿洖鍐呭 + wxMsgXml = IOUtils.toString(con.getInputStream(), "utf-8"); + obj = JSONObject.fromObject(wxMsgXml); + // //System.out.println("HttpURLUtil:"+wxMsgXml); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (con != null) { + con.disconnect(); + } + } + return obj; + } + + /** + * post 璇锋眰锛氫互琛ㄥ崟鏂瑰紡鎻愪氦鏁版嵁 + * <p> + * 鐢变簬 multipart/form-data 涓嶆槸 http 鏍囧噯鍐呭锛岃�屾槸灞炰簬鎵╁睍绫诲瀷锛� + * 鍥犳闇�瑕佽嚜宸辨瀯閫犳暟鎹粨鏋勶紝鍏蜂綋濡備笅锛� + * <p> + * 1銆侀鍏堬紝璁剧疆 Content-Type + * <p> + * Content-Type: multipart/form-data; boundary=${bound} + * <p> + * 鍏朵腑${bound} 鏄竴涓崰浣嶇锛屼唬琛ㄦ垜浠瀹氱殑鍒嗗壊绗︼紝鍙互鑷繁浠绘剰瑙勫畾锛� + * 浣嗕负浜嗛伩鍏嶅拰姝e父鏂囨湰閲嶅浜嗭紝灏介噺瑕佷娇鐢ㄥ鏉備竴鐐圭殑鍐呭 + * <p> + * 2銆佽缃富浣撳唴瀹� + * <p> + * --${bound} + * Content-Disposition: form-data; name="userName" + * <p> + * Andy + * --${bound} + * Content-Disposition: form-data; name="file"; filename="娴嬭瘯.excel" + * Content-Type: application/octet-stream + * <p> + * 鏂囦欢鍐呭 + * --${bound}-- + * <p> + * 鍏朵腑${bound}鏄箣鍓嶅ご淇℃伅涓殑鍒嗛殧绗︼紝濡傛灉澶翠俊鎭腑瑙勫畾鏄�123锛岄偅杩欓噷涔熻鏄�123锛� + * 鍙互寰堝鏄撶湅鍒帮紝杩欎釜璇锋眰鎻愭槸澶氫釜鐩稿悓閮ㄥ垎缁勬垚鐨勶細 + * 姣忎竴閮ㄥ垎閮芥槸浠�--鍔犲垎闅旂寮�濮嬬殑锛岀劧鍚庢槸璇ラ儴鍒嗗唴瀹圭殑鎻忚堪淇℃伅锛岀劧鍚庝竴涓洖杞︽崲琛岋紝鐒跺悗鏄弿杩颁俊鎭殑鍏蜂綋鍐呭锛� + * 濡傛灉浼犻�佺殑鍐呭鏄竴涓枃浠剁殑璇濓紝閭d箞杩樹細鍖呭惈鏂囦欢鍚嶄俊鎭互鍙婃枃浠跺唴瀹圭被鍨嬨�� + * 涓婇潰绗簩閮ㄥ垎鏄竴涓枃浠朵綋鐨勭粨鏋勶紝鏈�鍚庝互--鍒嗛殧绗�--缁撳熬锛岃〃绀鸿姹備綋缁撴潫 + * + * @param urlStr 璇锋眰鐨剈rl + * @param filePathMap key 鍙傛暟鍚嶏紝value 鏂囦欢鐨勮矾寰� + * @param keyValues 鏅�氬弬鏁扮殑閿�煎 + * @param headers + * @return + * @throws IOException + */ + public static HttpResponse postFormData(String urlStr, Map<String, String> filePathMap, Map<String, Object> keyValues, Map<String, Object> headers) throws IOException { + HttpResponse response; + HttpURLConnection conn = getHttpURLConnection(urlStr, headers); + //鍒嗛殧绗︼紝鍙互浠绘剰璁剧疆锛岃繖閲岃缃负 MyBoundary+ 鏃堕棿鎴筹紙灏介噺澶嶆潅鐐癸紝閬垮厤鍜屾鏂囬噸澶嶏級 + String boundary = "MyBoundary" + System.currentTimeMillis(); + //璁剧疆 Content-Type 涓� multipart/form-data; boundary=${boundary} + conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); + + //鍙戦�佸弬鏁版暟鎹� + try (DataOutputStream out = new DataOutputStream(conn.getOutputStream())) { + //鍙戦�佹櫘閫氬弬鏁� + if (keyValues != null && !keyValues.isEmpty()) { + for (Map.Entry<String, Object> entry : keyValues.entrySet()) { + writeSimpleFormField(boundary, out, entry); + } + } + //鍙戦�佹枃浠剁被鍨嬪弬鏁� + if (filePathMap != null && !filePathMap.isEmpty()) { + for (Map.Entry<String, String> filePath : filePathMap.entrySet()) { + writeFile(filePath.getKey(), filePath.getValue(), boundary, out); + } + } + + //鍐欑粨灏剧殑鍒嗛殧绗�--${boundary}--,鐒跺悗鍥炶溅鎹㈣ + String endStr = BOUNDARY_PREFIX + boundary + BOUNDARY_PREFIX + LINE_END; + out.write(endStr.getBytes()); + } catch (Exception e) { + e.printStackTrace(); + response = new HttpResponse(500, e.getMessage()); + return response; + } + + return getHttpResponse(conn); + } + + public static HttpResponse postFormData(String urlStr, Map<String, MultipartFile> filePathMap, Map<String, Object> keyValues) throws IOException { + HttpResponse response; + HttpURLConnection conn = getHttpURLConnection(urlStr, null); + //鍒嗛殧绗︼紝鍙互浠绘剰璁剧疆锛岃繖閲岃缃负 MyBoundary+ 鏃堕棿鎴筹紙灏介噺澶嶆潅鐐癸紝閬垮厤鍜屾鏂囬噸澶嶏級 + String boundary = "MyBoundary" + System.currentTimeMillis(); + //璁剧疆 Content-Type 涓� multipart/form-data; boundary=${boundary} + conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); + + //鍙戦�佸弬鏁版暟鎹� + try (DataOutputStream out = new DataOutputStream(conn.getOutputStream())) { + //鍙戦�佹櫘閫氬弬鏁� + if (keyValues != null && !keyValues.isEmpty()) { + for (Map.Entry<String, Object> entry : keyValues.entrySet()) { + writeSimpleFormField(boundary, out, entry); + } + } + //鍙戦�佹枃浠剁被鍨嬪弬鏁� + if (filePathMap != null && !filePathMap.isEmpty()) { + for (Map.Entry<String, MultipartFile> filePath : filePathMap.entrySet()) { + writeFile(filePath.getKey(), filePath.getValue(), boundary, out); + } + } + + //鍐欑粨灏剧殑鍒嗛殧绗�--${boundary}--,鐒跺悗鍥炶溅鎹㈣ + String endStr = BOUNDARY_PREFIX + boundary + BOUNDARY_PREFIX + LINE_END; + out.write(endStr.getBytes()); + } catch (Exception e) { + response = new HttpResponse(500, e.getMessage()); + return response; + } + + return getHttpResponse(conn); + } + + /** + * 鑾峰緱杩炴帴瀵硅薄 + * + * @param urlStr + * @param headers + * @return + * @throws IOException + */ + private static HttpURLConnection getHttpURLConnection(String urlStr, Map<String, Object> headers) throws IOException { + URL url = new URL(urlStr); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + //璁剧疆瓒呮椂鏃堕棿 + conn.setConnectTimeout(50000); + conn.setReadTimeout(50000); + //鍏佽杈撳叆娴� + conn.setDoInput(true); + //鍏佽杈撳嚭娴� + conn.setDoOutput(true); + //涓嶅厑璁镐娇鐢ㄧ紦瀛� + conn.setUseCaches(false); + //璇锋眰鏂瑰紡 + conn.setRequestMethod("POST"); + //璁剧疆缂栫爜 utf-8 + conn.setRequestProperty("Charset", "UTF-8"); + //璁剧疆涓洪暱杩炴帴 + conn.setRequestProperty("connection", "keep-alive"); + + //璁剧疆鍏朵粬鑷畾涔� headers + if (headers != null && !headers.isEmpty()) { + for (Map.Entry<String, Object> header : headers.entrySet()) { + conn.setRequestProperty(header.getKey(), header.getValue().toString()); + } + } + + return conn; + } + + private static HttpResponse getHttpResponse(HttpURLConnection conn) { + HttpResponse response; + try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) { + int responseCode = conn.getResponseCode(); + StringBuilder responseContent = new StringBuilder(); + String line; + while ((line = reader.readLine()) != null) { + responseContent.append(line); + } + response = new HttpResponse(responseCode, responseContent.toString()); + } catch (Exception e) { + e.printStackTrace(); + response = new HttpResponse(500, e.getMessage()); + } + return response; + } + + /** + * 鍐欐枃浠剁被鍨嬬殑琛ㄥ崟鍙傛暟 + * + * @param paramName 鍙傛暟鍚� + * @param filePath 鏂囦欢璺緞 + * @param boundary 鍒嗛殧绗� + * @param out + * @throws IOException + */ + private static void writeFile(String paramName, String filePath, String boundary, + DataOutputStream out) { + try (BufferedReader fileReader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)))) { + /** + * 鍐欏垎闅旂--${boundary}锛屽苟鍥炶溅鎹㈣ + */ + String boundaryStr = BOUNDARY_PREFIX + boundary + LINE_END; + out.write(boundaryStr.getBytes()); + /** + * 鍐欐弿杩颁俊鎭�(鏂囦欢鍚嶈缃负涓婁紶鏂囦欢鐨勬枃浠跺悕)锛� + * 鍐� Content-Disposition: form-data; name="鍙傛暟鍚�"; filename="鏂囦欢鍚�"锛屽苟鍥炶溅鎹㈣ + * 鍐� Content-Type: application/octet-stream锛屽苟涓や釜鍥炶溅鎹㈣ + */ + String fileName = new File(filePath).getName(); + String contentDispositionStr = String.format("Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"", paramName, fileName) + LINE_END; + out.write(contentDispositionStr.getBytes()); + String contentType = "Content-Type: application/octet-stream" + LINE_END + LINE_END; + out.write(contentType.getBytes()); + + String line; + while ((line = fileReader.readLine()) != null) { + out.write(line.getBytes()); + } + //鍥炶溅鎹㈣ + out.write(LINE_END.getBytes()); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * 鍐欐枃浠剁被鍨嬬殑琛ㄥ崟鍙傛暟 + * + * @param paramName 鍙傛暟鍚� + * @param multipartFile 鏂囦欢 + * @param boundary 鍒嗛殧绗� + * @param out + * @throws IOException + */ + private static void writeFile(String paramName, MultipartFile multipartFile, String boundary, + DataOutputStream out) { + + try (BufferedReader fileReader = new BufferedReader(new InputStreamReader(multipartFile.getInputStream()))) { + /** + * 鍐欏垎闅旂--${boundary}锛屽苟鍥炶溅鎹㈣ + */ + String boundaryStr = BOUNDARY_PREFIX + boundary + LINE_END; + out.write(boundaryStr.getBytes()); + /** + * 鍐欐弿杩颁俊鎭�(鏂囦欢鍚嶈缃负涓婁紶鏂囦欢鐨勬枃浠跺悕)锛� + * 鍐� Content-Disposition: form-data; name="鍙傛暟鍚�"; filename="鏂囦欢鍚�"锛屽苟鍥炶溅鎹㈣ + * 鍐� Content-Type: application/octet-stream锛屽苟涓や釜鍥炶溅鎹㈣ + */ + String fileName = multipartFile.getName(); + String contentDispositionStr = String.format("Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"", paramName, fileName) + LINE_END; + out.write(contentDispositionStr.getBytes()); + String contentType = "Content-Type: application/octet-stream" + LINE_END + LINE_END; + out.write(contentType.getBytes()); + + String line; + while ((line = fileReader.readLine()) != null) { + out.write(line.getBytes()); + } + //鍥炶溅鎹㈣ + out.write(LINE_END.getBytes()); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * 鍐欐櫘閫氱殑琛ㄥ崟鍙傛暟 + * + * @param boundary 鍒嗛殧绗� + * @param out + * @param entry 鍙傛暟鐨勯敭鍊煎 + * @throws IOException + */ + private static void writeSimpleFormField(String boundary, DataOutputStream out, Map.Entry<String, Object> entry) throws IOException { + //鍐欏垎闅旂--${boundary}锛屽苟鍥炶溅鎹㈣ + String boundaryStr = BOUNDARY_PREFIX + boundary + LINE_END; + out.write(boundaryStr.getBytes()); + //鍐欐弿杩颁俊鎭細Content-Disposition: form-data; name="鍙傛暟鍚�"锛屽苟涓や釜鍥炶溅鎹㈣ + String contentDispositionStr = String.format("Content-Disposition: form-data; name=\"%s\"", entry.getKey()) + LINE_END + LINE_END; + out.write(contentDispositionStr.getBytes()); + //鍐欏叿浣撳唴瀹癸細鍙傛暟鍊硷紝骞跺洖杞︽崲琛� + String valueStr = entry.getValue().toString() + LINE_END; + out.write(valueStr.getBytes()); + } + + public static String formUpload(String urlStr, Map<String, String> textMap, + Map<String, String> fileMap,String contentType) { + String res = ""; + HttpURLConnection conn = null; + // boundary灏辨槸request澶村拰涓婁紶鏂囦欢鍐呭鐨勫垎闅旂 + String BOUNDARY = "---------------------------123821742118716"; + try { + URL url = new URL(urlStr); + conn = (HttpURLConnection) url.openConnection(); + conn.setConnectTimeout(5000); + conn.setReadTimeout(30000); + conn.setDoOutput(true); + conn.setDoInput(true); + conn.setUseCaches(false); + conn.setRequestMethod("POST"); + conn.setRequestProperty("Connection", "Keep-Alive"); + // conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)"); + conn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY); + OutputStream out = new DataOutputStream(conn.getOutputStream()); + // text + if (textMap != null) { + StringBuffer strBuf = new StringBuffer(); + Iterator iter = textMap.entrySet().iterator(); + while (iter.hasNext()) { + Map.Entry entry = (Map.Entry) iter.next(); + String inputName = (String) entry.getKey(); + String inputValue = (String) entry.getValue(); + if (inputValue == null) { + continue; + } + strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n"); + strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n"); + strBuf.append(inputValue); + } + out.write(strBuf.toString().getBytes()); + } + // file + if (fileMap != null) { + Iterator iter = fileMap.entrySet().iterator(); + while (iter.hasNext()) { + Map.Entry entry = (Map.Entry) iter.next(); + String inputName = (String) entry.getKey(); + String inputValue = (String) entry.getValue(); + if (inputValue == null) { + continue; + } + File file = new File(inputValue); + String filename = file.getName(); + + //娌℃湁浼犲叆鏂囦欢绫诲瀷锛屽悓鏃舵牴鎹枃浠惰幏鍙栦笉鍒扮被鍨嬶紝榛樿閲囩敤application/octet-stream + contentType = new MimetypesFileTypeMap().getContentType(file); + //contentType闈炵┖閲囩敤filename鍖归厤榛樿鐨勫浘鐗囩被鍨� + if(!"".equals(contentType)){ + if (filename.endsWith(".png")) { + contentType = "image/png"; + }else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) { + contentType = "image/jpeg"; + }else if (filename.endsWith(".gif")) { + contentType = "image/gif"; + }else if (filename.endsWith(".ico")) { + contentType = "image/image/x-icon"; + } + } + if (contentType == null || "".equals(contentType)) { + contentType = "application/octet-stream"; + } + StringBuffer strBuf = new StringBuffer(); + strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n"); + strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n"); + strBuf.append("Content-Type:" + contentType + "\r\n\r\n"); + out.write(strBuf.toString().getBytes()); + DataInputStream in = new DataInputStream(new FileInputStream(file)); + int bytes = 0; + byte[] bufferOut = new byte[1024]; + while ((bytes = in.read(bufferOut)) != -1) { + out.write(bufferOut, 0, bytes); + } + in.close(); + } + } + byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes(); + out.write(endData); + out.flush(); + out.close(); + // 璇诲彇杩斿洖鏁版嵁 + StringBuffer strBuf = new StringBuffer(); + BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); + String line = null; + while ((line = reader.readLine()) != null) { + strBuf.append(line).append("\n"); + } + res = strBuf.toString(); + reader.close(); + reader = null; + } catch (Exception e) { + System.out.println("鍙戦�丳OST璇锋眰鍑洪敊銆�" + urlStr); + e.printStackTrace(); + } finally { + if (conn != null) { + conn.disconnect(); + conn = null; + } + } + return res; + } + +} diff --git a/hx_common/src/main/java/com/hx/util/IPUtils.java b/hx_common/src/main/java/com/hx/util/IPUtils.java new file mode 100644 index 0000000..b3e2b82 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/IPUtils.java @@ -0,0 +1,40 @@ +package com.hx.util; + +import javax.servlet.http.HttpServletRequest; + +/** + * @author ChenJiaHe + * @date 2020-12-2 + */ +public class IPUtils { + + /**鑾峰彇璁块棶ip鍦板潃*/ + public static String getIpAddr(HttpServletRequest request) { + String ip=request.getHeader("x-forwarded-for"); + if(null!=ip && ip.length()!=0 && !"unknown".equalsIgnoreCase(ip)) { + if(ip.indexOf(",")!=-1) { + ip=ip.split(",")[0]; + } + } + if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)) { + ip=request.getHeader("Proxy-Client-Ip"); + } + if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)) { + ip=request.getHeader("WL-Proxy-Client-IP"); + } + if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)) { + ip=request.getHeader("HTTP_CLIENT_IP"); + } + if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)) { + ip=request.getHeader("HTTP_X_FORWARDED_FOR"); + } + if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)) { + ip=request.getHeader("X-Real-IP"); + } + if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)) { + ip=request.getRemoteAddr(); + } + return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip; + + } +} diff --git a/hx_common/src/main/java/com/hx/util/ImageBase64Util.java b/hx_common/src/main/java/com/hx/util/ImageBase64Util.java new file mode 100644 index 0000000..5dbfb5a --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/ImageBase64Util.java @@ -0,0 +1,79 @@ +package com.hx.util; + +import sun.misc.BASE64Decoder; +import sun.misc.BASE64Encoder; + +import java.io.*; + +/** + * 鍥剧墖鍜宐ase64瀛楃杞崲宸ュ叿 + * @USER: fhx + * @DATE: 2023/4/6 + **/ +public class ImageBase64Util { + + /** + * base64瀛楃涓茶浆鍖栨垚鍥剧墖 + * @param base64 + * @param fileName + * @param filePath + * @return + * @throws Exception + */ + public static File base64ToFile(String base64, String fileName, String filePath) throws Exception { + if(base64.contains("data:image")){ + base64 = base64.substring(base64.indexOf(",")+1); + } + base64 = base64.replace("\r\n", ""); + //鍒涘缓鏂囦欢鐩綍 + File file = File.createTempFile(base64, fileName, new File(filePath)); + BufferedOutputStream bos = null; + FileOutputStream fos = null; + try { + BASE64Decoder decoder = new BASE64Decoder(); + byte[] bytes = decoder.decodeBuffer(base64); + fos = new FileOutputStream(file); + bos = new BufferedOutputStream(fos); + bos.write(bytes); + }finally { + if (bos != null) { + try { + bos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (fos != null) { + try { + fos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + return file; + } + + /** + * 鍥剧墖杞寲鎴恇ase64瀛楃涓� + * @param imgFile + * @return + */ + public static String GetImageStr(File imgFile) {//灏嗗浘鐗囨枃浠惰浆鍖栦负瀛楄妭鏁扮粍瀛楃涓诧紝骞跺鍏惰繘琛孊ase64缂栫爜澶勭悊 + InputStream in = null; + byte[] data = null; + //璇诲彇鍥剧墖瀛楄妭鏁扮粍 + try { + in = new FileInputStream(imgFile); + data = new byte[in.available()]; + in.read(data); + in.close(); + } catch (IOException e) { + e.printStackTrace(); + } + //瀵瑰瓧鑺傛暟缁凚ase64缂栫爜 + BASE64Encoder encoder = new BASE64Encoder(); + return encoder.encode(data);//杩斿洖Base64缂栫爜杩囩殑瀛楄妭鏁扮粍瀛楃涓� + } + +} diff --git a/hx_common/src/main/java/com/hx/util/ImagesAddDomain.java b/hx_common/src/main/java/com/hx/util/ImagesAddDomain.java new file mode 100644 index 0000000..8a7f0be --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/ImagesAddDomain.java @@ -0,0 +1,84 @@ +package com.hx.util; + +import net.sf.json.JSONArray; + +/**鍥剧墖璺緞鍔犱笂鍩熷悕 + * @author ChenJiaHe + * @Date 2020-07-07 + */ +public class ImagesAddDomain { + + /** + * 鍥剧墖璺緞鍔犱笂鍩熷悕 + * @param arrString 鍥剧墖JSON瀛楃涓叉暟缁� + * @param domainName 鍩熷悕 + * @return + */ + public static JSONArray imagesAddDomain(String arrString, String domainName){ + JSONArray arr = new JSONArray(); + if(SimpleTool.checkNotNull(arrString)){ + JSONArray images = JSONArray.fromObject(arrString); + for(int i = 0;i<images.size();i++){ + if(images.getString(i).startsWith("http")){ + arr.add(images.getString(i)); + }else{ + arr.add(urlAddDomain(images.getString(i),domainName)); + } + } + } + return arr; + } + + /** + * 鍥剧墖璺緞鍔犱笂鍩熷悕 + * @param imagesArr 鍥剧墖鏁扮粍 + * @param domainName 鍩熷悕 + * @return + */ + public static JSONArray imagesAddDomain(JSONArray imagesArr, String domainName){ + JSONArray arr = new JSONArray(); + if(SimpleTool.checkNotNull(imagesArr)){ + for(int i = 0;i<imagesArr.size();i++){ + if(imagesArr.getString(i).startsWith("http")){ + arr.add(imagesArr.getString(i)); + }else{ + arr.add(urlAddDomain(imagesArr.getString(i),domainName)); + } + } + } + return arr; + } + + /** + * 鍥剧墖璺緞鍔犱笂鍩熷悕 + * @param imagesUrl 鍥剧墖璺緞 + * @param domainName 鍩熷悕 + * @return + */ + public static String urlAddDomain(String imagesUrl, String domainName){ + if(StringUtils.isEmpty(domainName)){ + return imagesUrl; + } + if(SimpleTool.checkNotNull(imagesUrl)){ + if(imagesUrl.startsWith("http")){ + return imagesUrl; + } + if(domainName.endsWith("/")){ + if(imagesUrl.startsWith("/")){ + imagesUrl = imagesUrl.replaceFirst("/",""); + imagesUrl = domainName+imagesUrl; + }else{ + imagesUrl = domainName+imagesUrl; + } + }else{ + if(imagesUrl.startsWith("/")){ + imagesUrl = domainName+imagesUrl; + }else{ + imagesUrl = domainName+"/"+imagesUrl; + } + } + } + return imagesUrl; + } + +} diff --git a/hx_common/src/main/java/com/hx/util/JwtConstant.java b/hx_common/src/main/java/com/hx/util/JwtConstant.java new file mode 100644 index 0000000..be0eac5 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/JwtConstant.java @@ -0,0 +1,54 @@ +package com.hx.util; + +import com.alibaba.fastjson.JSONObject; + +import io.jsonwebtoken.Claims; + +/** + * JWT 鍏峰閰嶇疆 + * @author chenjiahe + * @Data 2020-06-09 + */ +public class JwtConstant { + + public static void main(String[] args) { + //姣忔柊寮�涓�涓」鐩氨閲嶆柊鐢熸垚JWT_SECERT绉橀挜 + //String s = BASE64.encryptBASE64("hx-haoqi168".getBytes()); + //System.out.println("s:"+s); + JSONObject obj = new JSONObject(); + obj.put("id", "111"); + obj.put("adminRoleId", "22"); + String token = JwtTool.createJWT("111", obj.toString(), 300); + System.out.println("token:"+token); + //eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxMTEiLCJzdWIiOiLkuprpurvot4wiLCJpc3MiOiJ1c2VyIiwiaWF0IjoxNTkxODY4NjAxLCJleHAiOjE1OTE4Njg5MDF9.8m_TgK8m49r35-qQRQ0cGjL4r_jBlaVqb318vM00qrE + } + + public static String JWT_ERRCODE_EXPIRE = "鐧诲綍鏈夋晥鏈熷凡杩囷紒"; + public static String JWT_ERRCODE_FAIL = "鐧诲綍鏃犳晥锛岃閲嶆柊鐧诲綍锛�"; + public static String JWT_SECERT = "aGFvcWkxNjg=";//鐢熸垚JWT鐨勭閽� + + private Claims claims; + private boolean success; + private String errCode; + + + /*************************************************************************/ + public Claims getClaims() { + return claims; + } + public void setClaims(Claims claims) { + this.claims = claims; + } + public boolean isSuccess() { + return success; + } + public void setSuccess(boolean success) { + this.success = success; + } + public String getErrCode() { + return errCode; + } + public void setErrCode(String errCode) { + this.errCode = errCode; + } +} diff --git a/hx_common/src/main/java/com/hx/util/JwtTool.java b/hx_common/src/main/java/com/hx/util/JwtTool.java new file mode 100644 index 0000000..c2d050a --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/JwtTool.java @@ -0,0 +1,94 @@ +package com.hx.util; + +import java.util.Base64; +import java.util.Date; + +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.ExpiredJwtException; +import io.jsonwebtoken.JwtBuilder; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import io.jsonwebtoken.SignatureException; + +/** + * 鐢熸垚token 锛堢櫥褰曪紝鎴栬�呭叾浠栵級 + * @author chenjiahe + * @Data 20200609 + */ +public class JwtTool { + + /** + * 绛惧彂JWT + * @param id 鏍囪瘑 + * @param subject 鍙互鏄疛SON鏁版嵁 灏藉彲鑳藉皯 + * @param ttlMillis 鏈夋晥鏃堕棿闀垮害(绉�)锛屼负绌轰綘璁よ瘉鏃堕棿 + * @return String + * + */ + public static String createJWT(String id, String subject, long ttlMillis) { + SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; + long nowMillis = System.currentTimeMillis(); + Date now = new Date(nowMillis); + SecretKey secretKey = generalKey(); + JwtBuilder builder = Jwts.builder() + .setId(id) + .setSubject(subject) // 涓婚 + .setIssuer("user") // 绛惧彂鑰� + .setIssuedAt(now) // 绛惧彂鏃堕棿 + .signWith(signatureAlgorithm, secretKey); // 绛惧悕绠楁硶浠ュ強瀵嗗寵 + if (SimpleTool.checkNotNull(ttlMillis)&&ttlMillis >= 0) { + long expMillis = nowMillis + ttlMillis*1000; + Date expDate = new Date(expMillis); + builder.setExpiration(expDate); // 杩囨湡鏃堕棿 + } + return builder.compact(); + } + /** + * 楠岃瘉JWT + * @param jwtStr + * @return JwtConstant + */ + public static JwtConstant validateJWT(String jwtStr) { + JwtConstant checkResult = new JwtConstant(); + Claims claims = null; + try { + claims = parseJWT(jwtStr); + checkResult.setSuccess(true); + checkResult.setClaims(claims); + } catch (ExpiredJwtException e) { + checkResult.setErrCode(JwtConstant.JWT_ERRCODE_EXPIRE); + checkResult.setSuccess(false); + } catch (SignatureException e) { + checkResult.setErrCode(JwtConstant.JWT_ERRCODE_FAIL); + checkResult.setSuccess(false); + } catch (Exception e) { + checkResult.setErrCode(JwtConstant.JWT_ERRCODE_FAIL); + checkResult.setSuccess(false); + } + return checkResult; + } + + public static SecretKey generalKey() { + byte[] encodedKey = Base64.getDecoder().decode(JwtConstant.JWT_SECERT); + SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES"); + return key; + } + + /** + * + * 瑙f瀽JWT瀛楃涓� + * @param jwt + * @return + * @throws Exception + */ + public static Claims parseJWT(String jwt) throws Exception { + SecretKey secretKey = generalKey(); + return Jwts.parser() + .setSigningKey(secretKey) + .parseClaimsJws(jwt) + .getBody(); + } +} diff --git a/hx_common/src/main/java/com/hx/util/MD5.java b/hx_common/src/main/java/com/hx/util/MD5.java new file mode 100644 index 0000000..2196ad7 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/MD5.java @@ -0,0 +1,64 @@ +package com.hx.util; + +import java.security.MessageDigest; + +public class MD5 { + private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5", + "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; + + public static String byteArrayToHexString(byte[] b) { + StringBuffer resultSb = new StringBuffer(); + for (int i = 0; i < b.length; i++) { + resultSb.append(byteToHexString(b[i])); + } + return resultSb.toString(); + } + + private static String byteToHexString(byte b) { + int n = b; + if (n < 0) + n = 256 + n; + int d1 = n / 16; + int d2 = n % 16; + return hexDigits[d1] + hexDigits[d2]; + } + + public static String MD5Encode(String origin) { + String resultString = null; + + try { + resultString = new String(origin); + MessageDigest md = MessageDigest.getInstance("MD5"); + resultString = byteArrayToHexString(md.digest(resultString + .getBytes())); + } catch (Exception ex) { + + } + return resultString; + } + + /**瀵嗙爜鍔犲瘑 **/ + public static String encryption(String str){ + try{ + MessageDigest md5 = MessageDigest.getInstance("MD5"); + md5.update(str.getBytes()); + byte b[] = md5.digest(); + int i ; + StringBuffer buf = new StringBuffer(""); + for(int j = 0;j<b.length;j++){ + i = b[j]; + if(i<0) + i+=256; + if(i<116) + buf.append("0"); + buf.append(Integer.toHexString(i)); + } + str = buf.toString().substring(8, 24); //鍗佸叚浣� + }catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("鍔犲瘑绋嬪簭閿欒锛�"); + } + return str; + } + +} \ No newline at end of file diff --git a/hx_common/src/main/java/com/hx/util/MD5Util.java b/hx_common/src/main/java/com/hx/util/MD5Util.java new file mode 100644 index 0000000..f7eba43 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/MD5Util.java @@ -0,0 +1,48 @@ +package com.hx.util; + +import java.security.MessageDigest; + +public class MD5Util { + + private static String byteArrayToHexString(byte b[]) { + StringBuffer resultSb = new StringBuffer(); + for (int i = 0; i < b.length; i++) + resultSb.append(byteToHexString(b[i])); + + return resultSb.toString(); + } + + private static String byteToHexString(byte b) { + int n = b; + if (n < 0) + n += 256; + int d1 = n / 16; + int d2 = n % 16; + return hexDigits[d1] + hexDigits[d2]; + } + + /** + * @param origin 鍔犲瘑淇℃伅 + * @param charsetname 鍔犲瘑淇℃伅鐨勫瓧绗︿覆鍚嶇О锛堝彲浠ヤ负绌猴級 + * @return + */ + public static String MD5Encode(String origin, String charsetname) { + String resultString = null; + try { + resultString = new String(origin); + MessageDigest md = MessageDigest.getInstance("MD5"); + if (charsetname == null || "".equals(charsetname)) + resultString = byteArrayToHexString(md.digest(resultString + .getBytes())); + else + resultString = byteArrayToHexString(md.digest(resultString + .getBytes(charsetname))); + } catch (Exception exception) { + } + return resultString; + } + + private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5", + "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; + +} diff --git a/hx_common/src/main/java/com/hx/util/MapUtil.java b/hx_common/src/main/java/com/hx/util/MapUtil.java new file mode 100644 index 0000000..1fba6e0 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/MapUtil.java @@ -0,0 +1,93 @@ +package com.hx.util; + +import java.math.BigDecimal; +import java.util.Map; + +/** + * map宸ュ叿绫� + * + * @author cmg + * @date 2023-03-16 + */ +public class MapUtil { + + /** + * 浠巑ap涓幏鍙� + * @param map + * @param key + * @return + */ + public static String getString(Map<String, Object> map, String key) + { + if(map == null || StringUtils.isEmpty(key)) + { + return null; + } + + return null == map.get(key) ? null : map.get(key).toString(); + } + + /** + * 浠巑ap涓幏鍙栨暣鏁帮紝濡傛灉娌℃湁锛屽垯杩斿洖-1 + * @param map + * @param key + * @return + */ + public static int getInt(Map<String, Object> map, String key) + { + if(map == null || StringUtils.isEmpty(key)) + { + return -1; + } + + return null == map.get(key) ? -1 : Integer.parseInt(map.get(key).toString()); + } + + /** + * 浠巑ap涓幏鍙栨暣鏁帮紝濡傛灉娌℃湁锛屽垯杩斿洖0 + * @param map + * @param key + * @return + */ + public static int getIntZero(Map<String, Object> map, String key) + { + if(map == null || StringUtils.isEmpty(key)) + { + return 0; + } + + return null == map.get(key) ? 0 : Integer.parseInt(map.get(key).toString()); + } + + /** + * 浠巑ap涓幏鍙栨暟瀛楃被鍨嬪璞� + * @param map + * @param key + * @return + */ + public static BigDecimal getBigDecimal(Map<String, Object> map, String key) + { + if(map == null || StringUtils.isEmpty(key)) + { + return BigDecimal.ZERO; + } + + return null == map.get(key) ? BigDecimal.ZERO : new BigDecimal(map.get(key).toString()); + } + + /** + * 鑾峰彇娴偣鏁帮紝榛樿杩斿洖0 + * @param map + * @param key + * @return + */ + public static Double getDoubleZero(Map<String, Object> map, String key) + { + if(map == null || StringUtils.isEmpty(key)) + { + return 0D; + } + + return null == map.get(key) ? 0D : Double.parseDouble(map.get(key).toString()); + } +} diff --git a/hx_common/src/main/java/com/hx/util/MultipartFileUtil.java b/hx_common/src/main/java/com/hx/util/MultipartFileUtil.java new file mode 100644 index 0000000..464494e --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/MultipartFileUtil.java @@ -0,0 +1,58 @@ +package com.hx.util; + +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.FileItemFactory; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; +import org.apache.commons.io.IOUtils; +import org.springframework.http.MediaType; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.multipart.commons.CommonsMultipartFile; + +import java.io.*; + +public class MultipartFileUtil { + + + /**鏂囦欢杞寲 + * File to MultipartFile + * @param file + * @return + */ + public static MultipartFile getMultipartFile(File file) { + FileItem item = new DiskFileItemFactory().createItem("file" + , MediaType.MULTIPART_FORM_DATA_VALUE + , true + , file.getName()); + try (InputStream input = new FileInputStream(file); + OutputStream os = item.getOutputStream()) { + // 娴佽浆绉� + IOUtils.copy(input, os); + } catch (Exception e) { + throw new IllegalArgumentException("Invalid file: " + e, e); + } + return new CommonsMultipartFile(item); + } + + + /**鏂囦欢杞寲 + * File to MultipartFile + * @param file 鏂囦欢 + * @param fileName 甯﹀悗缂�鐨勬枃浠跺悕 + * @return + */ + public static MultipartFile getMultipartFile(File file,String fileName) { + FileItem item = new DiskFileItemFactory().createItem("file" + , MediaType.MULTIPART_FORM_DATA_VALUE + , true + , StringUtils.isEmpty(fileName)?file.getName():fileName); + try (InputStream input = new FileInputStream(file); + OutputStream os = item.getOutputStream()) { + // 娴佽浆绉� + IOUtils.copy(input, os); + } catch (Exception e) { + throw new IllegalArgumentException("Invalid file: " + e, e); + } + return new CommonsMultipartFile(item); + } + +} diff --git a/hx_common/src/main/java/com/hx/util/MyRedisTemplate.java b/hx_common/src/main/java/com/hx/util/MyRedisTemplate.java new file mode 100644 index 0000000..5a081c7 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/MyRedisTemplate.java @@ -0,0 +1,139 @@ +package com.hx.util; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.ListOperations; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.ValueOperations; +import org.springframework.stereotype.Component; + +import java.util.concurrent.TimeUnit; + +/** + * @PackageName com.hx.util + * @ProjectName hx-parent + * @Author: ChenJiaHe + * @Date: Create in 16:51 2019/7/22 + * @Description: + * @Copyright Copyright (c) 2019, hx01@163.com All Rights Reserved. + */ +@Component +public class MyRedisTemplate<E> { + @Autowired + private RedisTemplate redisTemplate; + + @Autowired + private SerializeUtil<E> serialize; + + public static ListOperations<String, String> list; + + /** + * 鏍规嵁閿�艰幏鍙杤alue + * @param key + * @return + */ + public E get(String key) { + ValueOperations<String, String> opsForValue = redisTemplate.opsForValue(); + return key == null ? null : serialize.unserialize(opsForValue.get(key)); + } + + /** + * 璁剧疆閿�煎(鏃犺秴鏃舵椂闂�) + * @param key + * @param value + * @return + */ + public boolean set(String key, E value) { + ValueOperations<String, String> opsForValue = redisTemplate.opsForValue(); + try { + opsForValue.set(key, serialize.serialize(value)); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 璁剧疆閿�煎 (璁剧疆鏈夋晥鏃堕棿,浠ョ涓哄崟浣�) + * + * @param key + * @param value + * @param expire + * @return boolean + */ + public boolean set(String key, E value, long expire) { + ValueOperations<String, String> opsForValue = redisTemplate.opsForValue(); + try { + opsForValue.set(key, serialize.serialize(value), expire, TimeUnit.SECONDS); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 鏍规嵁key鍒犻櫎閿�煎 + * + * @param key + * @return + */ + public boolean delete(String key) { + try { + redisTemplate.delete(key); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + return true; + } + + /* + * 妯℃嫙闃熷垪 + */ + + /** + * lpush 杩涢槦鍒� + * + * @param key + * @param value + * @return + */ + public Long lpush(String key, String value) { + list = redisTemplate.opsForList(); + try { + Long leftPush = list.leftPush(key, value); + return leftPush; + } catch (Exception e) { + e.printStackTrace(); + return Long.valueOf(-1); + } + } + + /** + * rpop 鍑洪槦鍒� + * + * @param key + * @return + */ + public String rpop(String key) { + list = redisTemplate.opsForList(); + try { + return list.rightPop(key); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * 杩斿洖鎸囧畾闃熷垪(list)鍚嶉槦鍒楅暱搴� + * + * @param key + * @return + */ + public Long llen(String key) { + list = redisTemplate.opsForList(); + return list.size(key); + } +} diff --git a/hx_common/src/main/java/com/hx/util/NumberUtil.java b/hx_common/src/main/java/com/hx/util/NumberUtil.java new file mode 100644 index 0000000..9ed21d0 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/NumberUtil.java @@ -0,0 +1,418 @@ +package com.hx.util; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.text.DecimalFormat; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * 鏁板瓧宸ュ叿 + * + * @author mgchen + * + */ +public class NumberUtil { + + private static DecimalFormat fmt = new DecimalFormat("0.00"); + + private static DecimalFormat fmtOne = new DecimalFormat("0.0"); + + private static DecimalFormat fmtThree = new DecimalFormat("0.000"); + + /** + * 鑾峰彇鎸囧畾鏍煎紡鐨凞ouble 绫诲瀷鏁版嵁 + * @param e + * 瑕佽浆鎹㈢殑鏁版嵁婧� + **/ + public static Double getTypeDouble(Double e) { + fmt.setRoundingMode(RoundingMode.HALF_UP); // 淇濈暀灏忔暟鐐瑰悗涓や綅骞跺洓鑸嶄簲鍏ワ紝纭繚浠烽挶鍑嗙‘ + Double d = Double.valueOf(fmt.format(e)); + return d; + } + + /** + * 鑾峰彇鎸囧畾鏍煎紡鐨凞ouble 绫诲瀷鏁版嵁 + * + * @param e + * 瑕佽浆鎹㈢殑鏁版嵁婧� + **/ + public static Double getTypeDouble1(Double e) { + fmtOne.setRoundingMode(RoundingMode.HALF_UP); // 淇濈暀灏忔暟鐐瑰悗涓や綅骞跺洓鑸嶄簲鍏ワ紝纭繚浠烽挶鍑嗙‘ + Double d = Double.valueOf(fmtOne.format(e)); + return d; + } + + public static Double getTypeDouble2(Double e) { + fmtThree.setRoundingMode(RoundingMode.HALF_UP); // 淇濈暀灏忔暟鐐瑰悗涓や綅骞跺洓鑸嶄簲鍏ワ紝纭繚浠烽挶鍑嗙‘ + Double d = Double.valueOf(fmtThree.format(e)); + return d; + } + + /** + * 鎶婂瓨鍌ㄧ殑鍒嗗瓧绗︿覆杞垚鍏冪殑娴偣鏁� 渚嬪100鍒�1.0 + */ + public static Double getYunFromFenStr(String fenStr) { + return getTypeDouble(Integer.parseInt(fenStr) * 1.0 / 100); + } + + /** + * 鎶婂瓨鍌ㄧ殑鍒嗚浆鎴愬厓鐨勬诞鐐规暟 渚嬪100鍒�1.0 + */ + public static Double getYunFromFen(Integer fen) { + if (fen == null) { + return 0D; + } + return getTypeDouble(fen * 1.0 / 100); + } + + /** + * 鎶婂瓨鍌ㄧ殑鍘樿浆鎴愬厓鐨勬诞鐐规暟 渚嬪1000鍒�1.0 + */ + public static Double getYunFromLi(int li) { + return getTypeDouble2(li * 1.0 / 1000); + } + + /** + * 鎶婂瓨鍌ㄧ殑鏁板�艰浆涓虹櫨鍒嗘瘮 + * + * @param rate + * @return + */ + public static Double getRateFromInt(int rate) { + return getTypeDouble(rate * 1.0 / 100); + } + + /** 娴偣鏁板洓鑸嶄簲鍏ュ彇鏁� */ + public static int getRoundHalfUp(double tar) { + return new BigDecimal(tar).setScale(0, BigDecimal.ROUND_HALF_UP).intValue(); + } + + /** 娴偣鏁板洓鑸嶄簲鍏ュ彇鏁� */ + public static int getRoundHalfDown(double tar) { + Double d = Math.floor(tar); + return d.intValue(); + } + + /** + * 鎶婁竴涓猟ouble鐨勫瓧绗︿覆涔�100 杩斿洖鏁存暟 + * + * @return int 鏁存暟 + */ + public static int getYunFromFen(String str) { + // BigDecimal b1 = new BigDecimal(str); + // BigDecimal b2 = new BigDecimal("100"); + // return b1.multiply(b2).intValue(); + return multiply(str, "100").intValue(); + } + + /** 鑾峰彇涓や綅灏忔暟鐨勬暣鏁� */ + public static int getTwoDecimalInt(Double d) { + return Double.valueOf(fmt.format(d)).intValue(); + } + + /** + * num1 闄や互num2 寰楀埌鐧惧垎鐧� 淇濈暀涓�浣嶅皬鏁� + * + * @param num1 + * @param num2 + * @return + */ + public static Double getPercentage(Integer num1, Integer num2) { + Double reNum = 0d; + if (num1 == null || num2 == null || num1 == 0 || num2 == 0) { + return reNum; + } + BigDecimal b1 = new BigDecimal(num1 * 100); + BigDecimal b2 = new BigDecimal(num2); + reNum = b1.divide(b2, 1, BigDecimal.ROUND_HALF_UP).doubleValue(); + return reNum; + } + + /** + * 灏嗕竴涓暟闄や互100 + * + * @param fen + * @return Double + */ + public static Double fenForYuan(int fen) { + // BigDecimal b1 = new BigDecimal(fen); + // BigDecimal b2 = new BigDecimal(100); + // return b1.divide(b2).doubleValue(); + return divide(fen, 100); + } + + /** + * 灏嗕竴涓暟闄や互100 + * + * @param fen + * @return Double + */ + public static Double fenForYuan(String fen) { + // BigDecimal b1 = new BigDecimal(fen); + // BigDecimal b2 = new BigDecimal(100); + // return b1.divide(b2).doubleValue(); + return divide(fen, "100"); + } + + public static void main(String[] args) { + double d = 299999d; + System.out.println(getTwoOfDouble(d)); + } + + /** + * 涓や釜鏁扮浉闄� + * + * @param num1 + * 鏁板瓧1 + * @param num2 + * 鏁板瓧2 + * @return + */ + public static Double divide(int num1, int num2) { + return divide(num1 * 1D, num2 * 1D); + } + + /** + * 涓や釜鏁扮浉闄�- 淇濈暀涓や綅灏忔暟鐐� + * + * @param num1 + * 鏁板瓧1 + * @param num2 + * 鏁板瓧2 + * @return + */ + public static Double divide(String num1, String num2) { + return divide(Double.parseDouble(num1), Double.parseDouble(num1), 2); + } + + /** + * 涓や釜鏁扮浉闄�- 淇濈暀涓や綅灏忔暟鐐� + * + * @param num1 + * 鏁板瓧1 + * @param num2 + * 鏁板瓧2 + * @return + */ + public static Double divide(Double num1, Double num2) { + return divide(num1, num2, 2); + } + + /** + * 涓や釜鏁扮浉闄� + * + * @param num1 + * 鏁板瓧1 + * @param num2 + * 鏁板瓧2 + * @param scale + * 灏忔暟浣嶆暟锛� 榛樿淇濈暀2浣� + * @return + */ + public static Double divide(Double num1, Double num2, Integer scale) { + if (scale == null || scale < 0) { + scale = 2; + } + BigDecimal b1 = new BigDecimal(num1); + BigDecimal b2 = new BigDecimal(num2); + return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue(); + } + + /** + * + * 涓や釜鏁扮浉闄� + * + * @param num1 + * 鏁板瓧1 + * @param num2 + * 鏁板瓧2 + * @param scale + * 灏忔暟浣嶆暟锛� 榛樿淇濈暀2浣� + * @return + */ + public static Double divideDown(Double num1, Double num2, Integer scale) { + if (scale == null || scale < 0) { + scale = 2; + } + BigDecimal b1 = new BigDecimal(num1); + BigDecimal b2 = new BigDecimal(num2); + + return b1.divide(b2, scale, BigDecimal.ROUND_DOWN).doubleValue(); + } + + /** + * 涓や釜Double鏁扮浉涔� + * + * @param num1 + * @param num2 + * @return Double + * + */ + public static Double multiply(Double num1, Double num2) { + return multiply(num1.toString(), num2.toString()); + } + + /** + * 涓や釜Double鏁扮浉涔� + * + * @param num1 + * @param num2 + * @return Double + * + */ + public static Double multiply(String num1, String num2) { + BigDecimal b1 = new BigDecimal(num1); + BigDecimal b2 = new BigDecimal(num2); + return b1.multiply(b2).doubleValue(); + } + + /** + * 涓や釜Double鏁扮浉鍑� + * + * @param v1 + * @param v2 + * @return Double + */ + public static Double subtract(Double v1, Double v2) { + return subtract(v2.toString(), v2.toString()); + } + + /** + * 涓や釜Double鏁扮浉鍑� + * + * @param v1 + * @param v2 + * @return Double + */ + public static Double subtract(String v1, String v2) { + BigDecimal b1 = new BigDecimal(v1); + BigDecimal b2 = new BigDecimal(v2); + return b1.subtract(b2).doubleValue(); + } + + /** + * 涓や釜Double鏁扮浉鍔� + * + * @param v1 + * @param v2 + * @return Double + */ + public static Double add(Double v1, Double v2) { + return add(v1.toString(), v2.toString()); + } + + /** + * 涓や釜Double鏁扮浉鍔� + * + * @param v1 + * @param v2 + * @return Double + */ + public static Double add(String v1, String v2) { + BigDecimal b1 = new BigDecimal(v1); + BigDecimal b2 = new BigDecimal(v2); + return b1.add(b2).doubleValue(); + } + + /** 浠庡厓杞寲涓哄垎锛屽厓涓�2浣嶅皬鏁� */ + public static int getFenFromYun(String doubleStr) { + return getRoundHalfUp(Double.parseDouble(doubleStr) * 100); + } + + /**鑾峰彇涓や綅灏忔暟鐨勫瓧绗︿覆*/ + public static String getTwoOfDouble(double value) + { + String str = value + ""; + + //濡傛灉鏈夊皬鏁扮偣锛屽垯涓や綅灏忔暟 + int pointIndex = str.indexOf("."); + if(pointIndex != -1) + { + int len = str.length(); + if(len - (pointIndex + 1) > 2) + { + return str.substring(0, pointIndex + 3); + } + } + + return str; + } + + /**Double绫诲瀷杞寲 + * @param data 鏁版嵁 + * @param digitNumber 淇濈暀澶氬皯浣嶅皬鏁� + * @return + */ + public static Double getTypeDouble(Double data,Integer digitNumber) { + //鍒╃敤BigDecimal鏉ュ疄鐜板洓鑸嶄簲鍏�.淇濈暀涓�浣嶅皬鏁� + double result2 = new BigDecimal(data).setScale(digitNumber, BigDecimal.ROUND_HALF_UP).doubleValue(); + //1浠h〃淇濈暀1浣嶅皬鏁�,淇濈暀涓や綅灏忔暟灏辨槸2 + //BigDecimal.ROUND_HALF_UP 浠h〃浣跨敤鍥涜垗浜斿叆鐨勬柟寮� + + return result2; + } + + /** + * 浠庡瓧绗︿覆涓彁鍙栧皬鏁� + * @param str + * @return + */ + public static String getNumber(String str){ + // 鎺у埗姝e垯琛ㄨ揪寮忕殑鍖归厤琛屼负鐨勫弬鏁�(灏忔暟) + Pattern p = Pattern.compile("(\\d+\\.\\d+)"); + //Matcher绫荤殑鏋勯�犳柟娉曚篃鏄鏈夌殑,涓嶈兘闅忔剰鍒涘缓,鍙兘閫氳繃Pattern.matcher(CharSequence input)鏂规硶寰楀埌璇ョ被鐨勫疄渚�. + Matcher m = p.matcher(str); + //m.find鐢ㄦ潵鍒ゆ柇璇ュ瓧绗︿覆涓槸鍚﹀惈鏈変笌"(\\d+\\.\\d+)"鐩稿尮閰嶇殑瀛愪覆 + if (m.find()) { + //濡傛灉鏈夌浉鍖归厤鐨�,鍒欏垽鏂槸鍚︿负null鎿嶄綔 + //group()涓殑鍙傛暟锛�0琛ㄧず鍖归厤鏁翠釜姝e垯锛�1琛ㄧず鍖归厤绗竴涓嫭鍙风殑姝e垯,2琛ㄧず鍖归厤绗簩涓鍒�,鍦ㄨ繖鍙湁涓�涓嫭鍙�,鍗�1鍜�0鏄竴鏍风殑 + str = m.group(1) == null ? "" : m.group(1); + } else { + //濡傛灉鍖归厤涓嶅埌灏忔暟锛屽氨杩涜鏁存暟鍖归厤 + p = Pattern.compile("(\\d+)"); + m = p.matcher(str); + if (m.find()) { + //濡傛灉鏈夋暣鏁扮浉鍖归厤 + str = m.group(1) == null ? "" : m.group(1); + } else { + //濡傛灉娌℃湁灏忔暟鍜屾暣鏁扮浉鍖归厤,鍗冲瓧绗︿覆涓病鏈夋暣鏁板拰灏忔暟锛屽氨璁句负绌� + str = ""; + } + } + return str; + } + + /** 鏍¢獙瀛楃涓叉槸鍚︽暣鏁� */ + public static boolean checkStrIsInt(String str){ + if(StringUtils.isEmpty(str)){ + return false; + } + try{ + Integer.parseInt(str); + return true; + }catch (Exception e){ + return false; + } + } + + /** + * 瀛楃涓茶浆鏁村舰 + * @param str + * @param defInt 榛樿鏁存暟 + * @return + */ + public static int strChangeInt(String str, Integer defInt){ + if(defInt == null){ + defInt = 0; + } + if(StringUtils.isEmpty(str)){ + return defInt; + } + try{ + return Integer.parseInt(str); + }catch (Exception e){ + return defInt; + } + } +} diff --git a/hx_common/src/main/java/com/hx/util/OBSUtil.java b/hx_common/src/main/java/com/hx/util/OBSUtil.java new file mode 100644 index 0000000..87b0ea8 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/OBSUtil.java @@ -0,0 +1,156 @@ +package com.hx.util; + +import com.obs.services.ObsClient; +import com.obs.services.exception.ObsException; +import com.obs.services.model.HeaderResponse; +import com.obs.services.model.ObsBucket; +import com.obs.services.model.PutObjectResult; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.multipart.MultipartFile; + +import java.io.File; +import java.io.IOException; +import java.util.UUID; + +/**鍗庝负浜� OBS(OSS) + * @author ChenJiaHe + * @date 2021-05-06 + */ +public class OBSUtil { + + //log4j鏃ュ織 + private static Logger logger = LoggerFactory.getLogger(OBSUtil.class.getName()); + + /** 鍚庣璋冪敤涓婁紶鍥剧墖 + * @param localFile 鍥剧墖鏂囦欢 + * @param ak 璁块棶绉橀挜 + * @param sk 璁块棶绉橀挜 + * @param endPoint 鍖哄煙 + * @param bucketName 瀛樺偍妗� + * @param fileName 鏂囦欢鍚嶇О锛堝甫鍚庣紑锛夛紝涓虹┖鏃惰嚜鍔ㄧ敓鎴� + * @return + * @throws IOException + */ + public static PutObjectResult uploadImg(MultipartFile localFile,String ak,String sk,String endPoint,String bucketName,String folderName,String fileName) throws IOException { + + //娌℃湁鍚嶆鐨勬椂鍊欒嚜鍔ㄧ敓鎴� + if(StringUtils.isNull(fileName)){ + fileName = UUID.randomUUID().toString(); + if (localFile.getOriginalFilename().lastIndexOf(".") >= 0){ + fileName += localFile.getOriginalFilename().substring(localFile.getOriginalFilename().lastIndexOf(".")); + } + } + if(StringUtils.noNull(folderName)){ + fileName = folderName+"/"+fileName; + } + + PutObjectResult putObjectResult = null; + + //鍒濆鍖朞BS瀹㈡埛绔� + ObsClient obsClient = new ObsClient(ak, sk, endPoint); + try{ + putObjectResult = obsClient.putObject(bucketName,fileName , localFile.getInputStream()); + }catch (ObsException e){ + logger.error("鍗庝负浜� OBS 涓婁紶鏂囦欢鎶ラ敊 "); + logger.error("HTTP Code: " + e.getResponseCode()); + logger.error("Error Code:" + e.getErrorCode()); + logger.error("Error Message: " + e.getErrorMessage()); + + logger.error("Request ID:" + e.getErrorRequestId()); + logger.error("Host ID:" + e.getErrorHostId()); + e.printStackTrace(); + }finally { + if(obsClient != null){ + obsClient.close(); + } + } + + return putObjectResult; + } + + + /** 鍚庣璋冪敤涓婁紶鍥剧墖 + * @param localFile 瀛樺偍鏂囦欢 + * @param ak 璁块棶绉橀挜 + * @param sk 璁块棶绉橀挜 + * @param endPoint 鍖哄煙 + * @param bucketName 瀛樺偍妗� + * @param folderName 鏂囦欢澶瑰悕绉� + * @param fileName 鏂囦欢鍚嶇О锛堝甫鍚庣紑锛夛紝涓虹┖鏃惰嚜鍔ㄧ敓鎴� + * @return + * @throws IOException + */ + public static PutObjectResult uploadImg(File localFile,String ak,String sk,String endPoint,String bucketName,String folderName,String fileName) throws IOException { + + //娌℃湁鍚嶆鐨勬椂鍊欒嚜鍔ㄧ敓鎴� + if(StringUtils.isNull(fileName)){ + fileName = UUID.randomUUID().toString(); + if (localFile.getName().lastIndexOf(".") >= 0){ + fileName += localFile.getName().substring(localFile.getName().lastIndexOf(".")); + } + } + if(StringUtils.noNull(folderName)){ + fileName = folderName+"/"+fileName; + } + + PutObjectResult putObjectResult = null; + + //鍒濆鍖朞BS瀹㈡埛绔� + ObsClient obsClient = new ObsClient(ak, sk, endPoint); + try{ + putObjectResult = obsClient.putObject(bucketName, fileName, localFile); + }catch (ObsException e){ + logger.error("鍗庝负浜� OBS 涓婁紶鏂囦欢鎶ラ敊 "); + logger.error("HTTP Code: " + e.getResponseCode()); + logger.error("Error Code:" + e.getErrorCode()); + logger.error("Error Message: " + e.getErrorMessage()); + + logger.error("Request ID:" + e.getErrorRequestId()); + logger.error("Host ID:" + e.getErrorHostId()); + e.printStackTrace(); + }finally { + if(obsClient != null){ + obsClient.close(); + } + } + return putObjectResult; + + } + + /** 鍒涘缓妗� + * @param ak 璁块棶绉橀挜 + * @param sk 璁块棶绉橀挜 + * @param endPoint 鍖哄煙 + * @param bucketName 瀛樺偍妗� + * @return + * @throws IOException + */ + public static HeaderResponse createBucket(String ak,String sk,String endPoint,String bucketName) throws IOException { + + HeaderResponse response = null; + + //鍒濆鍖朞BS瀹㈡埛绔� + ObsClient obsClient = new ObsClient(ak, sk, endPoint); + try{ + response = obsClient.createBucket(bucketName); + }catch (ObsException e){ + + logger.error("鍗庝负浜� OBS 鍒涘缓妗舵姤閿� "); + logger.error("HTTP Code: " + e.getResponseCode()); + logger.error("Error Code:" + e.getErrorCode()); + logger.error("Error Message: " + e.getErrorMessage()); + + logger.error("Request ID:" + e.getErrorRequestId()); + logger.error("Host ID:" + e.getErrorHostId()); + e.printStackTrace(); + }finally { + if(obsClient != null){ + obsClient.close(); + } + } + return response; + } + + +} diff --git a/hx_common/src/main/java/com/hx/util/OSSUtil.java b/hx_common/src/main/java/com/hx/util/OSSUtil.java new file mode 100644 index 0000000..64228ec --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/OSSUtil.java @@ -0,0 +1,126 @@ +package com.hx.util; + +import com.aliyun.oss.OSSClient; +import com.aliyun.oss.model.OSSObject; +import org.springframework.web.multipart.MultipartFile; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; + +public class OSSUtil { + + private static OSSClient ossClient; + + public static OSSClient getOSSClient(String keyId, String keySecret, String endPoint) + { + if(ossClient == null) + { + ossClient = new OSSClient(endPoint, keyId, keySecret); + } + + return ossClient; + } + + /** 鍚庣璋冪敤涓婁紶鍥剧墖 */ + public static String uploadImg(String fileName, File imgFile, String keyId, String keySecret, String endPoint, String bucket) throws IOException { + + // // 鍘嬬缉鍒版枃浠跺す + // Thumbnails.of(imgFile).scale(1f).outputQuality(0.8f).toFile(SimpleToof.getRealpath("/upload/image/") + // + imgName); + // File file = new File(SimpleToof.getRealpath("/upload/image/") + imgName); + + // 鍒涘缓OSSClient瀹炰緥銆� + OSSClient ossClient = new OSSClient("https://" + endPoint, keyId, keySecret); + // 涓婁紶鏂囦欢銆�<yourLocalFile>鐢辨湰鍦版枃浠惰矾寰勫姞鏂囦欢鍚嶅寘鎷悗缂�缁勬垚锛屼緥濡�/users/local/myfile.txt銆� + // 鍒ゆ柇鍘嬬缉鍚庣殑澶у皬 + // if (file.length() > imgFile.length()) { + ossClient.putObject(bucket, fileName, imgFile); + // } else { + // ossClient.putObject(BUCKET, fileName, file); + // } + // 鍏抽棴OSSClient銆� + ossClient.shutdown(); + + return "https://" + bucket + "." + endPoint + "/" + fileName; + } + + /** 鍚庣璋冪敤涓婁紶鍥剧墖 */ + public static String uploadImg(String fileName, MultipartFile imgFile, String keyId, String keySecret, String endPoint, String bucket) { + + try { + // 鍒涘缓OSSClient瀹炰緥銆� + OSSClient ossClient = new OSSClient("https://" + endPoint, keyId, keySecret); + ossClient.putObject(bucket, fileName, imgFile.getInputStream()); + ossClient.shutdown(); + + return "https://" + bucket + "." + endPoint + "/" + fileName; + }catch (Exception e) + { + e.printStackTrace(); + return null; + } + } + + /** 鍚庣璋冪敤涓婁紶鍥剧墖 */ + public static String uploadImg(String fileName, InputStream is, String keyId, String keySecret, String endPoint, String bucket) { + + try { + // 鍒涘缓OSSClient瀹炰緥銆� + OSSClient ossClient = new OSSClient("https://" + endPoint, keyId, keySecret); + ossClient.putObject(bucket, fileName, is); + ossClient.shutdown(); + + return "https://" + bucket + "." + endPoint + "/" + fileName; + }catch (Exception e) + { + e.printStackTrace(); + return null; + } + } + + public static byte[] getObject(String key, String keyId, String keySecret, String endPoint, String bucket) { + + byte[] resultByte = null; + InputStream is = null; + ByteArrayOutputStream swapStream = null; + try { + OSSObject ossObject = getOSSClient(keyId, keySecret, endPoint).getObject(bucket, key); + is = ossObject.getObjectContent(); + swapStream = new ByteArrayOutputStream(); + byte[] buff = new byte[1024]; //buff鐢ㄤ簬瀛樻斁寰幆璇诲彇鐨勪复鏃舵暟鎹� + int rc = 0; + while ((rc = is.read(buff, 0, 1024)) > 0) { + swapStream.write(buff, 0, rc); + } + + resultByte = swapStream.toByteArray(); //in_b涓鸿浆鎹箣鍚庣殑缁撴灉 + + } catch (Exception e) { + e.printStackTrace(); + } finally { + if(is != null) + { + try { + is.close(); + } catch (IOException e) { + e.printStackTrace(); + } + is = null; + } + + if(swapStream != null) + { + try { + swapStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + swapStream = null; + } + } + + return resultByte; + } +} diff --git a/hx_common/src/main/java/com/hx/util/QRCodeUtil.java b/hx_common/src/main/java/com/hx/util/QRCodeUtil.java new file mode 100644 index 0000000..25fe7a3 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/QRCodeUtil.java @@ -0,0 +1,278 @@ +package com.hx.util; + +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.List; + +import javax.imageio.ImageIO; + +import com.google.zxing.*; + +import com.google.zxing.client.j2se.BufferedImageLuminanceSource; +import com.google.zxing.common.BitMatrix; +import com.google.zxing.common.HybridBinarizer; +import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; + +public class QRCodeUtil { + + // 浜岀淮鐮侀鑹�==榛戣壊 + private static final int BLACK = 0xFF000000; + // 浜岀淮鐮侀鑹�==鐧借壊 + private static final int WHITE = 0xFFFFFFFF; + // 浜岀淮鐮佸浘鐗囨牸寮�==jpg鍜宲ng涓ょ + private static final List<String> IMAGE_TYPE = new ArrayList<>(); + + static { + IMAGE_TYPE.add("jpg"); + IMAGE_TYPE.add("png"); + } + + /** + * zxing鏂瑰紡鐢熸垚浜岀淮鐮侊紙杩斿洖base64锛� + * 娉ㄦ剰锛� + * 1,鏂囨湰鐢熸垚浜岀淮鐮佺殑鏂规硶鐙珛鍑烘潵,杩斿洖image娴佺殑褰㈠紡,鍙互杈撳嚭鍒伴〉闈� + * 2,璁剧疆瀹归敊鐜囦负鏈�楂�,涓�鑸閿欑巼瓒婇珮,鍥剧墖瓒婁笉娓呮櫚, 浣嗘槸鍙湁灏嗗閿欑巼璁剧疆楂樹竴鐐规墠鑳藉吋瀹筶ogo鍥剧墖 + * 3,logo鍥剧墖榛樿鍗犱簩缁寸爜鍥剧墖鐨�20%,璁剧疆澶ぇ浼氬鑷存棤娉曡В鏋� + * + * @param content 浜岀淮鐮佸寘鍚殑鍐呭锛屾枃鏈垨缃戝潃 + * @param size 鐢熸垚鐨勪簩缁寸爜鍥剧墖灏哄 鍙互鑷畾涔夋垨鑰呴粯璁わ紙250锛� + * @param logoPath logo鐨勫瓨鏀句綅缃� + */ + public static String QRCodeCreate(String content, Integer size, String logoPath) { + ByteArrayOutputStream bos = null; + if(size == null){ + size = 400; + } + try{ + char[] rands = content.toCharArray(); + //鑾峰彇浜岀淮鐮佹祦鐨勫舰寮忥紝鍐欏叆鍒扮洰褰曟枃浠朵腑 + BufferedImage image = getBufferedImage(content, size, logoPath); + bos = new ByteArrayOutputStream(); + ImageIO.write(image, "JPEG", bos); + byte[] buf = bos.toByteArray(); + return "data:image/png;base64,"+Base64.getEncoder().encodeToString(buf); + }catch (Exception e){ + e.printStackTrace(); + }finally { + if(bos != null) { + try { + bos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + bos = null; + } + } + return null; + } + + /** + * zxing鏂瑰紡鐢熸垚浜岀淮鐮侊紙杩斿洖璺緞锛� + * 娉ㄦ剰锛� + * 1,鏂囨湰鐢熸垚浜岀淮鐮佺殑鏂规硶鐙珛鍑烘潵,杩斿洖image娴佺殑褰㈠紡,鍙互杈撳嚭鍒伴〉闈� + * 2,璁剧疆瀹归敊鐜囦负鏈�楂�,涓�鑸閿欑巼瓒婇珮,鍥剧墖瓒婁笉娓呮櫚, 浣嗘槸鍙湁灏嗗閿欑巼璁剧疆楂樹竴鐐规墠鑳藉吋瀹筶ogo鍥剧墖 + * 3,logo鍥剧墖榛樿鍗犱簩缁寸爜鍥剧墖鐨�20%,璁剧疆澶ぇ浼氬鑷存棤娉曡В鏋� + * + * @param content 浜岀淮鐮佸寘鍚殑鍐呭锛屾枃鏈垨缃戝潃 + * @param path 鐢熸垚鐨勪簩缁寸爜鍥剧墖瀛樻斁浣嶇疆 + * @param size 鐢熸垚鐨勪簩缁寸爜鍥剧墖灏哄 鍙互鑷畾涔夋垨鑰呴粯璁わ紙250锛� + * @param logoPath logo鐨勫瓨鏀句綅缃� + * @param autoDateFolder 鍦ㄥ瓨鏀鹃摼鎺ヤ笂鐢熸垚鏃ユ湡鏂囦欢澶癸紝鏍煎紡鏄痽yyyMM + */ + public static String QRCodeCreate(String content, String path, Integer size, String logoPath,Boolean autoDateFolder) { + try { + Date newDate = new Date(); + if(autoDateFolder){ + if(autoDateFolder){ + if(path.endsWith("/")){ + path = path+dateFormat(newDate,"yyyyMM")+"/"; + }else{ + path = path+"/"+dateFormat(newDate,"yyyyMM")+"/"; + } + } + } + + path = path+newDate.getTime()+".jpg"; + + //鍥剧墖绫诲瀷 + String imageType = "jpg"; + //鑾峰彇浜岀淮鐮佹祦鐨勫舰寮忥紝鍐欏叆鍒扮洰褰曟枃浠朵腑 + BufferedImage image = getBufferedImage(content, size, logoPath); + //鑾峰緱闅忔満鏁� + Random random = new Random(); + //鐢熸垚浜岀淮鐮佸瓨鏀炬枃浠� + File file = new File(path); + if (!file.exists()) { + file.mkdirs(); + } + ImageIO.write(image, imageType, file); + } catch (IOException e) { + e.printStackTrace(); + } + return path; + } + + /** + * 浜岀淮鐮佹祦鐨勫舰寮忥紝鍖呭惈鏂囨湰鍐呭 + * + * @param content 浜岀淮鐮佹枃鏈唴瀹� + * @param size 浜岀淮鐮佸昂瀵� + * @param logoPath logo鐨勫瓨鏀句綅缃� + * @return + */ + public static BufferedImage getBufferedImage(String content, Integer size, String logoPath) { + if (size == null || size <= 0) { + size = 250; + } + BufferedImage image = null; + try { + // 璁剧疆缂栫爜瀛楃闆� + Map<EncodeHintType, Object> hints = new HashMap<>(); + //璁剧疆缂栫爜 + hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); + //璁剧疆瀹归敊鐜囨渶楂� + hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); + hints.put(EncodeHintType.MARGIN, 1); + // 1銆佺敓鎴愪簩缁寸爜 + MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); + BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, size, size, hints); + // 2銆佽幏鍙栦簩缁寸爜瀹介珮 + int codeWidth = bitMatrix.getWidth(); + int codeHeight = bitMatrix.getHeight(); + // 3銆佸皢浜岀淮鐮佹斁鍏ョ紦鍐叉祦 + image = new BufferedImage(codeWidth, codeHeight, BufferedImage.TYPE_INT_RGB); + for (int i = 0; i < codeWidth; i++) { + for (int j = 0; j < codeHeight; j++) { + // 4銆佸惊鐜皢浜岀淮鐮佸唴瀹瑰畾鍏ュ浘鐗� + image.setRGB(i, j, bitMatrix.get(i, j) ? BLACK : WHITE); + } + } + //鍒ゆ柇鏄惁鍐欏叆logo鍥剧墖 + if (logoPath != null && !"".equals(logoPath)) { + File logoPic = new File(logoPath); + if (logoPic.exists()) { + Graphics2D g = image.createGraphics(); + BufferedImage logo = ImageIO.read(logoPic); + int widthLogo = logo.getWidth(null) > image.getWidth() * 2 / 10 ? (image.getWidth() * 2 / 10) : logo.getWidth(null); + int heightLogo = logo.getHeight(null) > image.getHeight() * 2 / 10 ? (image.getHeight() * 2 / 10) : logo.getHeight(null); + int x = (image.getWidth() - widthLogo) / 2; + int y = (image.getHeight() - heightLogo) / 2; + // 寮�濮嬬粯鍒跺浘鐗� + g.drawImage(logo, x, y, widthLogo, heightLogo, null); + g.drawRoundRect(x, y, widthLogo, heightLogo, 15, 15); + //杈规瀹藉害 + g.setStroke(new BasicStroke(2)); + //杈规棰滆壊 + g.setColor(Color.WHITE); + g.drawRect(x, y, widthLogo, heightLogo); + g.dispose(); + logo.flush(); + image.flush(); + } + } + } catch (WriterException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + return image; + } + + /** + * 缁欎簩缁寸爜鍥剧墖娣诲姞Logo + * + * @param qrPic 浜岀淮鐮佸浘鐗� + * @param logoPic logo鍥剧墖 + * @param path 鍚堟垚鍚庣殑鍥剧墖瀛樺偍鐩綍 + */ + public static boolean zxingCodeCreate(File qrPic, File logoPic, String path) { + try { + String imageType = path.substring(path.lastIndexOf(".") + 1).toLowerCase(); + if (!IMAGE_TYPE.contains(imageType)) { + return false; + } + + if (!qrPic.isFile() && !logoPic.isFile()) { + return false; + } + + //璇诲彇浜岀淮鐮佸浘鐗囷紝骞舵瀯寤虹粯鍥惧璞� + BufferedImage image = ImageIO.read(qrPic); + Graphics2D g = image.createGraphics(); + //璇诲彇Logo鍥剧墖 + BufferedImage logo = ImageIO.read(logoPic); + //璁剧疆logo鐨勫ぇ灏�,鏈�澶�20%0 + int widthLogo = logo.getWidth(null) > image.getWidth() * 2 / 10 ? (image.getWidth() * 2 / 10) : logo.getWidth(null); + int heightLogo = logo.getHeight(null) > image.getHeight() * 2 / 10 ? (image.getHeight() * 2 / 10) : logo.getHeight(null); + // 璁$畻鍥剧墖鏀剧疆浣嶇疆锛岄粯璁ゅ湪涓棿 + int x = (image.getWidth() - widthLogo) / 2; + int y = (image.getHeight() - heightLogo) / 2; + // 寮�濮嬬粯鍒跺浘鐗� + g.drawImage(logo, x, y, widthLogo, heightLogo, null); + g.drawRoundRect(x, y, widthLogo, heightLogo, 15, 15); + //杈规瀹藉害 + g.setStroke(new BasicStroke(2)); + //杈规棰滆壊 + g.setColor(Color.WHITE); + g.drawRect(x, y, widthLogo, heightLogo); + g.dispose(); + logo.flush(); + image.flush(); + File newFile = new File(path); + if (!newFile.exists()) { + newFile.mkdirs(); + } + ImageIO.write(image, imageType, newFile); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + + /** + * 浜岀淮鐮佺殑瑙f瀽鏂规硶 + * + * @param path 浜岀淮鐮佸浘鐗囩洰褰� + * @return + */ + public static Result zxingCodeAnalyze(String path) { + try { + MultiFormatReader formatReader = new MultiFormatReader(); + File file = new File(path); + if (file.exists()) { + BufferedImage image = ImageIO.read(file); + LuminanceSource source = new BufferedImageLuminanceSource(image); + Binarizer binarizer = new HybridBinarizer(source); + BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer); + Map hints = new HashMap(); + hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); + Result result = formatReader.decode(binaryBitmap, hints); + return result; + } + } catch (IOException e) { + e.printStackTrace(); + } catch (NotFoundException e) { + e.printStackTrace(); + } + return null; + } + + /** + * + * @param date 鏃堕棿 + * @param format 鏃堕棿鏍煎紡 + * @return 杩斿洖鐨勬椂闂存牸寮忓瓧绗︿覆 + */ + public static String dateFormat(Date date,String format) { + SimpleDateFormat df = new SimpleDateFormat(format);//璁剧疆鏃ユ湡鏍煎紡 + return df.format(date); + } + +} diff --git a/hx_common/src/main/java/com/hx/util/RegValidatorUtil.java b/hx_common/src/main/java/com/hx/util/RegValidatorUtil.java new file mode 100644 index 0000000..f74fb0b --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/RegValidatorUtil.java @@ -0,0 +1,272 @@ +package com.hx.util; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * 姝e垯琛ㄨ揪寮忛獙璇佸伐锟�? + * @author mgchen + * + */ +public class RegValidatorUtil { + + /**鎵嬫満鍙锋鍒欏垵濮嬪寲*/ + public static Pattern pattern = Pattern.compile("^1[3-9]\\d{9}$"); + + /** + * 楠岃瘉閭 + * + * @param str 寰呴獙璇佺殑瀛楃 + * @return 濡傛灉鏄鍚堢殑瀛楃锟�?,杩斿洖 <b>true </b>,鍚﹀垯锟�? <b>false </b> + */ + public static boolean isEmail(String str) { + String regex = "^([\\w-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([\\w-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$"; + return match(regex, str); + } + + /** + * 楠岃瘉IP鍦板潃 + * + * @param str 寰呴獙璇佺殑瀛楃锟�? + * @return 濡傛灉鏄鍚堟牸寮忕殑瀛楃锟�?,杩斿洖 <b>true </b>,鍚﹀垯锟�? <b>false </b> + */ + public static boolean isIP(String str) { + String num = "(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)"; + String regex = "^" + num + "\\." + num + "\\." + num + "\\." + num + "$"; + return match(regex, str); + } + + /** + * 楠岃瘉缃戝潃Url + * + * @param str 寰呴獙璇佺殑瀛楃锟�? + * @return 濡傛灉鏄鍚堟牸寮忕殑瀛楃锟�?,杩斿洖 <b>true </b>,鍚﹀垯锟�? <b>false </b> + */ + public static boolean IsUrl(String str) { + String regex = "http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?"; + return match(regex, str); + } + + /** + * 楠岃瘉鐢佃瘽鍙风爜 + * + * @param str 寰呴獙璇佺殑瀛楃锟�? + * @return 濡傛灉鏄鍚堟牸寮忕殑瀛楃锟�?,杩斿洖 <b>true </b>,鍚﹀垯锟�? <b>false </b> + */ + public static boolean IsTelephone(String str) { + String regex = "^(\\d{3,4}-)?\\d{6,8}$"; + return match(regex, str); + } + + /** + * 楠岃瘉杈撳叆瀵嗙爜鏉′欢(瀛楃涓庢暟鎹悓鏃跺嚭锟�?) + * + * @param str 寰呴獙璇佺殑瀛楃锟�? + * @return 濡傛灉鏄鍚堟牸寮忕殑瀛楃锟�?,杩斿洖 <b>true </b>,鍚﹀垯锟�? <b>false </b> + */ + public static boolean IsPassword(String str) { + String regex = "[A-Za-z0-9]+"; + return match(regex, str); + } + + /** + * 楠岃瘉杈撳叆瀵嗙爜闀垮害 (6-18锟�?) + * + * @param str 寰呴獙璇佺殑瀛楃锟�? + * @return 濡傛灉鏄鍚堟牸寮忕殑瀛楃锟�?,杩斿洖 <b>true </b>,鍚﹀垯锟�? <b>false </b> + */ + public static boolean IsPasswLength(String str) { + String regex = "^\\d{6,18}$"; + return match(regex, str); + } + + /** + * 楠岃瘉杈撳叆閭斂缂栧彿 + * + * @param str 寰呴獙璇佺殑瀛楃锟�? + * @return 濡傛灉鏄鍚堟牸寮忕殑瀛楃锟�?,杩斿洖 <b>true </b>,鍚﹀垯锟�? <b>false </b> + */ + public static boolean IsPostalcode(String str) { + String regex = "^\\d{6}$"; + return match(regex, str); + } + + /**鏍¢獙鎵嬫満鍙风爜 + * @param phoneNumber 鎵嬫満鍙� + * @return 鏍¢獙缁撴灉 + */ + public static boolean IsHandset(String phoneNumber) { + if ((phoneNumber != null) && (!phoneNumber.isEmpty())) { + Matcher m = pattern.matcher(phoneNumber); + return m.matches(); + } + return false; + } + + /** + * 楠岃瘉杈撳叆韬唤璇佸彿 + * + * @param str 寰呴獙璇佺殑瀛楃锟�? + * @return 濡傛灉鏄鍚堟牸寮忕殑瀛楃锟�?,杩斿洖 <b>true </b>,鍚﹀垯锟�? <b>false </b> + */ + public static boolean IsIDcard(String str) { + String regex = "(^\\d{18}$)|(^\\d{15}$)"; + return match(regex, str); + } + + /** + * 楠岃瘉杈撳叆涓や綅灏忔暟 + * + * @param str 寰呴獙璇佺殑瀛楃锟�? + * @return 濡傛灉鏄鍚堟牸寮忕殑瀛楃锟�?,杩斿洖 <b>true </b>,鍚﹀垯锟�? <b>false </b> + */ + public static boolean IsDecimal(String str) { + String regex = "^[0-9]+(.[0-9]{2})?$"; + return match(regex, str); + } + + /** + * 楠岃瘉杈撳叆锟�?骞寸殑12涓湀 + * + * @param str 寰呴獙璇佺殑瀛楃锟�? + * @return 濡傛灉鏄鍚堟牸寮忕殑瀛楃锟�?,杩斿洖 <b>true </b>,鍚﹀垯锟�? <b>false </b> + */ + public static boolean IsMonth(String str) { + String regex = "^(0?[[1-9]|1[0-2])$"; + return match(regex, str); + } + + /** + * 楠岃瘉杈撳叆锟�?涓湀锟�?31锟�? + * + * @param str 寰呴獙璇佺殑瀛楃锟�? + * @return 濡傛灉鏄鍚堟牸寮忕殑瀛楃锟�?,杩斿洖 <b>true </b>,鍚﹀垯锟�? <b>false </b> + */ + public static boolean IsDay(String str) { + String regex = "^((0?[1-9])|((1|2)[0-9])|30|31)$"; + return match(regex, str); + } + + /** + * 楠岃瘉鏃ユ湡鏃堕棿 + * + * @param str 寰呴獙璇佺殑瀛楃锟�? + * @return 濡傛灉鏄鍚堢綉锟�?鏍煎紡鐨勫瓧绗︿覆,杩斿洖 <b>true </b>,鍚﹀垯锟�? <b>false </b> + */ + public static boolean isDate(String str) { + // 涓ユ牸楠岃瘉鏃堕棿鏍煎紡锟�?(鍖归厤[2002-01-31], [1997-04-30], + // [2004-01-01])涓嶅尮锟�?([2002-01-32], [2003-02-29], [04-01-01]) + // String regex = + // "^((((19|20)(([02468][048])|([13579][26]))-02-29))|((20[0-9][0-9])|(19[0-9][0-9]))-((((0[1-9])|(1[0-2]))-((0[1-9])|(1\\d)|(2[0-8])))|((((0[13578])|(1[02]))-31)|(((01,3-9])|(1[0-2]))-(29|30)))))$"; + // 娌″姞鏃堕棿楠岃瘉鐨刌YYY-MM-DD + // String regex = + // "^((((1[6-9]|[2-9]\\d)\\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\\d|3[01]))|(((1[6-9]|[2-9]\\d)\\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\\d|30))|(((1[6-9]|[2-9]\\d)\\d{2})-0?2-(0?[1-9]|1\\d|2[0-8]))|(((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$"; + // 鍔犱簡鏃堕棿楠岃瘉鐨刌YYY-MM-DD 00:00:00 + String regex = "^((((1[6-9]|[2-9]\\d)\\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\\d|3[01]))|(((1[6-9]|[2-9]\\d)\\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\\d|30))|(((1[6-9]|[2-9]\\d)\\d{2})-0?2-(0?[1-9]|1\\d|2[0-8]))|(((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-)) (20|21|22|23|[0-1]?\\d):[0-5]?\\d:[0-5]?\\d$"; + return match(regex, str); + } + + /** + * 楠岃瘉鏁板瓧杈撳叆 + * + * @param str 寰呴獙璇佺殑瀛楃锟�? + * @return 濡傛灉鏄鍚堟牸寮忕殑瀛楃锟�?,杩斿洖 <b>true </b>,鍚﹀垯锟�? <b>false </b> + */ + public static boolean IsNumber(String str) { + String regex = "^[0-9]*$"; + return match(regex, str); + } + + /** + * 楠岃瘉闈為浂鐨勬鏁存暟 + * + * @param str 寰呴獙璇佺殑瀛楃锟�? + * @return 濡傛灉鏄鍚堟牸寮忕殑瀛楃锟�?,杩斿洖 <b>true </b>,鍚﹀垯锟�? <b>false </b> + */ + public static boolean IsIntNumber(String str) { + String regex = "^[1-9][0-9]*$"; + return match(regex, str); + } + + /** + * 楠岃瘉澶у啓瀛楁瘝 + * + * @param str 寰呴獙璇佺殑瀛楃锟�? + * @return 濡傛灉鏄鍚堟牸寮忕殑瀛楃锟�?,杩斿洖 <b>true </b>,鍚﹀垯锟�? <b>false </b> + */ + public static boolean IsUpChar(String str) { + String regex = "^[A-Z]+$"; + return match(regex, str); + } + + /** + * 楠岃瘉灏忓啓瀛楁瘝 + * + * @param str 寰呴獙璇佺殑瀛楃锟�? + * @return 濡傛灉鏄鍚堟牸寮忕殑瀛楃锟�?,杩斿洖 <b>true </b>,鍚﹀垯锟�? <b>false </b> + */ + public static boolean IsLowChar(String str) { + String regex = "^[a-z]+$"; + return match(regex, str); + } + + /** + * 楠岃瘉楠岃瘉杈撳叆瀛楁瘝 + * + * @param str 寰呴獙璇佺殑瀛楃锟�? + * @return 濡傛灉鏄鍚堟牸寮忕殑瀛楃锟�?,杩斿洖 <b>true </b>,鍚﹀垯锟�? <b>false </b> + */ + public static boolean IsLetter(String str) { + String regex = "^[A-Za-z]+$"; + return match(regex, str); + } + + /** + * 楠岃瘉楠岃瘉杈撳叆姹夊瓧 + * + * @param str 寰呴獙璇佺殑瀛楃锟�? + * @return 濡傛灉鏄鍚堟牸寮忕殑瀛楃锟�?,杩斿洖 <b>true </b>,鍚﹀垯锟�? <b>false </b> + */ + public static boolean IsChinese(String str) { + String regex = "^[\u4e00-\u9fa5],{0,}$"; + return match(regex, str); + } + + /** + * 楠岃瘉楠岃瘉杈撳叆瀛楃锟�? + * + * @param str 寰呴獙璇佺殑瀛楃锟�? + * @return 濡傛灉鏄鍚堟牸寮忕殑瀛楃锟�?,杩斿洖 <b>true </b>,鍚﹀垯锟�? <b>false </b> + */ + public static boolean IsLength(String str) { + String regex = "^.{8,}$"; + return match(regex, str); + } + + /** + * 鍒ゆ柇瀛楃涓叉槸涓嶆槸double鍨� + * @param str + * @return + */ + public static boolean isNumeric(String str){ + Pattern pattern = Pattern.compile("[0-9]+[.]{0,1}[0-9]*[dD]{0,1}"); + Matcher isNum = pattern.matcher(str); + if( !isNum.matches() ){ + return false; + } + return true; + } + + /** + * @param regex + * 姝e垯琛ㄨ揪寮忓瓧绗︿覆 + * @param str + * 瑕佸尮閰嶇殑瀛楃锟�? + * @return 濡傛灉str 绗﹀悎 regex鐨勬鍒欒〃杈惧紡鏍煎紡,杩斿洖true, 鍚﹀垯杩斿洖 false; + */ + private static boolean match(String regex, String str) { + Pattern pattern = Pattern.compile(regex); + Matcher matcher = pattern.matcher(str); + return matcher.matches(); + } +} diff --git a/hx_common/src/main/java/com/hx/util/RequestMethod.java b/hx_common/src/main/java/com/hx/util/RequestMethod.java new file mode 100644 index 0000000..6aa7102 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/RequestMethod.java @@ -0,0 +1,197 @@ +package com.hx.util; + +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class RequestMethod { + + /** + * 鍙戦�丳ost璇锋眰 + * @param path 璇锋眰璺緞 + * @param params 璇锋眰鍙傛暟 + * @param encoding 缂栫爜 + * @return 鏈嶅姟鍣ㄧ鍐呭 + */ + public static String sendPOSTRequest(String path, Map<String, String> params, String encoding) throws Exception{ + StringBuilder data = new StringBuilder(); + if(params!=null && !params.isEmpty()){ + for(Map.Entry<String, String> entry : params.entrySet()){ + data.append(entry.getKey()).append("="); + data.append(URLEncoder.encode(entry.getValue(), encoding)); + data.append("&"); + } + data.deleteCharAt(data.length() - 1); + } + byte[] entity = data.toString().getBytes();//鐢熸垚瀹炰綋鏁版嵁 + HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection(); + conn.setConnectTimeout(5000); + conn.setRequestMethod("POST"); + conn.setDoOutput(true);//鍏佽瀵瑰杈撳嚭鏁版嵁 + conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); + conn.setRequestProperty("Content-Length", String.valueOf(entity.length)); + OutputStream outStream = conn.getOutputStream(); + outStream.write(entity); + if(conn.getResponseCode() == 200){ + return StreamUtils.InputStreamTOString(conn.getInputStream()) ; + } + return null; + } + + /** + * 鍙戦�丳ost璇锋眰 + * @param path 璇锋眰璺緞 + * @param content 鍙戦�佸唴瀹� + * @param encoding 缂栫爜 + * @return 鏈嶅姟鍣ㄧ鍐呭 + */ + public static String sendPOSTRequest(String path, String content, String encoding){ + //byte[] entity = content.toString().getBytes();//鐢熸垚瀹炰綋鏁版嵁 + try{ + HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection(); + conn.setConnectTimeout(5000); + conn.setRequestMethod("POST"); + conn.setDoOutput(true);//鍏佽瀵瑰杈撳嚭鏁版嵁 + conn.setDoInput(true); + conn.setUseCaches(false); + conn.setRequestProperty("Charset", encoding); + conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); + //conn.setRequestProperty("Content-Length", String.valueOf(entity.length)); + OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream(),"UTF-8"); + outStream.write(content); + outStream.flush(); + if(conn.getResponseCode() == 200){ + return StreamUtils.InputStreamTOString(conn.getInputStream()); + } + }catch(Exception e){ + e.printStackTrace(); + } + return null; + } + + /** + * 鍙戦�丳ost璇锋眰 + * @param path 璇锋眰璺緞 + * @param content 鍙戦�佸唴瀹� + * @param header 璇锋眰澶村弬鏁拌缃� + * @param contentType 璇锋眰绫诲瀷锛岄粯璁pplication/x-www-form-urlencoded + * @param encoding 缂栫爜锛岄粯璁TF-8 + * @return 鏈嶅姟鍣ㄧ鍐呭 + */ + public static String sendPOSTRequest(String path, String content,Map<String,String> header,String contentType, String encoding){ + //byte[] entity = content.toString().getBytes();//鐢熸垚瀹炰綋鏁版嵁 + try{ + if(StringUtils.isNull(contentType)){ + contentType = "application/x-www-form-urlencoded"; + } + if(StringUtils.isNull(encoding)){ + encoding = "UTF-8"; + } + + HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection(); + conn.setConnectTimeout(5000); + conn.setRequestMethod("POST"); + conn.setDoOutput(true);//鍏佽瀵瑰杈撳嚭鏁版嵁 + conn.setDoInput(true); + conn.setUseCaches(false); + conn.setRequestProperty("Charset", encoding); + conn.setRequestProperty("Content-Type",contentType); + if(header != null){ + for(String key:header.keySet()){//keySet鑾峰彇map闆嗗悎key鐨勯泦鍚� 鐒跺悗鍦ㄩ亶鍘唊ey鍗冲彲 + conn.setRequestProperty(key,header.get(key)); + } + } + //conn.setRequestProperty("Content-Length", String.valueOf(entity.length)); + OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream(),"UTF-8"); + outStream.write(content); + outStream.flush(); + if(conn.getResponseCode() == 200){ + return StreamUtils.InputStreamTOString(conn.getInputStream()); + } + }catch(Exception e){ + e.printStackTrace(); + } + return null; + } + + /** + * 鍙戦�丳ost璇锋眰 + * @param path 璇锋眰璺緞 + * @param entity 鍙戦�佸唴瀹� + * @param encoding 缂栫爜 + * @return 鏈嶅姟鍣ㄧ鍐呭 + */ + public static String sendPOSTRequest(String path, byte[] entity, String encoding) throws Exception{ + System.out.println("entity:" + entity.length); + HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection(); + conn.setConnectTimeout(5000); + conn.setRequestMethod("POST"); + conn.setDoOutput(true);//鍏佽瀵瑰杈撳嚭鏁版嵁 + conn.setRequestProperty("Content-Type", "application/octet-stream"); + conn.setRequestProperty("Accept", "application/octet-stream"); + conn.setRequestProperty("Content-Length", String.valueOf(entity.length)); + OutputStream outStream = conn.getOutputStream(); + outStream.write(entity); + if(conn.getResponseCode() == 200){ + return StreamUtils.InputStreamTOString(conn.getInputStream()); + } + return null; + } + + /** + * 鍙戦�丟ET璇锋眰 + * @param path 璇锋眰璺緞 + * @param params 璇锋眰鍙傛暟 + * @return 鏈嶅姟鍣ㄧ鍐呭 + */ + public static String sendGETRequest(String path, Map<String, String> params, String ecoding) throws Exception{ + // http://192.168.1.100:8080/web/ManageServlet?title=xxx&timelength=90 + StringBuilder url = new StringBuilder(path); + if(params!=null){ + url.append("?"); + for(Map.Entry<String, String> entry : params.entrySet()){ + url.append(entry.getKey()).append("="); + url.append(URLEncoder.encode(entry.getValue(), ecoding)); + url.append("&"); + } + url.deleteCharAt(url.length() - 1); + } + HttpURLConnection conn = (HttpURLConnection)new URL(url.toString()).openConnection(); + conn.setConnectTimeout(5000); + conn.setRequestMethod("GET"); + if(conn.getResponseCode() == 200){ + return StreamUtils.InputStreamTOString(conn.getInputStream()) ; + } + return null; + } + + + + public static String msg(InputStream in) throws Exception{ + BufferedReader br = new BufferedReader(new InputStreamReader(in)); + String line; + List<String> lines = new ArrayList<String>(); + while((line = br.readLine())!=null){ + lines.add(line); + } + if(lines.size()>0){ + String f = lines.get(0); + if(f.indexOf("200")!=-1){ + String e = lines.get(lines.size()-1); + return e; + }else{ + return null; + } + }else{ + return null; + } + } +} diff --git a/hx_common/src/main/java/com/hx/util/SerializeUtil.java b/hx_common/src/main/java/com/hx/util/SerializeUtil.java new file mode 100644 index 0000000..07bbb47 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/SerializeUtil.java @@ -0,0 +1,72 @@ +package com.hx.util; + +import org.springframework.stereotype.Component; + +import java.io.*; +import java.net.URLDecoder; +import java.net.URLEncoder; + +/** + * @PackageName com.hx.util + * @ProjectName hx-parent + * @Author: ChenJiaHe + * @Date: Create in 16:52 2019/7/22 + * @Description: + * @Copyright Copyright (c) 2019, hx01@163.com All Rights Reserved. + */ +@Component +public class SerializeUtil<E> { + + public String serialize(E object) { + ObjectOutputStream oos = null; + ByteArrayOutputStream baos = null; + try { + baos = new ByteArrayOutputStream(); + oos = new ObjectOutputStream(baos); + oos.writeObject(object); + + String str = baos.toString("ISO-8859-1"); + return URLEncoder.encode(str, "UTF-8"); + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + baos.close(); + oos.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + return null; + } + + @SuppressWarnings("unchecked") + public E unserialize(String serializeStr) { + String readStr = ""; + if (serializeStr == null || "".equals(serializeStr)) { + return null; + } + try { + readStr = URLDecoder.decode(serializeStr, "UTF-8"); + } catch (Exception e) { + e.printStackTrace(); + } + ObjectInputStream ois = null; + InputStream bais = null; + try { + bais = new ByteArrayInputStream(readStr.getBytes("ISO-8859-1")); + ois = new ObjectInputStream(bais); + return (E) ois.readObject(); + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + ois.close(); + bais.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + return null; + } +} diff --git a/hx_common/src/main/java/com/hx/util/SimpleEncrypt.java b/hx_common/src/main/java/com/hx/util/SimpleEncrypt.java new file mode 100644 index 0000000..88f48a2 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/SimpleEncrypt.java @@ -0,0 +1,95 @@ +package com.hx.util; + +import java.util.*; + +/*** + * 锟�?鍗曠殑鍔犲瘑绋嬪簭锛屽拰瑙e瘑绋嬪簭 + * + * @author mq.c + * + */ +public class SimpleEncrypt { + + /** + * 鑾峰彇鎸囧畾闀垮害闅忔満鐨勫瓧绗︿覆 + * + * @param getNum + * @return + */ + private static String generateCheckCode(Integer getNum) { + // abcdefghijklmnopqrstuvwxyz + // String chars = + // "123456789.AB2CD3EF7G;HI5JK5LMN/OPQR8ST.UVW7X9YZ?~!@#$%^&*()_+{}:>?<|/.,';][=-"; + // String chars = + // "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~!@#$%^&*()_+{}|:<>?/.,';][\\=-"; + String chars = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789abcdefghijklmnopqrstuvwxyz._?"; + String[] charsx = chars.split(""); + // String[] charsx = chars.split(""); + List<String> list = Arrays.asList(charsx); + Collections.shuffle(list); + StringBuffer buff = new StringBuffer(); + Random random = new Random(); + for (int i = 0; i < getNum; i++) { + int rand = random.nextInt(list.size()); + // buff.append(chars.charAt(rand)); + buff.append(list.get(rand)); + } + return buff.toString(); + } + + /** + * 瀵瑰瓧绗︿覆杩涜绠�鏄撳姞瀵�(涓嶈鍦ㄦ剰閭g寰堝鏄撹浜虹牬瑙g殑灏忕粏鑺�) + * 璇ュ姞瀵嗛噰鐢�"鍓嶉潰13浣嶉殢鏈虹爜"+dataString+"鍚�9浣嶉殢鏈虹爜"锛岀粍鎷兼垚涓�涓瓧绗︿覆锛岃繘琛孊ASE64鍔犲瘑寰楀嚭鐨勫姞瀵嗗�� + * + * @param dataString + * 瑕佽繘琛屽姞瀵嗙殑鏁版嵁婧� + * @return + */ + public static String simpleEnCode(String dataString) { + // 缁勬嫾闅忔満鍊� + String ranString = generateCheckCode(13).toString() + dataString + generateCheckCode(9).toString(); + String enCode = new String(Base64.getEncoder().encode(ranString.getBytes())); + return enCode; + } + + /*** + * 瀵圭敤com.bang.units.SimpleEncrypt.simpleEnCode鍔犲瘑杩囩殑瀛楃涓茶繘琛岃В瀵� + * + * 璇ュ姞瀵嗛噰鐢�"鍓嶉潰13浣嶉殢鏈虹爜"+dataString+"鍚�9浣嶉殢鏈虹爜"锛岀粍鎷兼垚涓�涓瓧绗︿覆锛岃繘琛孊ASE64鍔犲瘑寰楀嚭鐨勫姞瀵嗗�� + * + * @param dataString + * 瑕佽繘琛岃В瀵嗙殑鏁版嵁婧� + * @return + */ + public static String simpleDeCode(String dataString) throws Exception { + // 杩涜瑙e瘑sun.misc.BASE64Decoder.BASE64Decoder() + + byte[] enCode = Base64.getDecoder().decode(dataString); + // 瑙e緱闅忔満鍊� + String ranString = new String(enCode); + + // System.out.println("simpleDeCode:" + ranString); + // 鎴彇鍑烘湁鏁堜綅缃弬鏁� + String daString = ranString.substring(13, ranString.length() - 9); + + return daString; + } + + public static void main(String[] args) throws Exception { + String chars = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ?~!@#$%^&*()_+{}:>?<|/.,';][=-`"; + String[] charsx = chars.split(""); + List<String> list = Arrays.asList(charsx); + Collections.shuffle(list); + // for (String string : list) { + // System.out.println(string); + // } + + String str = "15648sadf"; + String eStr = simpleEnCode(str); + System.out.println(eStr); + String dStr = simpleDeCode(eStr); + System.out.println(dStr); + + } + +} diff --git a/hx_common/src/main/java/com/hx/util/SimpleTool.java b/hx_common/src/main/java/com/hx/util/SimpleTool.java new file mode 100644 index 0000000..eccf481 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/SimpleTool.java @@ -0,0 +1,1097 @@ +package com.hx.util; + +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.net.FileNameMap; +import java.net.HttpURLConnection; +import java.net.InetAddress; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLDecoder; +import java.net.UnknownHostException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Timestamp; +import java.text.DateFormat; +import java.text.DecimalFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.io.IOUtils; +import org.apache.poi.hssf.usermodel.HSSFCell; +import org.apache.poi.hssf.usermodel.HSSFDataFormatter; +import org.apache.poi.hssf.usermodel.HSSFDateUtil; +import org.apache.poi.hssf.usermodel.HSSFRow; +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.ss.usermodel.Cell; + +import net.sf.json.JSONArray; +import net.sf.json.JSONException; +import net.sf.json.JSONObject; +import net.sourceforge.pinyin4j.PinyinHelper; +import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat; +import net.sourceforge.pinyin4j.format.HanyuPinyinToneType; +import org.apache.poi.ss.usermodel.CellType; +import org.springframework.cglib.beans.BeanMap; + +public class SimpleTool { + + public static SimpleDateFormat myformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + public static DecimalFormat fmt = new DecimalFormat("0.00"); + public static Byte[] lock = new Byte[] {0}; + + /**瀵硅薄杞琺ap*/ + public static Map<?, ?> objectToMap(Object obj) { + if(obj == null) + return null; + + return new org.apache.commons.beanutils.BeanMap(obj); + } + + /** + * 灏嗗璞¤鎹负map + * + * @param bean + * @return + */ + public static <T> Map<String, Object> beanToMap(T bean) { + Map<String, Object> map = new HashMap<>(); + if (bean != null) { + BeanMap beanMap = BeanMap.create(bean); + for (Object key : beanMap.keySet()) { + map.put(key + "", beanMap.get(key)); + } + } + return map; + } + + /** + * 灏嗗璞¤鎹负map + * + * @param bean + * @return + */ + public static Map<String, String> beanToMapS(Object bean) { + Map<String, String> map = new HashMap<>(); + if (bean != null) { + BeanMap beanMap = BeanMap.create(bean); + for (Object key : beanMap.keySet()) { + if(beanMap.get(key) != null){ + map.put(key + "", beanMap.get(key).toString()); + }else{ + map.put(key + "", ""); + } + } + } + return map; + } + + + /** + * 鍚庡彴鏍煎紡鏋勫缓杩斿洖鍊兼牸寮忓垪琛�-鍚庡彴鑾峰彇鍒楄〃 + * @param count 杩斿洖鎬绘潯鏁� + * @return JSONObject 鐗瑰畾鏍煎紡鐨凧SONObject + */ + public static JSONObject resAdminLsit(Integer status,String errMsg,JSONArray arr,Integer count){ + + JSONObject fObj = new JSONObject(); + try{ + fObj.put("code", status); + fObj.put("count", count); + fObj.put("msg", errMsg); + fObj.put("data", arr); + }catch (Exception e) { + e.printStackTrace(); + } + return fObj; + } + + /** + * 鑾峰彇鎸囧畾鏍煎紡鐨凞ouble 绫诲瀷鏁版嵁 + * + * @param type + * 杞崲鏍煎紡鐨勭被鍨� 榛樿涓� "#.#" + * @param e + * 瑕佽浆鎹㈢殑鏁版嵁婧� + **/ + public static Double getTypeDouble(String type, Double e) { + if (!checkNotNull(type)) + type = "0.00"; + fmt = new DecimalFormat(type); + fmt.setRoundingMode(RoundingMode.HALF_UP); // 淇濈暀灏忔暟鐐瑰悗涓や綅骞跺洓鑸嶄簲鍏ワ紝纭繚浠烽挶鍑嗙‘ + Double d = Double.valueOf(fmt.format(e)); + return d; + } + + /** + * 棣栧瓧姣嶅ぇ鍐� + * + * @param str + */ + public static String capitalized(String str) { + if ("".equals(str.trim()) || str == null) { + return ""; + } + String key = str.substring(0, 1).toUpperCase(); + String keys = key + str.substring(1, str.length()); + return keys; + } + + /** 鍒ゆ柇鍙傛暟鏄惁涓簄ull锛屽鏋渘ull鎶涘嚭瀵瑰簲寮傚父 */ + public static void checkErrMsg(Object obj, String errMsg) { + if (!checkNotNull(obj)) + throw new RuntimeException(errMsg); + } + + /*** 鍒涘缓鏂囦欢锛堣嚜鍔ㄧ敓鎴愭枃浠跺す銆傦級(闇�瑕佺湡瀹炶矾寰�) **/ + public static File createFile(String mkdirPath, String fileName) throws IOException { + System.out.println(mkdirPath + fileName); + // mkdirPath = + // "E:\\work\\soft\\MyEclipse\\apache-tomcat-7.0.61\\webapps\\ROOT\\"; + + File f = new File(mkdirPath); + if (!f.exists()) { + f.mkdirs(); + } + File file = new File(f, fileName); + if (!file.exists()) { + file.createNewFile(); + } + + // System.out.println(file.getAbsolutePath()); + return file; + } + + /** + * 鏋勫缓杩斿洖鍊兼牸寮� + * + * @param status + * 杩斿洖鐘舵�� + * @param errMsg + * 杩斿洖闄勫甫淇℃伅 + * @param inf + * 杩斿洖瀹炰綋鍊� + * @return JSONObject 鐗瑰畾鏍煎紡鐨凧SONObject + */ + public static JSONObject res(Integer status, String errMsg, JSONObject inf) { + JSONObject res = new JSONObject(); + JSONObject fObj = new JSONObject(); + try { + res.put("status", status); + res.put("errMsg", errMsg); + + fObj.put("res", res); + fObj.put("inf", inf); + } catch (Exception e) { + e.printStackTrace(); + } + return fObj; + } + + /** + * Date绫诲瀷杞崲涓�10浣嶆椂闂存埑 + * + * @param time + * @return + */ + public static Integer DateToTimestamp(Date time) { + Timestamp ts = new Timestamp(time.getTime()); + return (int) ((ts.getTime()) / 1000); + } + + /** 鍒ゆ柇褰撳墠鏃堕棿鏄粈涔堟椂鍊� **/ + public static Boolean IsTime(Date date, Integer year, Integer month, Integer day, Integer hour, Integer minute) { + Calendar cal = new GregorianCalendar(); + cal.setTime(date); + if (year != null) { + int iyear = cal.get(Calendar.YEAR); + if (iyear != year) + return false; + } + + if (month != null) { + int imonth = cal.get(Calendar.MONTH);// 鑾峰彇鏈堜唤(鏈堜唤浠�0寮�濮嬭绠楃殑) + imonth = imonth + 1; + if (imonth != month) + return false; + } + + if (day != null) { + int iday = cal.get(Calendar.DATE);// 鑾峰彇鏃� + if (iday != day) + return false; + } + + if (hour != null) { + int ihour = cal.get(Calendar.HOUR_OF_DAY);// 24灏忔椂 0- 23 + if (ihour != hour) + return false; + } + + if (minute != null) { + int iminute = cal.get(Calendar.MINUTE); + if (iminute != minute) + return false; + } + // Boolean b = yearTag && monthTag && dayTag && hourTag && minuteTag; + return true; + } + + /** + * 鏍规嵁鍏蜂綋鏃堕棿灞炴�у垽鏂槸鍚︾浉鍚� + * + */ + public static Boolean DateEquals(Date date1, Date date2, Boolean year, Boolean month, Boolean day, Boolean hour, + Boolean minute) { + + Calendar calendar1 = new GregorianCalendar(); + Calendar calendar2 = new GregorianCalendar(); + calendar1.setTime(date1); + calendar2.setTime(date2); + + if (year) { + if (calendar1.get(Calendar.YEAR) != calendar2.get(Calendar.YEAR)) { + return false; + } + } + if (month) { + if (calendar1.get(Calendar.MONTH) != calendar2.get(Calendar.MONTH)) { + return false; + } + } + if (day) { + if (calendar1.get(Calendar.DATE) != calendar2.get(Calendar.DATE)) { + return false; + } + } + if (year) { + if (calendar1.get(Calendar.HOUR_OF_DAY) != calendar2.get(Calendar.HOUR_OF_DAY)) { + return false; + } + } + if (year) { + if (calendar1.get(Calendar.MINUTE) != calendar2.get(Calendar.MINUTE)) { + return false; + } + } + + // Boolean b = yearTag && monthTag && dayTag && hourTag && minuteTag; + + return true; + } + + /** 鑾峰彇10浣嶆暟鏃堕棿鎴� */ + public static Integer getTenTime(Date date) { + Timestamp ts = new Timestamp(date.getTime()); + return (int) ((ts.getTime()) / 1000); + } + + /** + * 鑾峰彇鎸囧畾鏃ユ湡鐨勬槑澶� difDay 鎶婃棩鏈熷線鍚庡鍔犱竴澶�.鏁存暟寰�鍚庢帹,璐熸暟寰�鍓嶇Щ鍔� + * + * @return date + */ + @SuppressWarnings("static-access") + public static Date getDetailDay(Date today, int difDay) { + Calendar calendar = new GregorianCalendar(); + calendar.setTime(today); + calendar.add(calendar.DATE, difDay);// 鎶婃棩鏈熷線鍚庡鍔犱竴澶�.鏁存暟寰�鍚庢帹,璐熸暟寰�鍓嶇Щ鍔� + Date d = calendar.getTime(); + return d; + } + + /** + * 鑾峰彇鎯宠鐨勬牸寮忕殑鏃堕棿 + * + * @return String + */ + public static String getTypeDate(String type, Date date) { + if (date == null) + return null; + + if (SimpleTool.checkNotNull(type)) { + myformat = new SimpleDateFormat(type); + String returnDate = myformat.format(date); + myformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + return returnDate; + } else { + String returnDate = myformat.format(date); + return returnDate; + } + + } + + /** + * 姣旇緝涓や釜鏃堕棿澶╂暟宸� startTime - endTime + * + * @param type + * (鏃犳晥) + * @return String + * @throws ParseException + */ + public static int getDiffDate(String type, Date startTime, Date endTime) throws ParseException { + type = "yyyyMMdd"; + SimpleDateFormat myformat = new SimpleDateFormat(type); + int i = 0; + i = (int) ((myformat.parse(myformat.format(startTime)).getTime() + - myformat.parse(myformat.format(endTime)).getTime()) / (1000 * 60 * 60 * 24)); + // return + // myformat.parse(myformat.format(date1)).compareTo(myformat.parse(myformat.format(date2))); + return i; + } + + /** + * 寰楀埌涓や釜鏃堕棿鐨勫垎閽熷樊 date1 - date2 杩欎釜鏄釜濂囪懇銆備絾鏄暣鍨嬩簡銆� + * + * @return int + * @throws ParseException + */ + public static int getLeftDateForMinue(Date date1, Date date2) throws ParseException { + long times = date1.getTime() - date2.getTime(); + times = times / (1000 * 60); + return (int) times; + } + + /**鎶婂瓧绗︿覆杞负鐗瑰畾鏃堕棿鏍煎紡 + * + * @param type 鏃堕棿鏍煎紡 + * @param sDate 瀛楃涓叉椂闂达紙鍙互涓虹┖锛� + * @return date + * @throws ParseException + */ + public static Date parseStringForDate(String type, String sDate){ + Date date = null; + try { + if(SimpleTool.checkNotNull(sDate)) { + SimpleDateFormat myformat = new SimpleDateFormat(type); + date = myformat.parse(sDate); + } + } catch (Exception e) { + e.printStackTrace(); + } + return date; + } + + /** + * 鍒ゆ柇鏄惁涓虹┖ + */ + public static boolean checkNotNull(Object o) { + boolean b = false; + if (o != null && !"".equals(o)&&!"undefined".equals(o)&&!" ".equals(o)) { + b = true; + } + return b; + } + + /** + * 鍒ゆ柇鏄惁涓虹┖ (澶氫釜) + */ + public static boolean checkNotNullM(Object[] os) { + boolean b = true; + for (Object o : os) { + if (o == null || "".equals(o)) + return false; + } + return b; + } + + /** + * 鑾峰彇鏈嶅姟鍣ㄧ鐨剋ebapps璺緞 + * + * @return + */ + public String findServerPath() { + String classPath = this.getClass().getClassLoader().getResource("/").getPath(); + try { + classPath = URLDecoder.decode(classPath, "gb2312"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + String[] strPath = classPath.split("/"); + String path = ""; + for (int i = 0; i < strPath.length; i++) { + if (i > 0 && i <= 3) { + path = path + strPath[i] + "/"; + } + } + return path; + } + + /** + * 鍒犻櫎鏂囦欢 杈撳叆鐪熸槸璺緞 + */ + public static void deleteFile(String sPath) { + File file = new File(sPath); + // 鍒ゆ柇鐩綍鎴栨枃浠舵槸鍚﹀瓨鍦� + if (file.exists()) { + // 鍒ゆ柇鏄惁涓烘枃浠� + if (file.isFile()) { // 涓烘枃浠舵椂璋冪敤鍒犻櫎鏂囦欢鏂规硶 + deleteFileForOne(sPath); + } else { // 涓虹洰褰曟椂璋冪敤鍒犻櫎鐩綍鏂规硶 + throw new RuntimeException("dir is no del"); + // deleteDirectory(sPath); + } + } + } + + /** + * 鍒犻櫎鐩綍锛堟枃浠跺す锛変互鍙婄洰褰曚笅鐨勬枃浠� + * + * @param sPath + * 琚垹闄ょ洰褰曠殑鏂囦欢璺緞 + * @return 鐩綍鍒犻櫎鎴愬姛杩斿洖true锛屽惁鍒欒繑鍥瀎alse + */ + public static boolean deleteDirectory(String sPath) { + // 濡傛灉sPath涓嶄互鏂囦欢鍒嗛殧绗︾粨灏撅紝鑷姩娣诲姞鏂囦欢鍒嗛殧绗� + if (!sPath.endsWith(File.separator)) { + sPath = sPath + File.separator; + } + File dirFile = new File(sPath); + // 濡傛灉dir瀵瑰簲鐨勬枃浠朵笉瀛樺湪锛屾垨鑰呬笉鏄竴涓洰褰曪紝鍒欓��鍑� + if (!dirFile.exists() || !dirFile.isDirectory()) { + return false; + } + Boolean flag = true; + // 鍒犻櫎鏂囦欢澶逛笅鐨勬墍鏈夋枃浠�(鍖呮嫭瀛愮洰褰�) + File[] files = dirFile.listFiles(); + for (int i = 0; i < files.length; i++) { + // 鍒犻櫎瀛愭枃浠� + if (files[i].isFile()) { + flag = deleteFileForOne(files[i].getAbsolutePath()); + if (!flag) + break; + } // 鍒犻櫎瀛愮洰褰� + else { + flag = deleteDirectory(files[i].getAbsolutePath()); + if (!flag) + break; + } + } + if (!flag) + return false; + // 鍒犻櫎褰撳墠鐩綍 + if (dirFile.delete()) { + return true; + } else { + return false; + } + } + + /** + * 鍒犻櫎鍗曚釜鏂囦欢 + * + * @param sPath + * 琚垹闄ゆ枃浠剁殑鏂囦欢鍚� + * @return 鍗曚釜鏂囦欢鍒犻櫎鎴愬姛杩斿洖true锛屽惁鍒欒繑鍥瀎alse + */ + public static boolean deleteFileForOne(String sPath) { + Boolean flag = false; + File file = new File(sPath); + // 璺緞涓烘枃浠朵笖涓嶄负绌哄垯杩涜鍒犻櫎 + if (file.isFile() && file.exists()) { + file.delete(); + flag = true; + } + return flag; + } + + + /** + * 鑾峰彇uuid + */ + public static String getUUIDName() { + return UUID.randomUUID().toString(); + } + + + /** 鑾峰彇寮傚父淇℃伅 **/ + public static String getExceptionMsg(Exception e) { + StringBuffer emsg = new StringBuffer(); + if (e != null) { + StackTraceElement[] st = e.getStackTrace(); + for (StackTraceElement stackTraceElement : st) { + String exclass = stackTraceElement.getClassName(); + String method = stackTraceElement.getMethodName(); + emsg.append("[绫�:" + exclass + "]璋冪敤---" + method + "----鏃跺湪绗�" + stackTraceElement.getLineNumber() + + "琛屼唬鐮佸鍙戠敓寮傚父!寮傚父绫诲瀷:" + e.toString() + "(" + e.getMessage() + ")\r\n"); + } + } + return emsg.toString(); + } + + /** + * 鑾峰彇鎸囧畾鏍煎紡鐨凞ouble 绫诲瀷鏁版嵁 + * + * 杞崲鏍煎紡鐨勭被鍨� 榛樿涓� "#.##" + * @param e + * 瑕佽浆鎹㈢殑鏁版嵁婧� + **/ + public static Double getTypeDouble(Double e) { + fmt.setRoundingMode(RoundingMode.HALF_UP); // 淇濈暀灏忔暟鐐瑰悗涓や綅骞跺洓鑸嶄簲鍏ワ紝纭繚浠烽挶鍑嗙‘ + Double d = Double.valueOf(fmt.format(e)); + return d; + } + + + /** + * SHA1 鍔犲瘑 + * + * @param decript + * @return + */ + public static String SHA1(String decript) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-1"); + digest.update(decript.getBytes()); + byte messageDigest[] = digest.digest(); + // Create Hex String + StringBuffer hexString = new StringBuffer(); + // 瀛楄妭鏁扮粍杞崲涓� 鍗佸叚杩涘埗 鏁� + for (int i = 0; i < messageDigest.length; i++) { + String shaHex = Integer.toHexString(messageDigest[i] & 0xFF); + if (shaHex.length() < 2) { + hexString.append(0); + } + hexString.append(shaHex); + } + return hexString.toString(); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + return ""; + } + + + public static String getLocalIP() { + InetAddress addr = null; + try { + addr = InetAddress.getLocalHost(); + } catch (UnknownHostException e) { + e.printStackTrace(); + } + + byte[] ipAddr = addr.getAddress(); + String ipAddrStr = ""; + for (int i = 0; i < ipAddr.length; i++) { + if (i > 0) { + ipAddrStr += "."; + } + ipAddrStr += ipAddr[i] & 0xFF; + } + // System.out.println("i am ip:......"+ipAddrStr); + return ipAddrStr; + } + + /**闅忔満鐢熸垚瀛楃涓诧紙0-9锛� + * + * @param lengthCount 闀垮害 + * @return + */ + public static String generateCardNo(Integer lengthCount) { + if(!SimpleTool.checkNotNull(lengthCount)) { + lengthCount = 6; + } + java.util.Random r=new java.util.Random(); + StringBuilder str = new StringBuilder();//瀹氫箟鍙橀暱瀛楃涓� + for(int i=0;i<lengthCount;i++){ + str.append(r.nextInt(10)); + } + return str.toString(); + } + + /**鍒ゆ柇鏄笉鏄棰戞枃浠� + * @param fileName 鏂囦欢鍚嶇О + * @return boolean true鏄棰戞枃浠� + */ + public static boolean getMimeType(String fileName) { + boolean b = false; + FileNameMap fileNameMap = URLConnection.getFileNameMap(); + String type = fileNameMap.getContentTypeFor(fileName); + //鏄棰憈ype鏄负绌虹殑 + if(!checkNotNull(type)) { + b = true; + } + return b; + } + + /** + * 鍒ゆ柇鏄惁涓鸿棰� + * @param fileName + * @return + */ + public static String isVideo(String fileName) { + FileNameMap fileNameMap = URLConnection.getFileNameMap(); + String type = fileNameMap.getContentTypeFor(fileName); + return type; + } + + /**鍒ゆ柇鏄惁鏄腑鏂�*/ + public static boolean isChineseChar(String str){ + boolean temp = false; + Pattern p=Pattern.compile("[\u4e00-\u9fa5]"); + Matcher m=p.matcher(str); + if(m.find()){ + temp = true; + } + return temp; + } + + /**鍘婚櫎瀛楃涓蹭腑涓嶆槸涓枃鐨勫瓧绗� + * + */ + public static String deleteNoChinese(String str){ + String name=""; + if(checkNotNull(str)){ + for(int i=0;i<str.length();i++){ + String s = str.substring(i, i+1); + if(isChineseChar(s)){ + name = name +s; + } + } + } + return name; + } + + /**鐢熸垚瀛楁瘝锛堝叏閮ㄦ槸涓枃鐨勶級*/ + public static String convertHanzi3Pinyin(String hanzi,boolean full){ + hanzi = deleteNoChinese(hanzi); + hanzi = convertHanzi2Pinyin(hanzi,false); + return hanzi; + } + + /***鑾峰彇瀛楃涓叉嫾闊崇殑绗竴涓瓧姣嶏紙澶у啓锛�**/ + public static String convertStringPinyinOne(String hanzi) { + if(SimpleTool.checkNotNull(hanzi)) { + //杞寲涓轰究瀹� + hanzi = convertHanzi2Pinyin(hanzi,false); + //杞寲澶у啓 + hanzi = hanzi.toUpperCase(); + /*//鑾峰彇绗竴涓� + byte[] datas = hanzi.getBytes(); + if(datas.length>0) { + byte[] datas2 = new byte[] {datas[0]}; + hanzi = new String(datas2); + }else { + hanzi = ""; + }*/ + } + return hanzi; + } + + + /***灏嗘眽瀛楄浆鎴愭嫾闊�(鍙栭瀛楁瘝鎴栧叏鎷�) + * @param hanzi + * @param full 鏄惁鍏ㄦ嫾 + * @return + */ + public static String convertHanzi2Pinyin(String hanzi,boolean full){ + //鑾峰彇绗竴涓瓧 + /* if(checkNotNull(hanzi)){ + boolean isHave = true; + Integer l = hanzi.length(); + Integer index = 0; + while (isHave) { + String hanzi2 = hanzi.substring(index,index+1); + if(isChineseChar(hanzi2)){ + isHave = false; + hanzi = hanzi2; + }else{ + if(index<l-1){ + index++; + }else{ + isHave = false; + } + } + } + } + */ + //鍘婚櫎鎵�鏈夌殑绌烘牸 + if(checkNotNull(hanzi)){ + hanzi = hanzi.replaceAll(" ", ""); + } + + /*** + * ^[\u2E80-\u9FFF]+$ 鍖归厤鎵�鏈変笢浜氬尯鐨勮瑷� + * ^[\u4E00-\u9FFF]+$ 鍖归厤绠�浣撳拰绻佷綋 + * ^[\u4E00-\u9FA5]+$ 鍖归厤绠�浣� + */ + String regExp="^[\u4E00-\u9FFF]+$"; + StringBuffer sb=new StringBuffer(); + if(hanzi==null||"".equals(hanzi.trim())){ + return ""; + } + String pinyin=""; + for(int i=0;i<hanzi.length();i++){ + char unit=hanzi.charAt(i); + if(match(String.valueOf(unit),regExp)){//鏄眽瀛楋紝鍒欒浆鎷奸煶 + pinyin=convertSingleHanzi2Pinyin(unit); + if(full){ + sb.append(pinyin); + }else{ + sb.append(pinyin.charAt(0)); + } + }else{ + sb.append(unit); + } + } + return sb.toString(); + } + + /***灏嗗崟涓眽瀛楄浆鎴愭嫾闊� + * @param hanzi + * @return + */ + private static String convertSingleHanzi2Pinyin(char hanzi){ + HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat(); + outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE); + String[] res; + StringBuffer sb=new StringBuffer(); + try { + res = PinyinHelper.toHanyuPinyinStringArray(hanzi,outputFormat); + sb.append(res[0]);//瀵逛簬澶氶煶瀛楋紝鍙敤绗竴涓嫾闊� + } catch (Exception e) { + e.printStackTrace(); + return ""; + } + return sb.toString(); + } + + /***@param str 婧愬瓧绗︿覆 + * @param regex 姝e垯琛ㄨ揪寮� + * @return 鏄惁鍖归厤 + */ + public static boolean match(String str,String regex){ + Pattern pattern=Pattern.compile(regex); + Matcher matcher=pattern.matcher(str); + return matcher.find(); + } + + /** 璇诲彇 Excel鏂囦欢鍐呭(3.24 quan) + * + * @param excel_name File + * @return + * @throws Exception + */ + public static List<String[]> readExcelByeFile2(File excel_name) throws Exception { + // 缁撴灉闆� + List<String[]> list = new ArrayList<String[]>(); + HSSFWorkbook hssfworkbook = new HSSFWorkbook(new FileInputStream(excel_name)); + + // 閬嶅巻璇ヨ〃鏍间腑鎵�鏈夌殑宸ヤ綔琛紝i琛ㄧず宸ヤ綔琛ㄧ殑鏁伴噺 getNumberOfSheets琛ㄧず宸ヤ綔琛ㄧ殑鎬绘暟 + HSSFSheet hssfsheet = hssfworkbook.getSheetAt(0); + + // 閬嶅巻璇ヨ鎵�鏈夌殑琛�,j琛ㄧず琛屾暟 getPhysicalNumberOfRows琛岀殑鎬绘暟 + for (int j = 0; j < hssfsheet.getPhysicalNumberOfRows(); j++) { + HSSFRow hssfrow = hssfsheet.getRow(j); + if(hssfrow!=null){ + int col = hssfrow.getPhysicalNumberOfCells(); + // 鍗曡鏁版嵁 + String[] arrayString = new String[col]; + for (int i = 0; i < col; i++) { + HSSFCell cell = hssfrow.getCell(i); + if (cell == null) { + arrayString[i] = ""; + } else if (cell.getCellType() == CellType.NUMERIC) { + // arrayString[i] = new Double(cell.getNumericCellValue()).toString(); + short format = cell.getCellStyle().getDataFormat(); + SimpleDateFormat sdf = null; + if(format == 14 || format == 31 || format == 57 || format == 58){ + //鏃ユ湡 + sdf = new SimpleDateFormat("yyyy-MM-dd"); + }else if (format == 20 || format == 32) { + //鏃堕棿 + sdf = new SimpleDateFormat("HH:mm"); + }else if (CellType.NUMERIC == cell.getCellType()) { + if (HSSFDateUtil.isCellDateFormatted(cell)) { + Date d = cell.getDateCellValue(); + DateFormat formater = new SimpleDateFormat("yyyy骞�"); + // DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + arrayString[i] = formater.format(d); + } else { + arrayString[i] = new BigDecimal(cell.getNumericCellValue()).toString(); + } + } + } else {// 濡傛灉EXCEL琛ㄦ牸涓殑鏁版嵁绫诲瀷涓哄瓧绗︿覆鍨� + arrayString[i] = cell.getStringCellValue().trim(); + } + } + list.add(arrayString); + } + } + return list; + } + + /** + * 璇诲彇 Excel鏂囦欢鍐呭 + * + * @param excel_name + * @param header 鏄惁鍖呮嫭琛ㄥご + * @return + * @throws Exception + */ + public static List<String[]> readExcelByeFileData(File excel_name,boolean header) throws Exception { + // 缁撴灉闆� + List<String[]> list = new ArrayList<String[]>(); + + HSSFWorkbook hssfworkbook = new HSSFWorkbook(new FileInputStream( + excel_name)); + + // 閬嶅巻璇ヨ〃鏍间腑鎵�鏈夌殑宸ヤ綔琛紝i琛ㄧず宸ヤ綔琛ㄧ殑鏁伴噺 getNumberOfSheets琛ㄧず宸ヤ綔琛ㄧ殑鎬绘暟 + for(int s=0;s<hssfworkbook.getNumberOfSheets();s++) { + HSSFSheet hssfsheet = hssfworkbook.getSheetAt(s); + int col = 0; + // 閬嶅巻璇ヨ鎵�鏈夌殑琛�,j琛ㄧず琛屾暟 getPhysicalNumberOfRows琛岀殑鎬绘暟 鍘婚櫎鏍囬 + for (int j = 0; j < hssfsheet.getPhysicalNumberOfRows(); j++) { + HSSFRow hssfrow = hssfsheet.getRow(j); + if(hssfrow!=null){ + if(j == 0) { + col = hssfrow.getPhysicalNumberOfCells(); + if(!header) { + //涓嶅寘鎷〃澶� + continue; + } + } + // 鍗曡鏁版嵁 + String[] arrayString = new String[col]; + for (int i = 0; i < col; i++) { + HSSFCell cell = hssfrow.getCell(i); + if (cell == null) { + arrayString[i] = ""; + } else if (cell.getCellType() == CellType.NUMERIC) { + // arrayString[i] = new Double(cell.getNumericCellValue()).toString(); + if (CellType.NUMERIC == cell.getCellType()) { + short format = cell.getCellStyle().getDataFormat(); + if(format == 14 || format == 31 || format == 57 || format == 58){ + //鏃ユ湡锛堜腑鏂囨椂闂存牸寮忕殑锛� + Date d = cell.getDateCellValue(); + DateFormat formater = new SimpleDateFormat("yyyy骞�"); + // DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + arrayString[i] = formater.format(d); + }else if (HSSFDateUtil.isCellDateFormatted(cell)) { + Date d = cell.getDateCellValue(); + DateFormat formater = new SimpleDateFormat("yyyy骞�"); + // DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + arrayString[i] = formater.format(d); + } else { + if(CellType.STRING == cell.getCellType()){ + arrayString[i] =cell.getStringCellValue(); + }else if(CellType.FORMULA==cell.getCellType()){ + arrayString[i] =cell.getCellFormula(); + }else if(CellType.NUMERIC== cell.getCellType()){ + HSSFDataFormatter dataFormatter = new HSSFDataFormatter(); + arrayString[i] =dataFormatter.formatCellValue(cell); + } + } + } + } else if(cell.getCellType() == CellType.BLANK){ + arrayString[i] = ""; + } else { // 濡傛灉EXCEL琛ㄦ牸涓殑鏁版嵁绫诲瀷涓哄瓧绗︿覆鍨� + arrayString[i] = cell.getStringCellValue().trim(); + } + } + list.add(arrayString); + } + } + } + return list; + } + + /** + * 璇诲彇 Excel鏂囦欢鍐呭锛堝鏍′俊鎭笓鐢級 + * + * @param excel_name + * @return + * @throws Exception + */ + public static List<String[]> readExcelByeFile(File excel_name) throws Exception { + // 缁撴灉闆� + List<String[]> list = new ArrayList<String[]>(); + + HSSFWorkbook hssfworkbook = new HSSFWorkbook(new FileInputStream( + excel_name)); + + // 閬嶅巻璇ヨ〃鏍间腑鎵�鏈夌殑宸ヤ綔琛紝i琛ㄧず宸ヤ綔琛ㄧ殑鏁伴噺 getNumberOfSheets琛ㄧず宸ヤ綔琛ㄧ殑鎬绘暟 + for(int s=0;s<hssfworkbook.getNumberOfSheets();s++) { + HSSFSheet hssfsheet = hssfworkbook.getSheetAt(s); + int col = 0; + // 閬嶅巻璇ヨ鎵�鏈夌殑琛�,j琛ㄧず琛屾暟 getPhysicalNumberOfRows琛岀殑鎬绘暟 鍘婚櫎鏍囬 + for (int j = 0; j < hssfsheet.getPhysicalNumberOfRows(); j++) { + HSSFRow hssfrow = hssfsheet.getRow(j); + if(hssfrow!=null){ + if(j == 0) { + col = hssfrow.getPhysicalNumberOfCells(); + }else { + // int col = hssfrow.getPhysicalNumberOfCells(); + // 鍗曡鏁版嵁 + String[] arrayString = new String[col]; + for (int i = 0; i < col; i++) { + HSSFCell cell = hssfrow.getCell(i); + if (cell == null) { + arrayString[i] = ""; + } else if (cell.getCellType() == CellType.NUMERIC) { + // arrayString[i] = new Double(cell.getNumericCellValue()).toString(); + if (CellType.NUMERIC == cell.getCellType()) { + short format = cell.getCellStyle().getDataFormat(); + if(format == 14 || format == 31 || format == 57 || format == 58){ + //鏃ユ湡锛堜腑鏂囨椂闂存牸寮忕殑锛� + Date d = cell.getDateCellValue(); + DateFormat formater = new SimpleDateFormat("yyyy骞�"); + // DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + arrayString[i] = formater.format(d); + }else if (HSSFDateUtil.isCellDateFormatted(cell)) { + Date d = cell.getDateCellValue(); + DateFormat formater = new SimpleDateFormat("yyyy骞�"); + // DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + arrayString[i] = formater.format(d); + } else { + if(CellType.STRING == cell.getCellType()){ + arrayString[i] =cell.getStringCellValue(); + }else if(CellType.FORMULA==cell.getCellType()){ + arrayString[i] =cell.getCellFormula(); + }else if(CellType.NUMERIC== cell.getCellType()){ + HSSFDataFormatter dataFormatter = new HSSFDataFormatter(); + arrayString[i] =dataFormatter.formatCellValue(cell); + } + } + } + } else if(cell.getCellType() == CellType.BLANK){ + arrayString[i] = ""; + } else { // 濡傛灉EXCEL琛ㄦ牸涓殑鏁版嵁绫诲瀷涓哄瓧绗︿覆鍨� + cell.setCellType(CellType.STRING); + String name = cell.getStringCellValue().trim(); + if(name.equals("-")) { + arrayString[i] = ""; + }else { + arrayString[i] = name; + } + } + } + list.add(arrayString); + } + } + } + } + return list; + } + + /**鑾峰彇瀛楃涓查噷闈㈢殑鏁板瓧锛屾寜椤哄簭鎺掑簭*/ + public static String stringNumber(String data) { + String da = null; + String regEc = "[^0-9]"; + Pattern pattern = Pattern.compile(regEc); + Matcher m = pattern.matcher(data); + da = m.replaceAll("").trim(); + return da; + } + + /** + * @param url:璇锋眰url + * @param content: 璇锋眰浣�(鍙傛暟) + * @return errorStr:閿欒淇℃伅;status:鐘舵�佺爜锛宺esponse锛氳繑鍥炴暟鎹� + * @throws JSONException + */ + public static JSONObject requestData(String url, String content) throws JSONException { + JSONObject obj = new JSONObject(); + String errMsg_r = ""; + String status_r = "0"; + String response = ""; + //PrintWriter out = null; + DataOutputStream out = null; + BufferedReader in = null; + try { + URL realUrl = new URL(url); + // 鎵撳紑鍜孶RL涔嬮棿鐨勮繛鎺� + URLConnection conn = realUrl.openConnection(); + HttpURLConnection httpUrlConnection = (HttpURLConnection) conn; + // 璁剧疆璇锋眰灞炴�� + httpUrlConnection.setRequestProperty("Content-type", "application/json;charset=UTF-8"); + //httpUrlConnection.setRequestProperty("Content-Type", "application/json"); + //httpUrlConnection.setRequestProperty("Charset", "UTF-8"); + httpUrlConnection.setRequestProperty("x-adviewrtb-version", "2.1"); + // 鍙戦�丳OST璇锋眰蹇呴』璁剧疆濡備笅涓よ + httpUrlConnection.setDoOutput(true); + httpUrlConnection.setDoInput(true); + // 鑾峰彇URLConnection瀵硅薄瀵瑰簲鐨勮緭鍑烘祦 + out = new DataOutputStream(httpUrlConnection.getOutputStream()); + //out = new PrintWriter(httpUrlConnection.getOutputStream()); + // 鍙戦�佽姹傚弬鏁� + //out.write(content); + out.write(content.getBytes("UTF-8")); + // flush杈撳嚭娴佺殑缂撳啿 + out.flush(); + httpUrlConnection.connect(); + // 瀹氫箟BufferedReader杈撳叆娴佹潵璇诲彇URL鐨勫搷搴� + // in = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream())); + String wxMsgXml = IOUtils.toString(httpUrlConnection.getInputStream(), "utf-8"); + System.out.println("wxMsgXml:"+wxMsgXml); + if(SimpleTool.checkNotNull(wxMsgXml)) { + obj = JSONObject.fromObject(wxMsgXml); + } + /* String line; + while ((line = in.readLine()) != null) { + response += line; + } */ + status_r = new Integer(httpUrlConnection.getResponseCode()).toString(); + } catch (Exception e) { + System.out.println("鍙戦�� POST 璇锋眰鍑虹幇寮傚父锛�" + e); + errMsg_r = e.getMessage(); + e.printStackTrace(); + } + // 浣跨敤finally鍧楁潵鍏抽棴杈撳嚭娴併�佽緭鍏ユ祦 + finally { + try { + if (out != null) { out.close();} + if (in != null) {in.close();} + } catch (Exception ex) { + ex.printStackTrace(); + } + } + obj.put("errMsg_r", errMsg_r); + obj.put("status_r", status_r); + return obj; + } + + /**闅忔満鐢熸垚瀛楁暟锛堟暣鏁帮級锛堝寘鎷� 0锛� + * @param maxNumber 鏈�澶у�� + * @return + */ + public static Integer randomData(Integer maxNumber) { + java.util.Random r=new java.util.Random(); + return r.nextInt(maxNumber); + } + + private static final String[] HEADERS_TO_TRY = {"X-Forwarded-For", "Proxy-Client-IP", "WL-Proxy-Client-IP", + "HTTP_X_FORWARDED_FOR", "HTTP_X_FORWARDED", "HTTP_X_CLUSTER_CLIENT_IP", "HTTP_CLIENT_IP", + "HTTP_FORWARDED_FOR", "HTTP_FORWARDED", "HTTP_VIA", "REMOTE_ADDR", "X-Real-IP"}; + + /** + * getClientIpAddress:(鑾峰彇鐢ㄦ埛ip锛屽彲绌块�忎唬鐞�). <br/> + * @param request + * @return + * @author chenjiahe + * @Date 2018骞�3鏈�2鏃ヤ笅鍗�4:41:47 + * @since JDK 1.7 + */ + public static String getClientIpAddress(HttpServletRequest request) { + for (String header : HEADERS_TO_TRY) { + String ip = request.getHeader(header); + if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) { + return ip; + } + } + return request.getRemoteAddr(); + } + +} diff --git a/hx_common/src/main/java/com/hx/util/StreamUtils.java b/hx_common/src/main/java/com/hx/util/StreamUtils.java new file mode 100644 index 0000000..755eb93 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/StreamUtils.java @@ -0,0 +1,266 @@ +package com.hx.util; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; + +public class StreamUtils { + + final static int BUFFER_SIZE = 4096; + /** + * 锟斤拷InputStream转锟斤拷锟斤拷String + * + * @param in + * InputStream + * @return String + * @throws Exception + * + */ + public static String InputStreamTOString(InputStream in) { + + ByteArrayOutputStream outStream = new ByteArrayOutputStream(); + byte[] data = new byte[BUFFER_SIZE]; + String string = null; + int count = 0; + try { + while ((count = in.read(data, 0, BUFFER_SIZE)) != -1) + outStream.write(data, 0, count); + } catch (IOException e) { + e.printStackTrace(); + } + + data = null; + try { + string = new String(outStream.toByteArray(), "UTF-8"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + return string; + } + + /** + * 锟斤拷InputStream转锟斤拷锟斤拷某锟斤拷锟街凤拷锟斤拷锟斤拷String + * + * @param in + * @param encoding + * @return + * @throws Exception + */ + public static String InputStreamTOString(InputStream in, String encoding) { + String string = null; + ByteArrayOutputStream outStream = new ByteArrayOutputStream(); + byte[] data = new byte[BUFFER_SIZE]; + int count = -1; + try { + while ((count = in.read(data, 0, BUFFER_SIZE)) != -1) + outStream.write(data, 0, count); + } catch (IOException e) { + e.printStackTrace(); + } + + data = null; + try { + string = new String(outStream.toByteArray(), encoding); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + return string; + } + + /** + * 锟斤拷String转锟斤拷锟斤拷InputStream + * + * @param in + * @return + * @throws Exception + */ + public static InputStream StringTOInputStream(String in) throws Exception { + + ByteArrayInputStream is = new ByteArrayInputStream(in.getBytes("UTF-8")); + return is; + } + + /** + * 锟斤拷String转锟斤拷锟斤拷InputStream + * + * @param in + * @return + * @throws Exception + */ + public static byte[] StringTObyte(String in) { + byte[] bytes = null; + try { + bytes = InputStreamTOByte(StringTOInputStream(in)); + } catch (IOException e) { + } catch (Exception e) { + e.printStackTrace(); + } + return bytes; + } + + /** + * 锟斤拷InputStream转锟斤拷锟斤拷byte锟斤拷锟斤拷 + * + * @param in + * InputStream + * @return byte[] + * @throws IOException + */ + public static byte[] InputStreamTOByte(InputStream in) throws IOException { + + ByteArrayOutputStream outStream = new ByteArrayOutputStream(); + byte[] data = new byte[BUFFER_SIZE]; + int count = -1; + while ((count = in.read(data, 0, BUFFER_SIZE)) != -1) + outStream.write(data, 0, count); + + data = null; + return outStream.toByteArray(); + } + + + /** + * 锟斤拷byte锟斤拷锟斤拷转锟斤拷锟斤拷InputStream + * + * @param in + * @return + * @throws Exception + */ + public static InputStream byteTOInputStream(byte[] in) throws Exception { + + ByteArrayInputStream is = new ByteArrayInputStream(in); + return is; + } + + /** + * 锟斤拷byte锟斤拷锟斤拷转锟斤拷锟斤拷String + * + * @param in + * @return + * @throws Exception + */ + public static String byteTOString(byte[] in) { + + InputStream is = null; + try { + is = byteTOInputStream(in); + } catch (Exception e) { + e.printStackTrace(); + } + return InputStreamTOString(is, "UTF-8"); + } + /** + * 锟斤拷byte锟斤拷锟斤拷转锟斤拷锟斤拷String + * + * @param in + * @return + * @throws Exception + */ + public static String getString(String in) { + + String is = null; + try { + is = byteTOString(StringTObyte(in)); + } catch (Exception e) { + e.printStackTrace(); + } + return is; + } + + // InputStream 转锟斤拷锟斤拷byte[] + public byte[] getBytes(InputStream is) throws IOException { + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + byte[] b = new byte[BUFFER_SIZE]; + int len = 0; + + while ((len = is.read(b, 0, BUFFER_SIZE)) != -1) { + baos.write(b, 0, len); + } + + baos.flush(); + + byte[] bytes = baos.toByteArray(); + + System.out.println(new String(bytes)); + + return bytes; + } + /** + * 锟斤拷锟斤拷募锟铰凤拷锟斤拷锟斤拷锟斤拷募锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟� + * 锟斤拷锟街斤拷为锟斤拷位锟斤拷锟斤拷 unicode 锟斤拷 + * @return + */ + public static FileInputStream getFileInputStream(String filepath) { + FileInputStream fileInputStream = null; + try { + fileInputStream = new FileInputStream(filepath); + } catch (FileNotFoundException e) { + System.out.print("锟斤拷锟斤拷锟斤拷息:锟侥硷拷锟斤拷锟斤拷锟斤拷"); + e.printStackTrace(); + } + return fileInputStream; + } + /** + * 锟斤拷锟斤拷募锟斤拷锟斤拷蟠唇锟斤拷募锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟� + * 锟斤拷锟街斤拷为锟斤拷位锟斤拷锟斤拷 unicode 锟斤拷 + * @return + */ + public static FileInputStream getFileInputStream(File file) { + FileInputStream fileInputStream = null; + try { + fileInputStream = new FileInputStream(file); + } catch (FileNotFoundException e) { + System.out.print("锟斤拷锟斤拷锟斤拷息:锟侥硷拷锟斤拷锟斤拷锟斤拷"); + e.printStackTrace(); + } + return fileInputStream; + } + /** + * 锟斤拷锟斤拷募锟斤拷锟斤拷蟠唇锟斤拷募锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷 + * 锟斤拷锟街斤拷为锟斤拷位锟斤拷锟斤拷 unicode 锟斤拷 + * @param file + * @param append true:锟侥硷拷锟斤拷追锟接凤拷式锟斤拷,false:锟津覆革拷原锟侥硷拷锟斤拷锟斤拷锟斤拷 + * @return + */ + public static FileOutputStream getFileOutputStream(File file,boolean append) { + FileOutputStream fileOutputStream = null; + try { + fileOutputStream = new FileOutputStream(file,append); + } catch (FileNotFoundException e) { + System.out.print("锟斤拷锟斤拷锟斤拷息:锟侥硷拷锟斤拷锟斤拷锟斤拷"); + e.printStackTrace(); + } + return fileOutputStream; + } + /** + * 锟斤拷锟斤拷募锟铰凤拷锟斤拷锟斤拷锟斤拷募锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷 + * 锟斤拷锟街斤拷为锟斤拷位锟斤拷锟斤拷 unicode 锟斤拷 + * @param append true:锟侥硷拷锟斤拷追锟接凤拷式锟斤拷,false:锟津覆革拷原锟侥硷拷锟斤拷锟斤拷锟斤拷 + * @return + */ + public static FileOutputStream getFileOutputStream(String filepath,boolean append) { + FileOutputStream fileOutputStream = null; + try { + fileOutputStream = new FileOutputStream(filepath,append); + } catch (FileNotFoundException e) { + System.out.print("锟斤拷锟斤拷锟斤拷息:锟侥硷拷锟斤拷锟斤拷锟斤拷"); + e.printStackTrace(); + } + return fileOutputStream; + } + + public static File getFile(String filepath) { + return new File(filepath); + } + public static ByteArrayOutputStream getByteArrayOutputStream() { + return new ByteArrayOutputStream(); + } + +} \ No newline at end of file diff --git a/hx_common/src/main/java/com/hx/util/StringUtils.java b/hx_common/src/main/java/com/hx/util/StringUtils.java new file mode 100644 index 0000000..76e38a8 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/StringUtils.java @@ -0,0 +1,372 @@ +package com.hx.util; + +import java.io.UnsupportedEncodingException; +import java.text.MessageFormat; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * 瀛楃涓插伐鍏风被 + * + * @author ThinkGem + * @version 2013-05-22 + */ +public class StringUtils { + + private static final char SEPARATOR = '_'; + private static final String CHARSET_NAME = "UTF-8"; + + /** + * 鏍煎紡鍖栧瓧绗︿覆锛屾浛鎹㈠師瀛楃涓蹭腑鐨剓0}, {1}锛屾寜椤哄簭鏇挎崲 + * + * @param oriStr + * @param args + * @return + */ + public static String format(String oriStr, Object... args) { + return MessageFormat.format(oriStr, args); + } + + /** + * 杞崲涓哄瓧鑺傛暟锟�? + * + * @param str + * @return + */ + public static byte[] getBytes(String str) { + if (str != null) { + try { + return str.getBytes(CHARSET_NAME); + } catch (UnsupportedEncodingException e) { + return null; + } + } else { + return null; + } + } + + /** + * 鍙彇鍚庝袱锟�? + * + * @param str + * @return + */ + public static String getLastTwoChars(String str) { + if (null != str && str.trim().length() > 0) { + str = str.trim(); + int len = str.length(); + if (len == 2) { + return str; + } else if (len > 2) { + return str.substring(len - 2); + } + } + return ""; + } + + /** + * 鍙彇鍚庝笁锟�? + * + * @param str + * @return + */ + public static String getLastThreeChars(String str) { + if (null != str && str.trim().length() > 0) { + str = str.trim(); + int len = str.length(); + if (len == 3) { + return str; + } else if (len > 3) { + return str.substring(len - 3); + } + } + return ""; + } + + /** + * 鏇挎崲涓烘墜鏈鸿瘑鍒殑HTML锛屽幓鎺夋牱寮忓強灞烇拷?锟斤紝淇濈暀鍥炶溅锟�? + * + * @param html + * @return + */ + public static String replaceMobileHtml(String html) { + if (html == null) { + return ""; + } + return html.replaceAll("<([a-z]+?)\\s+?.*?>", "<$1>"); + } + + /** + * 椹煎嘲鍛藉悕娉曞伐锟�? + * + * @return toCamelCase("hello_world") == "helloWorld" + * toCapitalizeCamelCase("hello_world") == "HelloWorld" + * toUnderScoreCase("helloWorld") = "hello_world" + */ + public static String toCamelCase(String s) { + if (s == null) { + return null; + } + + s = s.toLowerCase(); + + StringBuilder sb = new StringBuilder(s.length()); + boolean upperCase = false; + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + + if (c == SEPARATOR) { + upperCase = true; + } else if (upperCase) { + sb.append(Character.toUpperCase(c)); + upperCase = false; + } else { + sb.append(c); + } + } + + return sb.toString(); + } + + /** + * 椹煎嘲鍛藉悕娉曞伐锟�? + * + * @return toCamelCase("hello_world") == "helloWorld" + * toCapitalizeCamelCase("hello_world") == "HelloWorld" + * toUnderScoreCase("helloWorld") = "hello_world" + */ + public static String toCapitalizeCamelCase(String s) { + if (s == null) { + return null; + } + s = toCamelCase(s); + return s.substring(0, 1).toUpperCase() + s.substring(1); + } + + /** + * 椹煎嘲鍛藉悕娉曞伐锟�? + * + * @return toCamelCase("hello_world") == "helloWorld" + * toCapitalizeCamelCase("hello_world") == "HelloWorld" + * toUnderScoreCase("helloWorld") = "hello_world" + */ + public static String toUnderScoreCase(String s) { + if (s == null) { + return null; + } + + StringBuilder sb = new StringBuilder(); + boolean upperCase = false; + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + + boolean nextUpperCase = true; + + if (i < (s.length() - 1)) { + nextUpperCase = Character.isUpperCase(s.charAt(i + 1)); + } + + if ((i > 0) && Character.isUpperCase(c)) { + if (!upperCase || !nextUpperCase) { + sb.append(SEPARATOR); + } + upperCase = true; + } else { + upperCase = false; + } + + sb.append(Character.toLowerCase(c)); + } + + return sb.toString(); + } + + /** + * 鏍规嵁瑙勫垯regExpr,鍒ゆ柇瀛楃鍐呭鏄惁鍖归厤 + * <p> + * 鍒╃敤姝e垯琛ㄨ揪寮忚鍒欏垽鏂紝寰呴獙璇佺殑瀛楃鍐呭鏄惁绗﹀悎瑕佹眰锟�? <br> + * 姣斿'[0-9]*'鍗冲垽鏂槸鍚︿负鏁板瓧鐨勮锟�?, '^[a-z0-9_-]{3,15}$'鍗冲垽鏂槸鍚︿负鐢ㄦ埛鍚嶇殑瑙勫垯,<br> + * '((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})'鍗冲垽鏂槸鍚︿负瀵嗙爜鐨勮锟�?,<br> + * '^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$'鍗砮mail瑙勫垯,<br> + * '([^\s]+(\.(?i)(jpg|png|gif|bmp))$)'鍗冲垽鏂煇鍥剧墖鏂囦欢鏍煎紡,<br> + * '^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])$'鍗矷P瑙勫垯. + * + * + * @param regExpr + * 姝e垯琛ㄨ揪锟�? + * @param content + * 寰呴獙璇佺殑瀛楃鍐呭 + * @return boolean + */ + public static boolean isMatch(String regExpr, String content) { + if (StringUtils.isEmpty(regExpr, content)) + return false; + + Pattern pattern = Pattern.compile(regExpr); + Matcher matcher = pattern.matcher(content); + + return matcher.matches(); + } + + /** + * 姝e垯鍒ゆ柇绾暟锟�? + * + * @param str + * @return + */ + public static boolean isNumeric(String str) { + Pattern pattern = Pattern.compile("[0-9]*"); + Matcher isNum = pattern.matcher(str); + if (!isNum.matches()) { + return false; + } + return true; + } + + public static boolean isEmpty(String str) { + return null == str || str.trim().length() == 0 || "undefined".equals(str); + } + + /**鍒ゆ柇绌�*/ + public static boolean isNull(String str) { + return null == str || str.trim().length() == 0 || "undefined".equals(str); + } + + /**鍒ゆ柇闈炵┖*/ + public static boolean noNull(String str) { + return null != str && str.trim().length() != 0 && !"undefined".equals(str); + } + + /** + * 鍒ゆ柇瀛楃鍐呭涓槸鍚﹀瓨鍦ㄤ竴涓负绌虹殑瀛楃锟�? + * <p> + * 濡傛灉鍦ㄦ墍鏈夌殑瀛楃涓插唴瀹逛腑锛屽彧瑕佸瓨鍦ㄦ煇锟�?涓瓧绗︿覆涓虹┖锛屽垯杩斿洖涓簍rue, 濡傛灉锟�?鏈夌殑瀛楃涓插唴瀹逛腑锛屼笉瀛樺湪锟�?涓┖瀛楃涓诧紝鍒欒繑鍥炰负false. + * + * @param strings + * @return boolean + */ + public static boolean isEmpty(String... strings) { + if (strings == null) + return true; + + for (String str : strings) { + if (StringUtils.isEmpty(str)) + return true; + } + + return false; + } + + public static boolean isAllEmpty(String... strings) { + if (strings == null) + return true; + + for (String str : strings) { + if (!StringUtils.isEmpty(str)) + return false; + } + + return true; + } + + /** + * @param strings + * 璇ユ暟缁勬槸鍚︽湁锟�? + * @return + */ + public static boolean hasContent(String[] strings) { + if (strings != null && strings.length > 0) + return true; + + return false; + } + + /** + * @param params + * 璇ap鏄惁鏈夛拷?? + * @return + */ + public static boolean hasContent(Map<?, ?> params) { + if (params != null && params.size() > 0) + return true; + + return false; + } + + public static boolean isNumeric2(String str) { + if (null == str || isEmpty(str)) { + return false; + } + char[] chars = str.toCharArray(); + for (char c : chars) { + if (!Character.isDigit(c)) + return false; + } + return true; + } + + public static int parseInt(String string) { + if (null != string && isNumeric2(string)) { + return Integer.parseInt(string); + } + return 0; + } + + /** + * 瀵瑰瓧绗︿覆锛堟墜鏈猴紝鍚嶇О锛変綔闅愯棌澶勭悊 + * @param oriStr 鍘熷瀛楃涓� + * @param type 绫诲瀷0锛氬彧淇濈暀绗竴涓強鏈�鍚庝竴涓瓧绗︼紝鍏跺畠鐢�*鏇夸唬锛�1鍓�4鍚�3淇濈暀锛屼腑闂寸敤*鏇夸唬 + * @return + */ + public static String hideKeyWord(String oriStr, int type) + { + if(!isEmpty(oriStr)) + { + String temp = null; + + if(type == 0) + { + if(oriStr.length() == 1) + { + temp = oriStr; + }else if(oriStr.length() == 2) { + temp = oriStr.substring(0, 1) + "*"; + }else if(oriStr.length() > 2) { + temp = oriStr.substring(0, 1); + for (int i = 1; i < oriStr.length() - 1; i++) { + temp += "*"; + } + temp += oriStr.substring(oriStr.length() - 1, oriStr.length()); + } + }else{ + if(oriStr.length() < 8) + { + temp = oriStr; + }else{ + temp = oriStr.substring(0,3); + for (int i = 3; i < oriStr.length() - 4; i++) { + temp += "*"; + } + temp += oriStr.substring(oriStr.length() - 4, oriStr.length()); + } + } + + return temp; + } + + return oriStr; + } + + /** + * 鍘婚櫎绌烘牸 + * @param info 淇℃伅 + * @return 杩斿洖 + */ + public static String trimBlank(String info){ + if (null != info){ + return info.trim(); + } + return null; + } +} diff --git a/hx_common/src/main/java/com/hx/util/TempltUtil.java b/hx_common/src/main/java/com/hx/util/TempltUtil.java new file mode 100644 index 0000000..01e917b --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/TempltUtil.java @@ -0,0 +1,150 @@ +package com.hx.util; + +import freemarker.template.Configuration; +import freemarker.template.DefaultObjectWrapper; +import freemarker.template.Template; +import freemarker.template.TemplateException; +import org.springframework.core.io.ClassPathResource; + +import java.io.*; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +public class TempltUtil { + + public static final String PREVIEW_DOC = "/temp.docx"; + public static final String TEMP_URL = "temp"; + public static final String TEMP_NAME = "contract.tpl"; + + /** + * + * @param tempUrl 妯℃澘鎵�鍦ㄦ枃浠跺す + * @param tempName 妯℃澘鍚嶇О + * @return + * @throws IOException + */ + public static Template configTemplate(String tempUrl,String tempName) throws IOException { + Configuration config = new Configuration(); + ClassPathResource classPathResource = new ClassPathResource(tempUrl); + config.setDirectoryForTemplateLoading(classPathResource.getFile()); + config.setObjectWrapper(new DefaultObjectWrapper()); + Template template = config.getTemplate(tempName, "UTF-8"); + return template; + } + + /** + * + * @param tempUrl 妯℃澘鎵�鍦ㄦ枃浠跺す + * @param temp 妯℃澘鍚嶇О + * @param copyUrl 澶嶅埗鏂囦欢璺緞 + * @param data 妯℃澘鏁版嵁map + * return 鐢熸垚璺緞 + */ + public static String toPreview(String tempUrl,String temp,String copyUrl, Map<?, ?> data){ + try { + Template template = configTemplate(tempUrl,temp); + ClassPathResource classPathResource = new ClassPathResource(tempUrl+"/"+PREVIEW_DOC); + //鐢熸垚鏂扮殑妯℃澘 + File tempFile = classPathResource.getFile(); + copyUrl = copyUrl+"/"+DateUtil.dateFormat(new Date(),"yyyyMMddHHmmss")+tempFile.getName(); + File file = new File(copyUrl); + FileUtils.copyFile(tempFile,file); + + File file2 = new File(copyUrl); + + FileOutputStream fos = new FileOutputStream(file2); + Writer out = new OutputStreamWriter(fos, "UTF-8"); + template.process(data, out); + out.flush(); + out.close(); + } catch (Exception e) { + e.printStackTrace(); + } + return copyUrl; + } + + /** + * + * @param templateUrl 妯℃澘璺緞鐩綍锛屼笉鍖呮嫭妯℃澘鍚嶇О,濡� ./src/main/resources/jsonFile + * @param templateName 妯℃澘鍚嶇О锛屽锛歞ata.tpl + * @param savaPath 鐢熸垚鏂囦欢瀛樻斁鐩綍锛屽 ./src/main/resources/jsonFile + * @param name 鐢熸垚鐨勬枃浠跺悕绉帮紝鍖呮嫭鍚庣紑鍚嶇О + * @param data 妯℃澘閲岄潰鍐呭 + * @throws Exception + */ + public static String createDataFile(String templateUrl,String templateName, + String savaPath, String name,Map<String, Object> data) throws IOException { + String targetFile = null; + Writer out = null; + if(!SimpleTool.checkNotNull(templateUrl)) { + throw new RuntimeException("templateUrl 涓虹┖"); + } + if(!SimpleTool.checkNotNull(templateName)) { + throw new RuntimeException("templateName 涓虹┖"); + } + if(!SimpleTool.checkNotNull(savaPath)) { + throw new RuntimeException("savaPath 涓虹┖"); + } + try { + if(!savaPath.endsWith("/")){ + savaPath = savaPath+"/"; + } + if(!templateUrl.endsWith("/")){ + templateUrl = templateUrl +"/"; + } + + //涓轰簡瑙e喅spingBoot鎵撳寘鎴恓ar鑾峰彇涓嶄簡鏂囦欢锛屾妸鏂囦欢淇濆瓨鍒版湰鍦� + //鎷垮埌jar閲岄潰鐨勬枃浠舵祦 + ClassPathResource classPathResource = new ClassPathResource(templateUrl+templateName); + //淇濆瓨妯℃澘鍥剧墖璺緞 + String saveTempUrl = savaPath+"temp/"; + //鍒ゆ柇鏄惁瀛樺湪浜� + File temFile = new File(saveTempUrl+templateName); + if(temFile.exists()){ + temFile = temFile.getParentFile(); + }else{ + //涓嶅瓨鍦ㄥ氨鍒涘缓涓�涓� + temFile = FileUtils.inputStreamToFile(classPathResource.getInputStream(),saveTempUrl,templateName); + temFile = temFile.getParentFile(); + } + + // 鍙嶅皠end + Configuration cfg = new Configuration(); + // 鎸囧畾妯℃澘鏂囦欢浠庝綍澶勫姞杞界殑鏁版嵁婧愶紝杩欓噷璁剧疆鎴愪竴涓枃浠剁洰褰� + cfg.setDirectoryForTemplateLoading(temFile); + cfg.setObjectWrapper(new DefaultObjectWrapper()); + cfg.setDefaultEncoding("UTF-8"); + // 鑾峰彇鎴栧垱寤烘ā鏉� + Template template = cfg.getTemplate(templateName); + template.setEncoding("UTF-8"); + + // String targetFile = "./src/template/test.html"; + //鐢熸垚璺緞 + targetFile = savaPath; + File file = new File(targetFile); + //娌℃湁鎵惧埌灏辨柊寤轰竴涓� + if (!file.isDirectory() && !file.exists()) { + file.mkdirs(); + } + targetFile += name; + System.out.println("targetFile:"+targetFile); + // 灏嗘ā鏉垮拰鏁版嵁妯″瀷鍚堝苟 杈撳嚭鍒癈onsole + out = new BufferedWriter(new OutputStreamWriter( + new FileOutputStream(targetFile), "UTF-8")); + template.process(data, out); + } catch (IOException e) { + e.printStackTrace(); + } catch (TemplateException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + }finally { + if(SimpleTool.checkNotNull(out)){ + out.flush(); + out.close(); + } + } + return targetFile; + } + +} \ No newline at end of file diff --git a/hx_common/src/main/java/com/hx/util/TengXunMapUtil.java b/hx_common/src/main/java/com/hx/util/TengXunMapUtil.java new file mode 100644 index 0000000..6aaef1c --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/TengXunMapUtil.java @@ -0,0 +1,191 @@ +package com.hx.util; + +import net.sf.json.JSONObject; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLEncoder; + +/** + * 鑵捐鍦板浘宸ュ叿 + * @author mgchen + * + */ +public class TengXunMapUtil { + + /**key*/ + public static final String KEY_SHOP = "NDTBZ-XH6WX-TOB4C-TZFHG-2ORS3-UCBFA"; + /**绛惧悕鏍¢獙*/ + public static final String SIGN = "qI6ZmfLk0IYt7PPWThwqXMjnNjjPzSaW"; + + public static final String URL_LOCATION = "http://apis.map.qq.com/ws/geocoder/v1/?address={1}&key={2}"; + public static final String URL_CITY = "http://apis.map.qq.com/ws/geocoder/v1/?location={1}&key={2}"; + + /**鍦板潃杞崲涓虹粡绾害*/ + public static String[] getLocation(String address, String key) + { + try{ + String str = sendGet("https://apis.map.qq.com/ws/geocoder/v1/", "address=" + URLEncoder.encode(address, "utf-8") + "&key=" + key); + JSONObject obj = JSONObject.fromObject(str); + int status = obj.optInt("status", -1); + if(status == 0) + { + JSONObject rObj = obj.optJSONObject("result"); + if(rObj != null) + { + JSONObject lObj = rObj.optJSONObject("location"); + if(lObj != null) + { + Double lng = lObj.optDouble("lng", 0.0); + Double lat = lObj.optDouble("lat", 0.0); + if(lng != 0.0 && lat != 0.0) + { + return new String[]{lng.toString(), lat.toString()}; + } + + } + } + } + }catch(Exception e) + { + e.printStackTrace(); + } + + return null; + } + + /**鍦板潃杞崲涓虹粡绾害锛堢鍚嶆牎楠岋級*/ + public static String[] getLocation(String address, String key,String sign) { + try{ + sign = MD5Util.MD5Encode("/ws/geocoder/v1?address=" + address + "&key=" + key+sign,null); + String str = sendGet("https://apis.map.qq.com/ws/geocoder/v1", "address=" + address + "&key=" + key+"&sig="+sign); + JSONObject obj = JSONObject.fromObject(str); + int status = obj.optInt("status", -1); + if(status == 0) + { + JSONObject rObj = obj.optJSONObject("result"); + if(rObj != null) + { + JSONObject lObj = rObj.optJSONObject("location"); + if(lObj != null) + { + Double lng = lObj.optDouble("lng", 0.0); + Double lat = lObj.optDouble("lat", 0.0); + if(lng != 0.0 && lat != 0.0) + { + return new String[]{lng.toString(), lat.toString()}; + } + + } + } + } + }catch(Exception e) { + e.printStackTrace(); + } + + return null; + } + + /** + * 鍚戞寚瀹歎RL鍙戦�丟ET鏂规硶鐨勮姹� + * + * @param url + * 鍙戦�佽姹傜殑URL + * @param param + * 璇锋眰鍙傛暟锛岃姹傚弬鏁板簲璇ユ槸 name1=value1&name2=value2 鐨勫舰寮忋�� + * @return URL 鎵�浠h〃杩滅▼璧勬簮鐨勫搷搴旂粨鏋� + */ + public static String sendGet(String url, String param) { + String result = ""; + BufferedReader in = null; + try { + String urlNameString = url + "?" + param; + System.out.println("urlNameString:"+urlNameString); + URL realUrl = new URL(urlNameString); + // 鎵撳紑鍜孶RL涔嬮棿鐨勮繛鎺� + URLConnection connection = realUrl.openConnection(); + // 璁剧疆閫氱敤鐨勮姹傚睘鎬� + connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3"); + connection.setRequestProperty("connection", "Keep-Alive"); + connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36"); + // 寤虹珛瀹為檯鐨勮繛鎺� + connection.connect(); + +// // 鑾峰彇鎵�鏈夊搷搴斿ご瀛楁 +// Map<String, List<String>> map = connection.getHeaderFields(); +// // 閬嶅巻鎵�鏈夌殑鍝嶅簲澶村瓧娈� +// for (String key : map.keySet()) { +// System.out.println(key + "--->" + map.get(key));/ +// } + + // 瀹氫箟 BufferedReader杈撳叆娴佹潵璇诲彇URL鐨勫搷搴� + in = new BufferedReader(new InputStreamReader( + connection.getInputStream())); + String line; + while ((line = in.readLine()) != null) { + result += line; + } + } catch (Exception e) { + System.out.println("鍙戦�丟ET璇锋眰鍑虹幇寮傚父锛�" + e); + e.printStackTrace(); + } + // 浣跨敤finally鍧楁潵鍏抽棴杈撳叆娴� + finally { + try { + if (in != null) { + in.close(); + } + } catch (Exception e2) { + e2.printStackTrace(); + } + } + return result; + } + + public static void main(String[] args) + { + System.out.println(sendGet("http://apis.map.qq.com/ws/geocoder/v1/", "address=" +"鍖椾含甯傛捣娣�鍖哄僵鍜屽潑璺捣娣�瑗垮ぇ琛�74鍙�" + "&key=" + "11")); + } + + /**鑾峰彇鐪�/甯�*/ + public static String[] getAddress(String lat, String lng, String key) + { + try{ + String str = sendGet("http://apis.map.qq.com/ws/geocoder/v1/", "location=" + lat + "," + lng + "&key=" + key); + JSONObject obj = JSONObject.fromObject(str); + if(obj != null && obj.optInt("status", -1) == 0) + { + obj = obj.optJSONObject("result"); + if(obj != null) + { + obj = obj.optJSONObject("address_component"); + if(obj != null) + { + String nation = obj.optString("nation"); + String province = obj.optString("province"); + String city = obj.optString("city"); + String area = obj.optString("district"); + String detail = obj.optString("street") + obj.optString("street_number"); + String[] addr = new String[]{ + new String(nation.getBytes(), "utf-8"), + new String(province.getBytes(), "utf-8"), + new String(city.getBytes(), "utf-8"), + new String(area.getBytes(), "utf-8"), + new String(detail.getBytes(), "utf-8") + }; + + return addr; + } + + return null; + } + } + }catch(Exception e) + { + e.printStackTrace(); + } + return null; + } +} diff --git a/hx_common/src/main/java/com/hx/util/ThreadPoolUtils.java b/hx_common/src/main/java/com/hx/util/ThreadPoolUtils.java new file mode 100644 index 0000000..a30af25 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/ThreadPoolUtils.java @@ -0,0 +1,42 @@ +package com.hx.util; + +import org.springframework.stereotype.Component; + +import java.util.concurrent.*; + +/** + * @PackageName com.hx.util + * @ProjectName hx-parent + * @Author: ChenJiaHe + * @Date: Create in 17:12 2019/8/6 + * @Description: + * @Copyright Copyright (c) 2019, hx01@163.com All Rights Reserved. + */ +@Component +public class ThreadPoolUtils { + + public static BlockingQueue<Runnable> queueToUse = new LinkedBlockingQueue<>(120); + + /** + * @param poolSize + * @param method + * @MethodName creatExeutorService + * @Description 鍒涘缓绾跨▼姹犳柟娉� + * @Auther ChenJiaHe + * @Date 2019/8/6 17:19 + * @Since JDK 1.8 + */ + public ExecutorService creatExeutorService(int poolSize, String method, BlockingQueue<Runnable> queueToUse) { + int coreSize = Runtime.getRuntime().availableProcessors(); + if (poolSize < coreSize) { + coreSize = poolSize; + } + ThreadFactory threadFactory = r -> { + Thread t = new Thread(r, "thread created mewthod{" + method + "}"); + t.setDaemon(true); + return t; + }; + final ThreadPoolExecutor executor = new ThreadPoolExecutor(coreSize, poolSize, 60, TimeUnit.SECONDS, queueToUse, threadFactory, new ThreadPoolExecutor.CallerRunsPolicy()); + return executor; + } +} diff --git a/hx_common/src/main/java/com/hx/util/WebUtil.java b/hx_common/src/main/java/com/hx/util/WebUtil.java new file mode 100644 index 0000000..db82e3c --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/WebUtil.java @@ -0,0 +1,53 @@ +package com.hx.util; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.servlet.http.HttpServletResponse; + +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import com.alibaba.fastjson.JSONObject; + +/** + * + * @author lijietian + * + */ +public class WebUtil { + /** + * 杩斿洖鏁版嵁缁欏墠绔殑鏂规硶 + * + * @param msg 杩斿洖鏁版嵁 + * + */ + public static void AJAXdata(String msg) { + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + HttpServletResponse response = attributes.getResponse(); + + response.setContentType("text/plain");// 鏂囨湰 + response.setHeader("Cache-Control", "no-store"); + response.setCharacterEncoding("utf-8"); + try { + PrintWriter pw = response.getWriter(); + pw.write(msg); + pw.flush(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * 缁勬垚缁熶竴鐨勬牸寮� + * + */ + public static String AJAXMsg(Integer status,String errorMsg,JSONObject obj) { + JSONObject info = new JSONObject(); + info.put("status", status); + info.put("errorMsg", errorMsg); + info.put("datas", obj); + return info.toJSONString(); + } + +} diff --git a/hx_common/src/main/java/com/hx/util/XmlUtil.java b/hx_common/src/main/java/com/hx/util/XmlUtil.java new file mode 100644 index 0000000..6ad4c95 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/XmlUtil.java @@ -0,0 +1,113 @@ +package com.hx.util; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.bind.Unmarshaller; +import java.io.*; + +public class XmlUtil { + + /** + * 灏嗗璞$洿鎺ヨ浆鎹㈡垚String绫诲瀷鐨� XML杈撳嚭 + * + * @param obj + * @return + */ + public static String convertToXml(Object obj) { + // 鍒涘缓杈撳嚭娴� + StringWriter sw = new StringWriter(); + try { + // 鍒╃敤jdk涓嚜甯︾殑杞崲绫诲疄鐜� + JAXBContext context = JAXBContext.newInstance(obj.getClass()); + + Marshaller marshaller = context.createMarshaller(); + // 鏍煎紡鍖杧ml杈撳嚭鐨勬牸寮� + marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, + Boolean.TRUE); + marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");// //缂栫爜鏍煎紡 + marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);// 鏄惁鏍煎紡鍖栫敓鎴愮殑xml涓� + marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);// 鏄惁鐪佺暐xm澶村0鏄庝俊鎭� + // 灏嗗璞¤浆鎹㈡垚杈撳嚭娴佸舰寮忕殑xml + marshaller.marshal(obj, sw); + } catch (JAXBException e) { + e.printStackTrace(); + } + return sw.toString(); + } + + /** + * 灏嗗璞℃牴鎹矾寰勮浆鎹㈡垚xml鏂囦欢 + * + * @param obj + * @param path + * @return + */ + public static void convertToXml(Object obj, String path) { + try { + // 鍒╃敤jdk涓嚜甯︾殑杞崲绫诲疄鐜� + JAXBContext context = JAXBContext.newInstance(obj.getClass()); + + Marshaller marshaller = context.createMarshaller(); + // 鏍煎紡鍖杧ml杈撳嚭鐨勬牸寮� + marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, + Boolean.TRUE); + marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");// //缂栫爜鏍煎紡 + marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);// 鏄惁鏍煎紡鍖栫敓鎴愮殑xml涓� + marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);// 鏄惁鐪佺暐xm澶村0鏄庝俊鎭� + // 灏嗗璞¤浆鎹㈡垚杈撳嚭娴佸舰寮忕殑xml + // 鍒涘缓杈撳嚭娴� + FileWriter fw = null; + try { + fw = new FileWriter(path); + } catch (IOException e) { + e.printStackTrace(); + } + marshaller.marshal(obj, fw); + } catch (JAXBException e) { + e.printStackTrace(); + } + } + + @SuppressWarnings("unchecked") + /** + * 灏哠tring绫诲瀷鐨剎ml杞崲鎴愬璞� + */ + public static Object convertXmlStrToObject(Class clazz, String xmlStr) { + Object xmlObject = null; + try { + JAXBContext context = JAXBContext.newInstance(clazz); + // 杩涜灏哫ml杞垚瀵硅薄鐨勬牳蹇冩帴鍙� + Unmarshaller unmarshaller = context.createUnmarshaller(); + StringReader sr = new StringReader(xmlStr); + xmlObject = unmarshaller.unmarshal(sr); + } catch (JAXBException e) { + e.printStackTrace(); + } + return xmlObject; + } + + @SuppressWarnings("unchecked") + /** + * 灏唂ile绫诲瀷鐨剎ml杞崲鎴愬璞� + */ + public static Object convertXmlFileToObject(Class clazz, String xmlPath) { + Object xmlObject = null; + try { + JAXBContext context = JAXBContext.newInstance(clazz); + Unmarshaller unmarshaller = context.createUnmarshaller(); + FileReader fr = null; + try { + fr = new FileReader(xmlPath); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + xmlObject = unmarshaller.unmarshal(fr); + } catch (JAXBException e) { + e.printStackTrace(); + } + return xmlObject; + } + + +} diff --git a/hx_common/src/main/java/com/hx/util/code/NumberTool.java b/hx_common/src/main/java/com/hx/util/code/NumberTool.java new file mode 100644 index 0000000..99f0d43 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/code/NumberTool.java @@ -0,0 +1,101 @@ +package com.hx.util.code; + +import com.hx.util.DateUtil; +import com.hx.util.StringUtils; +import org.apache.commons.lang3.RandomStringUtils; + +import java.util.Date; +import java.util.Random; + +/**鐢熸垚缂栧彿宸ュ叿 + */ +public class NumberTool { + + /**澶у皬鍐欏瓧姣�*/ + private static final String LETTER_ARR = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + /**澶у皬鍐欏瓧姣嶅拰鏁板瓧*/ + private static final String LETTER_NUMBER = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + /**灏忓啓瀛楁瘝*/ + private static final String LETTER_SMALL = "abcdefghijklmnopqrstuvwxyz"; + /**澶у啓瀛楁瘝*/ + private static final String LETTER_BIG = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + + + /**闅忔満鑾峰ぇ鍐欏瓧姣嶇粍鍚� + * @param lengrhCount 闀垮害 + * @return + */ + public static String letterBig(long lengrhCount){ + char[] c = LETTER_BIG.toCharArray(); + Random random = new Random(); + + StringBuilder data = new StringBuilder(); + for( int i = 0; i < lengrhCount; i ++) { + data.append(c[random.nextInt(c.length)]); + } + return data.toString(); + } + + + /**闅忔満鑾峰皬鍐欏瓧姣嶇粍鍚� + * @param lengrhCount 闀垮害 + * @return + */ + public static String letterSmall(long lengrhCount){ + char[] c = LETTER_SMALL.toCharArray(); + Random random = new Random(); + + StringBuilder data = new StringBuilder(); + for( int i = 0; i < lengrhCount; i ++) { + data.append(c[random.nextInt(c.length)]); + } + return data.toString(); + } + + + /**闅忔満鑾峰彇澶у皬鍐欏瓧姣嶅拰鏁板瓧缁勫悎 + * @param lengrhCount 闀垮害 + * @return + */ + public static String letterNumber(long lengrhCount){ + char[] c = LETTER_NUMBER.toCharArray(); + Random random = new Random(); + + StringBuilder data = new StringBuilder(); + for( int i = 0; i < lengrhCount; i ++) { + data.append(c[random.nextInt(c.length)]); + } + return data.toString(); + } + + /**闅忔満鑾峰彇澶у皬鍐欏瓧姣嶇粍鍚� + * @param lengrhCount 闀垮害 + * @return + */ + public static String letterRandom(long lengrhCount){ + char[] c = LETTER_ARR.toCharArray(); + Random random = new Random(); + + StringBuilder data = new StringBuilder(); + for( int i = 0; i < lengrhCount; i ++) { + data.append(c[random.nextInt(c.length)]); + } + return data.toString(); + } + + /**闅忔満鐢熸垚瀛楃涓诧紙0-9锛� + * @param lengthCount 闀垮害 + * @return + */ + public static String generateCardNo(long lengthCount) { + Random r=new Random(); + //瀹氫箟鍙橀暱瀛楃涓� + StringBuilder str = new StringBuilder(); + for(int i=0;i<lengthCount;i++){ + str.append(r.nextInt(10)); + } + return str.toString(); + } + + +} diff --git a/hx_common/src/main/java/com/hx/util/corp/CorpMpUtil.java b/hx_common/src/main/java/com/hx/util/corp/CorpMpUtil.java new file mode 100644 index 0000000..8ca404e --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/corp/CorpMpUtil.java @@ -0,0 +1,101 @@ +package com.hx.util.corp; + +import com.alibaba.fastjson.JSONObject; +import com.hx.util.HttpMethodUtil; +import com.hx.util.StringUtils; +import com.hx.util.corp.entity.AppLetInfo; +import com.hx.util.corp.entity.OpenIdAUserId; +import com.hx.util.corp.entity.WeiXinInfo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.HashMap; +import java.util.Map; + +/** 浼佷笟寰俊宸ュ叿绫� + * @author wangrenhuang + * @Date 2021-10-19 + */ +public class CorpMpUtil { + + //log4j鏃ュ織 + private static Logger logger = LoggerFactory.getLogger(CorpMpUtil.class.getName()); + + /**閾炬帴-鑾峰彇搴旂敤accessToken*/ + public static final String URL_GET_USER_INFO = "https://qyapi.weixin.qq.com/cgi-bin/user/get"; + + /**openid杞瑄serid*/ + public static final String URL_OPENID_TO_USERID = "https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_userid"; + + /**userid杞琽penid*/ + public static final String URL_USERID_TO_OPENID = "https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_openid"; + + /**鑾峰彇灏忕▼搴忛摼鎺�*/ + public static final String URL_LINK = "https://api.weixin.qq.com/wxa/generate_urllink"; + + + /** + * openId鑾峰彇userId + * @param openId 鐢ㄦ埛openId + * @return 杩斿洖 + */ + public static OpenIdAUserId openIdToUserId(String openId, String token) { + Map<String,Object> map=new HashMap<>(); + map.put("access_token",token); + + JSONObject data = new JSONObject(); + data.put("openid",openId); + + String datas = HttpMethodUtil.HttpURLUtilJson(URL_OPENID_TO_USERID, data.toString(), map, null, "GET"); + OpenIdAUserId openIdAUserId = JSONObject.parseObject(datas, OpenIdAUserId.class); + return openIdAUserId; + } + + + /** + * userId鑾峰彇openId + * @param userid 浼佷笟鍛樺伐id + * @return 杩斿洖 + */ + public static OpenIdAUserId userIdToOpenId(String userid, String token) { + Map<String,Object> map=new HashMap<>(); + map.put("access_token",token); + + JSONObject data = new JSONObject(); + data.put("userid",userid); + + String datas = HttpMethodUtil.HttpURLUtilJson(URL_USERID_TO_OPENID, data.toString(), map, null, "GET"); + OpenIdAUserId openIdAUserId = JSONObject.parseObject(datas, OpenIdAUserId.class); + return openIdAUserId; + } + + + + /** + * 鑾峰彇浼佷笟寰俊鍛樺伐淇℃伅 + * @param userId 鐢ㄦ埛id + * @return 杩斿洖 + */ + public static WeiXinInfo userInfo(String userId, String token) { + Map<String,Object> map=new HashMap<>(); + map.put("access_token",token); + map.put("userid",userId); + String datas = HttpMethodUtil.HttpURLUtilJson(URL_GET_USER_INFO, null, map, null, "GET"); + WeiXinInfo weiXinInfo = JSONObject.parseObject(datas, WeiXinInfo.class); + return weiXinInfo; + } + + public static AppLetInfo getAppLetUrl(String path, String token, String env_version, String query) { + Map<String, Object> map = new HashMap(); + map.put("access_token", token); + com.alibaba.fastjson.JSONObject data = new com.alibaba.fastjson.JSONObject(); + data.put("path", path); + data.put("env_version", env_version); + if (!StringUtils.isEmpty(query)){ + data.put("query", query); + } + String datas = HttpMethodUtil.HttpURLUtilJson(URL_LINK, data.toString(), map, (Map)null, "POST"); + AppLetInfo appLetInfo = com.alibaba.fastjson.JSONObject.parseObject(datas, AppLetInfo.class); + return appLetInfo; + } +} diff --git a/hx_common/src/main/java/com/hx/util/corp/entity/AppLetInfo.java b/hx_common/src/main/java/com/hx/util/corp/entity/AppLetInfo.java new file mode 100644 index 0000000..799ca19 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/corp/entity/AppLetInfo.java @@ -0,0 +1,22 @@ +package com.hx.util.corp.entity; + +import com.alibaba.fastjson.annotation.JSONField; +import lombok.Data; + +/** + * @ClassName AppLetInfo + * @Description 鑾峰彇 URL Link 杩斿洖鏁版嵁 + * @Author wrh + * @Date 2023/4/3 16:00 + * @Version 1.0 + */ +@Data +public class AppLetInfo { + //閿欒鐮� + private Integer errcode; + //閿欒淇℃伅 + private String errmsg; + //鐢熸垚鐨勫皬绋嬪簭 URL Link + @JSONField(name="url_link") + private String urlLink; +} diff --git a/hx_common/src/main/java/com/hx/util/corp/entity/OpenIdAUserId.java b/hx_common/src/main/java/com/hx/util/corp/entity/OpenIdAUserId.java new file mode 100644 index 0000000..07cc69b --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/corp/entity/OpenIdAUserId.java @@ -0,0 +1,62 @@ +package com.hx.util.corp.entity; + +/**openId杞瑄serid鎴栬�卽serid杞琽penId鎺ユ敹瀹炰綋 + * + */ +public class OpenIdAUserId { + + /**杩斿洖鐮侊紝0琛ㄧず鎴愬姛*/ + private Integer errcode; + /**瀵硅繑鍥炵爜鐨勬枃鏈弿杩板唴瀹�*/ + private String errmsg; + /**浼佷笟鍛樺伐userid*/ + private String userid; + /**鐢ㄦ埛openid*/ + private String openid; + + + /**鐘舵�佺爜-鎴愬姛*/ + public static final int CODE_SUCCESS = 0; + + public Integer getErrcode() { + return errcode; + } + + public void setErrcode(Integer errcode) { + this.errcode = errcode; + } + + public String getErrmsg() { + return errmsg; + } + + public void setErrmsg(String errmsg) { + this.errmsg = errmsg; + } + + public String getUserid() { + return userid; + } + + public void setUserid(String userid) { + this.userid = userid; + } + + public String getOpenid() { + return openid; + } + + public void setOpenid(String openid) { + this.openid = openid; + } + + @Override + public String toString() { + return "OpenIdAUserId{" + + "errcode=" + errcode + + ", errmsg='" + errmsg + '\'' + + ", userid='" + userid + '\'' + + ", openid='" + openid + '\'' + + '}'; + } +} diff --git a/hx_common/src/main/java/com/hx/util/corp/entity/WeiXinInfo.java b/hx_common/src/main/java/com/hx/util/corp/entity/WeiXinInfo.java new file mode 100644 index 0000000..702977c --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/corp/entity/WeiXinInfo.java @@ -0,0 +1,113 @@ +package com.hx.util.corp.entity; + +import java.io.Serializable; + +public class WeiXinInfo implements Serializable { + + //杩斿洖鐮� + private Integer errcode; + //瀵硅繑鍥炵爜鐨勬枃鏈弿杩板唴瀹� + private String errmsg; + //鎴愬憳UserID銆傚搴旂鐞嗙鐨勫笎鍙凤紝浼佷笟鍐呭繀椤诲敮涓�銆備笉鍖哄垎澶у皬鍐欙紝闀垮害涓�1~64涓瓧鑺� + private String userid; + //鎴愬憳鍚嶇О锛涚涓夋柟涓嶅彲鑾峰彇锛岃皟鐢ㄦ椂杩斿洖userid浠ヤ唬鏇縩ame锛涗唬寮�鍙戣嚜寤哄簲鐢ㄩ渶瑕佺鐞嗗憳鎺堟潈鎵嶈繑鍥烇紱瀵逛簬闈炵涓夋柟鍒涘缓鐨勬垚鍛橈紝绗笁鏂归�氳褰曞簲鐢ㄤ篃涓嶅彲鑾峰彇锛涙湭杩斿洖name鐨勬儏鍐甸渶瑕侀�氳繃閫氳褰曞睍绀虹粍浠舵潵灞曠ず鍚嶅瓧 + private String name; + //鎵嬫満鍙风爜锛� + private String mobile; + //鑱屽姟淇℃伅锛� + private String position; + //鎬у埆銆�0琛ㄧず鏈畾涔夛紝1琛ㄧず鐢锋�э紝2琛ㄧず濂虫�� + private Integer gender; + //閭锛� + private String email; + // 婵�娲荤姸鎬�: 1=宸叉縺娲伙紝2=宸茬鐢紝4=鏈縺娲伙紝5=閫�鍑轰紒涓氥�� + private Integer status; + + + public Integer getErrcode() { + return errcode; + } + + public void setErrcode(Integer errcode) { + this.errcode = errcode; + } + + public String getErrmsg() { + return errmsg; + } + + public void setErrmsg(String errmsg) { + this.errmsg = errmsg; + } + + public String getUserid() { + return userid; + } + + public void setUserid(String userid) { + this.userid = userid; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getMobile() { + return mobile; + } + + public void setMobile(String mobile) { + this.mobile = mobile; + } + + public String getPosition() { + return position; + } + + public void setPosition(String position) { + this.position = position; + } + + public Integer getGender() { + return gender; + } + + public void setGender(Integer gender) { + this.gender = gender; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } + + @Override + public String toString() { + return "WeiXinInfo{" + + "errcode=" + errcode + + ", errmsg='" + errmsg + '\'' + + ", userid='" + userid + '\'' + + ", name='" + name + '\'' + + ", mobile='" + mobile + '\'' + + ", position='" + position + '\'' + + ", gender=" + gender + + ", email='" + email + '\'' + + ", status=" + status + + '}'; + } +} diff --git a/hx_common/src/main/java/com/hx/util/gaode/AddressCode.java b/hx_common/src/main/java/com/hx/util/gaode/AddressCode.java new file mode 100644 index 0000000..c634312 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/gaode/AddressCode.java @@ -0,0 +1,42 @@ +package com.hx.util.gaode; + +/** + * 鑾峰彇鍦板潃缁忕含搴� + * 鍝嶅簲瀹炰綋鍖� + */ +public class AddressCode { + + /**缁忓害*/ + private String lng; + /**缁村害*/ + private String lat; + /**鍩庡競缂栫爜*/ + private String cityCode; + + public AddressCode() { + } + + public String getLng() { + return lng; + } + + public void setLng(String lng) { + this.lng = lng; + } + + public String getLat() { + return lat; + } + + public void setLat(String lat) { + this.lat = lat; + } + + public String getCityCode() { + return cityCode; + } + + public void setCityCode(String cityCode) { + this.cityCode = cityCode; + } +} diff --git a/hx_common/src/main/java/com/hx/util/gaode/GaoDeMapUtil.java b/hx_common/src/main/java/com/hx/util/gaode/GaoDeMapUtil.java new file mode 100644 index 0000000..cdf9cf4 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/gaode/GaoDeMapUtil.java @@ -0,0 +1,53 @@ +package com.hx.util.gaode; + +import com.hx.util.HttpUtil; +import com.hx.util.StringUtils; +import net.sf.json.JSONArray; +import net.sf.json.JSONObject; + +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; + +/** + * 楂樺痉鍦板浘宸ュ叿 + * @author mgchen + * + */ +public class GaoDeMapUtil { + + /**鑾峰彇缁忕含搴�*/ + public static String URL_CODE = "https://restapi.amap.com/v3/geocode/geo"; + + /** + * 鑾峰彇鍦板潃鐨勭粡绾害 + * @param address + * @param key + * @return + */ + public static AddressCode addressCode(String address,String key) { + AddressCode addressCode = null; + //URL_CODE = URL_CODE+"?key="+key+"&address="+URLEncoder.encode(address,"UTF-8");//鍦板潃缂栬瘧 + URL_CODE = URL_CODE+"?key="+key+"&address="+address; + JSONObject data = HttpUtil.HttpURLUtil(URL_CODE,null); + if(data.optInt("status",0) == 1){ + JSONArray geocodes = data.getJSONArray("geocodes"); + if(geocodes.size()==1){ + JSONObject locationObj = geocodes.getJSONObject(0); + String location = locationObj.optString("location"); + if(StringUtils.noNull(location)){ + String[] locations = location.split(","); + if(locations.length != 2){ + return null; + } + addressCode = new AddressCode(); + addressCode.setLng(locations[0]); + addressCode.setLat(locations[1]); + addressCode.setCityCode(locationObj.optString("citycode")); + } + } + } + return addressCode; + } + + +} diff --git a/hx_common/src/main/java/com/hx/util/mysql/aes/MysqlHexAesTool.java b/hx_common/src/main/java/com/hx/util/mysql/aes/MysqlHexAesTool.java new file mode 100644 index 0000000..ad8a51b --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/mysql/aes/MysqlHexAesTool.java @@ -0,0 +1,110 @@ +package com.hx.util.mysql.aes; + +import com.hx.util.StringUtils; +import org.apache.commons.codec.binary.Hex; + +import javax.crypto.Cipher; +import javax.crypto.spec.SecretKeySpec; +import java.io.UnsupportedEncodingException; +import java.util.regex.Pattern; + +/** + * mybatis鏁版嵁搴撶殑AES_ENCRYPT锛堝姞瀵嗭級鍜孉ES_DECRYPT锛堣В瀵嗭級 + * mybatis鏁版嵁搴撶殑HEX锛堝姞澹筹級UNHEX锛堣В澹筹級 + * @author CJH + * @Date 2021-01-06 + */ +public class MysqlHexAesTool { + + + public static SecretKeySpec generateMySQLAESKey(final String key, final String encoding) { + try { + final byte[] finalKey = new byte[16]; + int i = 0; + for(byte b : key.getBytes(encoding)) { + finalKey[i++%16] ^= b; + } + return new SecretKeySpec(finalKey, "AES"); + } catch(UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } + + /**AES 瑙e瘑 + * @param data 闇�瑕佽В瀵嗙殑鏁版嵁 + * @param aesKey 绉橀挜 + * @param encoding 缂栫爜锛屼笉濉粯璁TF-8 + * @return 瑙e瘑鏁版嵁 + */ + public static String decryptData(String data,String aesKey,String encoding) { + try{ + if(data == null){ + return null; + } + if(!isHexStrValid(data)){ + return data; + } + if(StringUtils.isEmpty(encoding)){ + encoding = "UTF-8"; + } + // Decrypt + final Cipher decryptCipher = Cipher.getInstance("AES"); + decryptCipher.init(Cipher.DECRYPT_MODE, generateMySQLAESKey(aesKey, encoding)); + data = new String(decryptCipher.doFinal(Hex.decodeHex(data.toCharArray()))); + }catch (Exception e){ + throw new RuntimeException(e); + } + return data; + } + + /**AES鍔犲瘑 + * @param data 闇�瑕佽В瀵嗙殑鏁版嵁 + * @param aesKey 绉橀挜 + * @param encoding 缂栫爜锛屼笉濉粯璁TF-8 + * @return 杩斿洖澶у啓鍔犲瘑鐨勬暟鎹� + */ + public static String encryptData(String data,String aesKey,String encoding) { + try { + if(data == null){ + return null; + } + + if (StringUtils.isEmpty(encoding)) { + encoding = "UTF-8"; + } + // Encrypt + final Cipher encryptCipher = Cipher.getInstance("AES"); + encryptCipher.init(Cipher.ENCRYPT_MODE, generateMySQLAESKey(aesKey, encoding)); + char[] code = Hex.encodeHex(encryptCipher.doFinal(data.getBytes(encoding))); + StringBuilder builder = new StringBuilder(); + for (char d : code) { + builder.append(d); + } + data = builder.toString().toUpperCase(); + } catch (Exception e) { + throw new RuntimeException(e); + } + return data; + } + + /** + * 鍒ゆ柇鏄笉鏄崄鍏繘鍒剁殑瀛楃涓诧紙瀛楁瘝鏄ぇ鍐欑殑锛� + * @param str 闇�瑕佸垽鏂殑瀛楃涓� + * @return true or false + */ + public static boolean isHexStrValid(String str) { + + if(str == null){ + return false; + } + //鏄惁32浣嶅�嶆暟 + if(str.length()%32 != 0){ + return false; + } + String pattern = "^[0-9A-F]+$"; + return Pattern.compile(pattern).matcher(str).matches(); + } + + + +} diff --git a/hx_common/src/main/java/com/hx/util/rsa/Base64.java b/hx_common/src/main/java/com/hx/util/rsa/Base64.java new file mode 100644 index 0000000..3287f12 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/rsa/Base64.java @@ -0,0 +1,273 @@ +package com.hx.util.rsa; + +public final class Base64 { + + static private final int BASELENGTH = 128; + static private final int LOOKUPLENGTH = 64; + static private final int TWENTYFOURBITGROUP = 24; + static private final int EIGHTBIT = 8; + static private final int SIXTEENBIT = 16; + static private final int FOURBYTE = 4; + static private final int SIGN = -128; + static private final char PAD = '='; + static private final boolean fDebug = false; + static final private byte[] base64Alphabet = new byte[BASELENGTH]; + static final private char[] lookUpBase64Alphabet = new char[LOOKUPLENGTH]; + + static { + for (int i = 0; i < BASELENGTH; ++i) { + base64Alphabet[i] = -1; + } + for (int i = 'Z'; i >= 'A'; i--) { + base64Alphabet[i] = (byte) (i - 'A'); + } + for (int i = 'z'; i >= 'a'; i--) { + base64Alphabet[i] = (byte) (i - 'a' + 26); + } + + for (int i = '9'; i >= '0'; i--) { + base64Alphabet[i] = (byte) (i - '0' + 52); + } + + base64Alphabet['+'] = 62; + base64Alphabet['/'] = 63; + + for (int i = 0; i <= 25; i++) { + lookUpBase64Alphabet[i] = (char) ('A' + i); + } + + for (int i = 26, j = 0; i <= 51; i++, j++) { + lookUpBase64Alphabet[i] = (char) ('a' + j); + } + + for (int i = 52, j = 0; i <= 61; i++, j++) { + lookUpBase64Alphabet[i] = (char) ('0' + j); + } + lookUpBase64Alphabet[62] = (char) '+'; + lookUpBase64Alphabet[63] = (char) '/'; + + } + + private static boolean isWhiteSpace(char octect) { + return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9); + } + + private static boolean isPad(char octect) { + return (octect == PAD); + } + + private static boolean isData(char octect) { + return (octect < BASELENGTH && base64Alphabet[octect] != -1); + } + + /** + * Encodes hex octects into Base64 + * + * @param binaryData Array containing binaryData + * @return Encoded Base64 array + */ + public static String encode(byte[] binaryData) { + + if (binaryData == null) { + return null; + } + + int lengthDataBits = binaryData.length * EIGHTBIT; + if (lengthDataBits == 0) { + return ""; + } + + int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; + int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; + int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets; + char encodedData[] = null; + + encodedData = new char[numberQuartet * 4]; + + byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0; + + int encodedIndex = 0; + int dataIndex = 0; + if (fDebug) { + System.out.println("number of triplets = " + numberTriplets); + } + + for (int i = 0; i < numberTriplets; i++) { + b1 = binaryData[dataIndex++]; + b2 = binaryData[dataIndex++]; + b3 = binaryData[dataIndex++]; + + if (fDebug) { + System.out.println("b1= " + b1 + ", b2= " + b2 + ", b3= " + b3); + } + + l = (byte) (b2 & 0x0f); + k = (byte) (b1 & 0x03); + + byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); + byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0); + byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc); + + if (fDebug) { + System.out.println("val2 = " + val2); + System.out.println("k4 = " + (k << 4)); + System.out.println("vak = " + (val2 | (k << 4))); + } + + encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f]; + } + + // form integral number of 6-bit groups + if (fewerThan24bits == EIGHTBIT) { + b1 = binaryData[dataIndex]; + k = (byte) (b1 & 0x03); + if (fDebug) { + System.out.println("b1=" + b1); + System.out.println("b1<<2 = " + (b1 >> 2)); + } + byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); + encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4]; + encodedData[encodedIndex++] = PAD; + encodedData[encodedIndex++] = PAD; + } else if (fewerThan24bits == SIXTEENBIT) { + b1 = binaryData[dataIndex]; + b2 = binaryData[dataIndex + 1]; + l = (byte) (b2 & 0x0f); + k = (byte) (b1 & 0x03); + + byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); + byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0); + + encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2]; + encodedData[encodedIndex++] = PAD; + } + + return new String(encodedData); + } + + /** + * Decodes Base64 data into octects + * + * @param encoded string containing Base64 data + * @return Array containind decoded data. + */ + public static byte[] decode(String encoded) { + + if (encoded == null) { + return null; + } + + char[] base64Data = encoded.toCharArray(); + // remove white spaces + int len = removeWhiteSpace(base64Data); + + if (len % FOURBYTE != 0) { + return null;//should be divisible by four + } + + int numberQuadruple = (len / FOURBYTE); + + if (numberQuadruple == 0) { + return new byte[0]; + } + + byte decodedData[] = null; + byte b1 = 0, b2 = 0, b3 = 0, b4 = 0; + char d1 = 0, d2 = 0, d3 = 0, d4 = 0; + + int i = 0; + int encodedIndex = 0; + int dataIndex = 0; + decodedData = new byte[(numberQuadruple) * 3]; + + for (; i < numberQuadruple - 1; i++) { + + if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++])) + || !isData((d3 = base64Data[dataIndex++])) + || !isData((d4 = base64Data[dataIndex++]))) { + return null; + }//if found "no data" just return null + + b1 = base64Alphabet[d1]; + b2 = base64Alphabet[d2]; + b3 = base64Alphabet[d3]; + b4 = base64Alphabet[d4]; + + decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4); + decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); + decodedData[encodedIndex++] = (byte) (b3 << 6 | b4); + } + + if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))) { + return null;//if found "no data" just return null + } + + b1 = base64Alphabet[d1]; + b2 = base64Alphabet[d2]; + + d3 = base64Data[dataIndex++]; + d4 = base64Data[dataIndex++]; + if (!isData((d3)) || !isData((d4))) {//Check if they are PAD characters + if (isPad(d3) && isPad(d4)) { + if ((b2 & 0xf) != 0)//last 4 bits should be zero + { + return null; + } + byte[] tmp = new byte[i * 3 + 1]; + System.arraycopy(decodedData, 0, tmp, 0, i * 3); + tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); + return tmp; + } else if (!isPad(d3) && isPad(d4)) { + b3 = base64Alphabet[d3]; + if ((b3 & 0x3) != 0)//last 2 bits should be zero + { + return null; + } + byte[] tmp = new byte[i * 3 + 2]; + System.arraycopy(decodedData, 0, tmp, 0, i * 3); + tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4); + tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); + return tmp; + } else { + return null; + } + } else { //No PAD e.g 3cQl + b3 = base64Alphabet[d3]; + b4 = base64Alphabet[d4]; + decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4); + decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); + decodedData[encodedIndex++] = (byte) (b3 << 6 | b4); + + } + + return decodedData; + } + + /** + * remove WhiteSpace from MIME containing encoded Base64 data. + * + * @param data the byte array of base64 data (with WS) + * @return the new length + */ + private static int removeWhiteSpace(char[] data) { + if (data == null) { + return 0; + } + + // count characters that's not whitespace + int newSize = 0; + int len = data.length; + for (int i = 0; i < len; i++) { + if (!isWhiteSpace(data[i])) { + data[newSize++] = data[i]; + } + } + return newSize; + } +} diff --git a/hx_common/src/main/java/com/hx/util/rsa/RSASignature.java b/hx_common/src/main/java/com/hx/util/rsa/RSASignature.java new file mode 100644 index 0000000..cf7a0a5 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/rsa/RSASignature.java @@ -0,0 +1,195 @@ +package com.hx.util.rsa; + +import com.hx.util.StringUtils; +import org.bouncycastle.asn1.ASN1Encodable; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.ASN1Primitive; +import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; + +import java.security.KeyFactory; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + + +/** + * RSA绛惧悕楠岀绫� + */ +public class RSASignature{ + + /** + * 绛惧悕绠楁硶 + */ + public static final String SIGN_ALGORITHMS = "SHA1WithRSA"; + + /** + * RSA绛惧悕 + * @param content 寰呯鍚嶆暟鎹� + * @param privateKey 鍟嗘埛绉侀挜 + * @param encode 瀛楃闆嗙紪鐮� + * @return 绛惧悕鍊� + */ + public static String createSign(String content, String privateKey, String encode) { + try { + PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec( Base64.decode(privateKey) ); + + KeyFactory keyf = KeyFactory.getInstance("RSA"); + PrivateKey priKey = keyf.generatePrivate(priPKCS8); + + java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS); + + signature.initSign(priKey); + signature.update( content.getBytes(encode)); + + byte[] signed = signature.sign(); + + return Base64.encode(signed); + } + catch (Exception e) + { + e.printStackTrace(); + } + + return null; + } + + /** + * RSA绛惧悕Pkcs1ToPkcs8 + * @param rawKey 鍟嗘埛绉侀挜 + * @return 绛惧悕鍊� + */ + public static String formatPkcs1ToPkcs8(String rawKey) { + if (!StringUtils.isEmpty(rawKey)) { + try { + //灏咮ASE64缂栫爜鐨勭閽ュ瓧绗︿覆杩涜瑙g爜 + byte[] encodeByte = Base64.decode(rawKey); + AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(PKCSObjectIdentifiers.pkcs8ShroudedKeyBag); + PrivateKeyInfo privKeyInfo = new PrivateKeyInfo(algorithmIdentifier, ASN1ObjectIdentifier.fromByteArray(encodeByte)); + return Base64.encode(privKeyInfo.getEncoded()); + } catch (Exception e) { + e.printStackTrace(); + } + } + return null; + } + /** + * RSA绛惧悕Pkcs8ToPkcs1 + * @param rawKey 鍟嗘埛绉侀挜 + * @return 绛惧悕鍊� + */ + public static String formatPkcs8ToPkcs1(String rawKey){ + try { + byte[] encodeByte = Base64.decode(rawKey); + PrivateKeyInfo pki = PrivateKeyInfo.getInstance(encodeByte); + ASN1Encodable asn = pki.parsePrivateKey(); + ASN1Primitive primitive = asn.toASN1Primitive(); + return Base64.encode(primitive.getEncoded()); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public static String createSign(String content, String privateKey) { + try{ + PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec( Base64.decode(privateKey) ); + KeyFactory keyf = KeyFactory.getInstance("RSA"); + PrivateKey priKey = keyf.generatePrivate(priPKCS8); + java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS); + signature.initSign(priKey); + signature.update( content.getBytes()); + byte[] signed = signature.sign(); + return Base64.encode(signed); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** + * RSA楠岀鍚嶆鏌� + * @param content 寰呯鍚嶆暟鎹� + * @param sign 绛惧悕鍊� + * @param publicKey 鍒嗛厤缁欏紑鍙戝晢鍏挜 + * @param encode 瀛楃闆嗙紪鐮� + * @return 甯冨皵鍊� + */ + public static boolean doCheck(String content, String sign, String publicKey,String encode) { + try { + KeyFactory keyFactory = KeyFactory.getInstance("RSA"); + byte[] encodedKey = Base64.decode(publicKey); + PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey)); + + + java.security.Signature signature = java.security.Signature + .getInstance(SIGN_ALGORITHMS); + + signature.initVerify(pubKey); + signature.update( content.getBytes(encode) ); + + boolean bverify = signature.verify( Base64.decode(sign) ); + return bverify; + + } catch (Exception e) { + e.printStackTrace(); + } + + return false; + } + + public static boolean doCheck(String content, String sign, String publicKey) { + try { + KeyFactory keyFactory = KeyFactory.getInstance("RSA"); + byte[] encodedKey = Base64.decode(publicKey); + PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey)); + + + java.security.Signature signature = java.security.Signature + .getInstance(SIGN_ALGORITHMS); + + signature.initVerify(pubKey); + signature.update( content.getBytes() ); + + boolean bverify = signature.verify( Base64.decode(sign) ); + return bverify; + + } catch (Exception e) { + e.printStackTrace(); + } + + return false; + } + + /** + * ASCII鐮侀�掑鎺掑簭锛堝墧闄ょ┖鍊硷級 + * @param params + * @return + */ + public static String getSignCheckContent(Map<String, String> params) { + if (params == null) { + return null; + } else { + StringBuilder content = new StringBuilder(); + List<String> keys = new ArrayList(params.keySet()); + Collections.sort(keys); + + for(int i = 0; i < keys.size(); ++i) { + String key = (String)keys.get(i); + Object value = params.get(key); + if(value == null || StringUtils.isEmpty(value.toString())){ + continue; + } + content.append(i == 0 ? "" : "&").append(key).append("=").append(value); + } + return content.toString(); + } + } + +} diff --git a/hx_common/src/main/java/com/hx/util/rsa/RSAUtil.java b/hx_common/src/main/java/com/hx/util/rsa/RSAUtil.java new file mode 100644 index 0000000..f874515 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/rsa/RSAUtil.java @@ -0,0 +1,121 @@ +package com.hx.util.rsa; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import sun.misc.BASE64Decoder; +import sun.misc.BASE64Encoder; + +import javax.crypto.Cipher; +import java.io.IOException; +import java.security.*; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; + +public class RSAUtil { + + //log4j鏃ュ織 + private static Logger logger = LoggerFactory.getLogger(RSAUtil.class.getName()); + + /**鐢熸垚绉橀挜瀵�*/ + public static KeyPair getKeyPair() throws Exception { + KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); + keyPairGenerator.initialize(2048); + KeyPair keyPair = keyPairGenerator.generateKeyPair(); + return keyPair; + } + + /**鑾峰彇鍏挜(Base64缂栫爜)*/ + public static String getPublicKey(KeyPair keyPair) { + PublicKey publicKey = keyPair.getPublic(); + byte[] bytes = publicKey.getEncoded(); + return byte2Base64(bytes); + } + + /**鑾峰彇绉侀挜(Base64缂栫爜)*/ + public static String getPrivateKey(KeyPair keyPair) { + PrivateKey privateKey = keyPair.getPrivate(); + byte[] bytes = privateKey.getEncoded(); + return byte2Base64(bytes); + } + + /**灏咮ase64缂栫爜鍚庣殑鍏挜杞崲鎴怭ublicKey瀵硅薄*/ + public static PublicKey string2PublicKey(String pubStr) throws Exception { + byte[] keyBytes = base642Byte(pubStr); + X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes); + KeyFactory keyFactory = KeyFactory.getInstance("RSA"); + PublicKey publicKey = keyFactory.generatePublic(keySpec); + return publicKey; + } + + /**灏咮ase64缂栫爜鍚庣殑绉侀挜杞崲鎴怭rivateKey瀵硅薄*/ + public static PrivateKey string2PrivateKey(String priStr) throws Exception { + byte[] keyBytes = base642Byte(priStr); + PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes); + KeyFactory keyFactory = KeyFactory.getInstance("RSA"); + PrivateKey privateKey = keyFactory.generatePrivate(keySpec); + return privateKey; + } + + /**鍏挜鍔犲瘑*/ + public static String publicEncrypt(String content, String publicKey) { + try { + Cipher cipher = Cipher.getInstance("RSA"); + cipher.init(Cipher.ENCRYPT_MODE, string2PublicKey(publicKey)); + byte[] bytes = cipher.doFinal(content.getBytes()); + return byte2Base64(bytes); + } catch (Exception e) { + e.printStackTrace(); + //logger.error("鍏挜鍔犲瘑澶辫触{}", e); + } + return null; + } + + /**绉侀挜瑙e瘑*/ + public static String privateDecrypt(String content, String privateKey) { + try { + Cipher cipher = Cipher.getInstance("RSA"); + cipher.init(Cipher.DECRYPT_MODE, string2PrivateKey(privateKey)); + byte[] bytes = cipher.doFinal(base642Byte(content)); + return new String(bytes); + } catch (Exception e) { + //logger.error("绉侀挜瑙e瘑澶辫触{}", e); + } + return null; + } + + //瀛楄妭鏁扮粍杞珺ase64缂栫爜 + public static String byte2Base64(byte[] bytes) { + BASE64Encoder encoder = new BASE64Encoder(); + return encoder.encode(bytes); + } + + //Base64缂栫爜杞瓧鑺傛暟缁� + public static byte[] base642Byte(String base64Key) throws IOException { + BASE64Decoder decoder = new BASE64Decoder(); + return decoder.decodeBuffer(base64Key); + } + + public static void main(String[] args) { + try { + + KeyPair keyPair = getKeyPair(); + String publicKeyStr = getPublicKey(keyPair); + String privateKeyStr = getPrivateKey(keyPair); + System.out.println("publicKey:"+publicKeyStr); + System.out.println("privateKey:"+privateKeyStr); + + //String publicKeyStr = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCWY1VKIXGStXOMtSkb2nqV9A4V6MqlTPv8Dg9Sdxm8TZgOYJJxFAjpUOwt0au6q5JDTrslZngg9um1IhNJlRLEySbTvN7Bzeq6XOpZx5w6XRZ+7/o0Ui4YvcYwIHB5DgS5XJnLa3vLqWOk4NAtY0lqC20170mHi5Fmjdak63OTzwIDAQAB"; + //=================瀹㈡埛绔�================= + String message = "jia_he"; + //鐢ㄥ叕閽ュ姞瀵� + String byte2Base64 = RSAUtil.publicEncrypt(message, publicKeyStr); + System.out.println("鍏挜鍔犲瘑骞禕ase64缂栫爜鐨勭粨鏋滐細" + byte2Base64); + //===================鏈嶅姟绔�================ + //String privateKeyStr = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJZjVUohcZK1c4y1KRvaepX0DhXoyqVM+/wOD1J3GbxNmA5gknEUCOlQ7C3Rq7qrkkNOuyVmeCD26bUiE0mVEsTJJtO83sHN6rpc6lnHnDpdFn7v+jRSLhi9xjAgcHkOBLlcmctre8upY6Tg0C1jSWoLbTXvSYeLkWaN1qTrc5PPAgMBAAECgYAJuQBRm5npHzwKM8glmdllCnNCrVs0lqaP5CTPcw3B485Z15qAHwh4dRff2ndcySzalyN4RoirsOrpH/vZPP8KinIhOT9zcHInWMKEPqGH+twB+c0hS6x2YZFuJqW3+zy56jnUMn3MDjNF5A5N9hD6taP1V+UOqgZvYwwMSCFLkQJBANZtQS2AqahHNjPgjkWcuaG8zXzgbu0VeU+wXDjxR81aLLJBOK6AGe7w5yJnip2w/FqGxPfORcn/bLxyDHOhpQcCQQCzi5zeeiXt1cxeGGqVxNvC51PuSna9YnPs+phiwwGVdAqVdMOJzsThs5EDVhX4eQYIeA4B6PItiPLHsw+6AXD5AkAp/ac/4+xVeeyRaC40T6bCl5ieFc1jPEtPYbgNpqJrAneySLdy5L8vXZnF0QUCMICasb2s0YY1MoH2vVbW5hbNAkEAsCxD5oFQikiI2aN3ojGhuWMnFeB3Fmlueo+ByxaxjSZp5DDIVYZP5W8+0Vk9Aawu4Ux74h/i0g9Yud7XhZo4cQJARyq8WJGDawo65CVcQQ2opbL8LqApr7Co4CAKmV4YFDraY00q9h1Dbj7WO+urJz7XUqbEYG0Yga+37jQAnQHUUQ=="; + //瑙e瘑鍚庣殑鏄庢枃 + System.out.println("瑙e瘑鍚庣殑鏄庢枃: " +RSAUtil.privateDecrypt(byte2Base64, privateKeyStr)); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/hx_common/src/main/java/com/hx/util/thread/ExecutorServiceTool.java b/hx_common/src/main/java/com/hx/util/thread/ExecutorServiceTool.java new file mode 100644 index 0000000..d473ed9 --- /dev/null +++ b/hx_common/src/main/java/com/hx/util/thread/ExecutorServiceTool.java @@ -0,0 +1,150 @@ +package com.hx.util.thread; + +import lombok.Setter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.LinkedBlockingDeque; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + + +/** + * 鍒涘缓绾跨▼姹犵殑锛屼富瑕侀伩鍏嶇嚎绋嬮槦鍒楄秴锛屽鑷存湇鍔″櫒鐖嗕簡 + */ +public class ExecutorServiceTool { + + /**log4j鏃ュ織*/ + private static final Logger logger = LoggerFactory.getLogger(ExecutorServiceTool.class.getName()); + + /**绾跨▼姹�-鑾峰彇闃熷垪鐨�*/ + private ThreadPoolExecutor threadPool; + /**鏈�澶ч槦鍒�*/ + private int maxQueue; + /**鏈�澶х嚎绋嬫暟*/ + private int maxTread; + /**鍒涘缓闃熷垪*/ + private ThreadTaskLinkedBlockingDeque<Runnable> queue = new ThreadTaskLinkedBlockingDeque<>(); + + public ExecutorServiceTool() { + } + + public ExecutorServiceTool(int initTread, int maxQueue) { + createThread(initTread,maxQueue); + } + + public ExecutorServiceTool(int initTread, int maxTread, int maxQueue) { + this.maxTread = maxTread; + createThread(initTread,maxTread,maxQueue); + } + + + /**鍒涘缓绾跨▼姹� + * @param initTread 鍒濆鍖栫嚎绋嬫睜 + * @param maxQueue 鏈�澶ч槦鍒楁柊澧為槦鍒楋紝娉ㄦ剰锛氳繖閲屽彧鍋氫紶鍊硷紝涓嶉檺鍒剁湡瀵� + * 绾跨▼姹犻檺鍒堕槦鍒楋紝鍥犱负闄愬埗浜嗕細鎶ラ敊锛屽鑷存暟鎹涪澶� + * @return 绾跨▼姹� + */ + public ThreadPoolExecutor createThread(int initTread,int maxQueue){ + this.threadPool = new ThreadPoolExecutor(initTread, initTread, + 60L, TimeUnit.SECONDS, + new LinkedBlockingQueue<Runnable>()); + this.maxQueue = maxQueue; + return this.threadPool; + } + + /**鍒涘缓绾跨▼姹� + * @param initTread 鍒濆鍖栫嚎绋嬫睜 + * @param initTread 鏈�澶х嚎绋嬫暟 + * @param maxQueue 鏈�澶ч槦鍒楁柊澧為槦鍒楋紝娉ㄦ剰锛氳繖閲屽彧鍋氫紶鍊硷紝涓嶉檺鍒剁湡瀵� + * 绾跨▼姹犻檺鍒堕槦鍒楋紝鍥犱负闄愬埗浜嗕細鎶ラ敊锛屽鑷存暟鎹涪澶� + * @return 绾跨▼姹� + */ + public ThreadPoolExecutor createThread(int initTread,int maxTread,int maxQueue){ + this.threadPool = new ThreadPoolExecutor(initTread,maxTread,60L,TimeUnit.SECONDS,queue); + this.maxQueue = maxQueue; + return this.threadPool; + } + + /**寰幆鏍¢獙闃熷垪鏁伴噺妯″紡锛岄拡瀵规渶澶х殑闃熷垪锛岃繑鍥瀟rue灏辨槸鍙互鍔犲叆闃熷垪 + * 閬垮厤姝诲惊鐜紝璁剧疆浜嗗惊鐜牎楠屾鏁� + * @param sleepMillisecond 鐫$湢锛屾绉掔,濡傛灉鏄┖鐨勶紝閭d箞鐩存帴杩斿洖 + * @param frequency 寰幆鏍¢獙娆℃暟锛岀┖鍊奸粯璁�100娆℃暟 + * @return 鏈�鍚庨兘鏄繑鍥瀟rue + */ + public boolean whileCheckQueue(Integer sleepMillisecond,Integer frequency){ + if(frequency == null){ + frequency = 100; + } + while (frequency>0){ + if(!noRund(sleepMillisecond)){ + return true; + } + frequency--; + } + return true; + } + + /**閽堝鏈�澶х殑闃熷垪锛屽鏋滄病鏈夎秴杩囪繑鍥炴槸false鐨勶紝瓒呰繃灏辫繑鍥炴槸true鐨� + * 鍗曡繑鍥瀟rue鐨勬椂鍊欙紝灏变笉瑕佷紶鍏ラ槦鍒椾簡 + * @param sleepMillisecond 鐫$湢锛屾绉掔,濡傛灉鏄┖鐨勶紝閭d箞鐩存帴杩斿洖 + * @return 濡傛灉娌℃湁瓒呰繃杩斿洖鏄痜alse鐨勶紝瓒呰繃灏辫繑鍥炴槸true鐨� + */ + public boolean noRund(Integer sleepMillisecond){ + if(threadPool.getQueue().size() > maxQueue){ + if(sleepMillisecond != null && sleepMillisecond > 0){ + try{ + Thread.sleep(sleepMillisecond); + }catch (Exception e){ + logger.error("绾跨▼姹犲紑鍚潯鐪犲け璐ワ紒"); + } + } + return true; + }else{ + return false; + } + } + + /**鍏抽棴*/ + public void shutdown(){ + this.threadPool.shutdown(); + } + + /** + * 鑷畾涔夌嚎绋嬩换鍔¢樆濉為槦鍒�. 鍦ㄦ椿璺冪嚎绋嬫暟灏忎簬鏈�澶ф敮鎸佺嚎绋嬫暟鐨勬儏鍐典笅锛屾柊浠诲姟涓嶆斁鍒伴槦鍒椾粠鑰屾縺鍙戠嚎绋嬫睜鍒涘缓鏂扮嚎绋嬪強鏃跺鐞�. + * 瑙e喅浣跨敤LinkedBlockingDeque鏃犻檺闃熷垪锛岀嚎绋嬫睜鍙湁鏍稿績绾跨▼鍦ㄥ鐞嗐�俶aximumPoolSize鏈惎浣滅敤鐨勯棶棰樸�� + * + * @author chenjiahe + */ + @Setter + private class ThreadTaskLinkedBlockingDeque<E> extends LinkedBlockingDeque<E> { + @Override + public boolean offer(E e) { + int activeThreadNum = threadPool.getActiveCount(); + if (activeThreadNum < maxTread) { + return false; + } + return offerLast(e); + } + } + + /****************************************************************************************/ + + public int getMaxQueue() { + return maxQueue; + } + + public void setMaxQueue(int maxQueue) { + this.maxQueue = maxQueue; + } + + public ThreadPoolExecutor getThreadPool() { + return threadPool; + } + + public void setThreadPool(ThreadPoolExecutor threadPool) { + this.threadPool = threadPool; + } + +} diff --git a/hx_common/src/main/java/com/hx/wx/gzh/WxGzhUtil.java b/hx_common/src/main/java/com/hx/wx/gzh/WxGzhUtil.java new file mode 100644 index 0000000..f83aa4d --- /dev/null +++ b/hx_common/src/main/java/com/hx/wx/gzh/WxGzhUtil.java @@ -0,0 +1,174 @@ +package com.hx.wx.gzh; + +import com.hx.common.service.CommonService; +import com.hx.exception.TipsException; +import com.hx.util.HttpUtil; +import net.sf.json.JSONArray; +import net.sf.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/** + * 寰俊鍏紬鍙峰伐鍏风被 + * @author wzh + */ +public class WxGzhUtil { + + private static Logger logger = LoggerFactory.getLogger(WxGzhUtil.class); + + public static final String CREATE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/create"; + public static final String DELETE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/delete"; + public static final String GET_MENU_URL = "https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info"; + public static final String GET_MATERIAL_URL = "https://api.weixin.qq.com/cgi-bin/material/batchget_material"; + + + /** + * 鍒涘缓鍏紬鍙疯嚜瀹氫箟鑿滃崟 + * @param token + * @param dataString + * @return + */ + public static String createMenu (String token, String dataString) { + try { + return HttpUtil.post(CREATE_MENU_URL, token, dataString); + } catch (Exception e) { + logger.error("鏇存柊寰俊鍏紬鍙疯嚜瀹氫箟鑿滃崟澶辫触锛�" + e); + throw new TipsException("鏇存柊澶辫触"); + } + } + + /** + * 鍒犻櫎鍏紬鍙疯嚜瀹氫箟鑿滃崟 + * @param token + * @param dataString + * @return + */ + public static String deleteMenu (String token, String dataString) { + try { + return HttpUtil.post(DELETE_MENU_URL, token, dataString); + } catch (Exception e) { + logger.error("鍒犻櫎寰俊鍏紬鍙疯嚜瀹氫箟鑿滃崟澶辫触锛�" + e); + throw new TipsException("鍒犻櫎澶辫触"); + } + } + + /** + * 鏌ヨ涓庢媺鍙栧井淇″叕浼楀彿鑷畾涔夎彍鍗� + * @param token + * @return + */ + public static String getMenuInfo (String token, CommonService commonService) { + try { + String result = HttpUtil.post(GET_MENU_URL, token, ""); + JSONObject obj = JSONObject.fromObject(result); + JSONObject menuInfo = obj.getJSONObject("selfmenu_info"); + if (menuInfo != null) { + JSONArray button = menuInfo.getJSONArray("button"); +// if (button != null && button.size() > 0) { +// // 鍒犻櫎鏃ф暟鎹� +// SqlSentence sqlSentence = new SqlSentence(); +// Map<String,Object> sqlMap = new HashMap<>(); +// sqlMap.put("isDel", BaseEntity.NO); +// sqlMap.put("del", BaseEntity.YES); +// sqlSentence.sqlSentence(" isDel = #{m.del} where isDel = #{m.isDel}", sqlMap); +// commonService.updateWhere(MenuMapper.class, sqlSentence); +// button.forEach(b -> { +// JSONObject j = JSONObject.fromObject(b); +// if (j != null) { +// getButton(j, commonService, ""); +// } +// }); +// } + } + return result; + } catch (Exception e) { + logger.error("鏌ヨ寰俊鍏紬鍙疯嚜瀹氫箟鑿滃崟澶辫触锛�" + e); + throw new TipsException("鏌ヨ澶辫触"); + } + } + + /** + * 鑾峰彇绱犳潗鍒楄〃 + * @param token + * @return + */ + public static JSONObject materialList (String token, String request) { + try { + return HttpUtil.HttpURLUtil("https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token="+token,request); + } catch (Exception e) { + logger.error("鑾峰彇绱犳潗鍒楄〃锛�" + e); + throw new TipsException("鑾峰彇绱犳潗鍒楄〃"); + } + } + + /** + * 鑾峰彇绱犳潗鍒楄〃 + * @param token + * @return + */ + public static JSONObject qrcodeCreate (String token, String request) { + try { + return HttpUtil.HttpURLUtil("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token="+token,request); + } catch (Exception e) { + logger.error("鑾峰彇浜岀淮鐮佷俊鎭細" + e); + throw new TipsException("鑾峰彇浜岀淮鐮佷俊鎭け璐�"); + } + } + + /** + * 鑾峰彇妯℃澘鍒楄〃 + * @param token + * @return + */ + public static JSONObject templateList (String token, String request) { + try { + return HttpUtil.HttpURLUtil("https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token="+token,request); + } catch (Exception e) { + logger.error("鑾峰彇妯℃澘鍒楄〃锛�" + e); + throw new TipsException("鑾峰彇妯℃澘鍒楄〃澶辫触"); + } + } + + /** + * 鍙戦�佹ā鏉挎秷鎭� + * @param token + * @return + */ + public static JSONObject templateSend (String token, String request) { + try { + return HttpUtil.HttpURLUtil("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token,request); + } catch (Exception e) { + logger.error("鍙戦�佹ā鏉挎秷鎭細" + e); + throw new TipsException("鍙戦�佹ā鏉挎秷鎭け璐�"); + } + } + + /** + * 鑾峰彇姘镐箙绱犳潗 + * @param token + * @return + */ + public static JSONObject mediaGet (String token, String request) { + try { + return HttpUtil.HttpURLUtil("https://api.weixin.qq.com/cgi-bin/material/get_material?access_token="+token,request); + } catch (Exception e) { + logger.error("鑾峰彇姘镐箙绱犳潗锛�" + e); + throw new TipsException("鑾峰彇姘镐箙绱犳潗澶辫触"); + } + } + + /** + * 鎵归噺鑾峰彇鐢ㄦ埛鍩烘湰淇℃伅 + * @param token + * @return + */ + public static JSONObject batchGetUserInfo (String token, String request) { + try { + return HttpUtil.HttpURLUtil("https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token="+token,request); + } catch (Exception e) { + logger.error("鎵归噺鑾峰彇鐢ㄦ埛鍩烘湰淇℃伅锛�" + e); + throw new TipsException("鎵归噺鑾峰彇鐢ㄦ埛鍩烘湰淇℃伅"); + } + } +} diff --git a/hx_common/src/main/java/com/hz/util/http/HttpHzUtil.java b/hx_common/src/main/java/com/hz/util/http/HttpHzUtil.java new file mode 100644 index 0000000..1f8e24e --- /dev/null +++ b/hx_common/src/main/java/com/hz/util/http/HttpHzUtil.java @@ -0,0 +1,114 @@ +package com.hz.util.http; + +import com.hx.util.StringUtils; +import com.hz.util.http.dto.HttpHzResponse; +import org.apache.commons.io.IOUtils; + +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.SocketTimeoutException; +import java.net.URL; +import java.util.Iterator; +import java.util.Map; + +public class HttpHzUtil { + + /** + * 璇锋眰鏂规硶 + */ + public static final String METHOD_POST = "POST"; + /** + * 缂栫爜 + */ + public static final String CHARSET = "UTF-8"; + + + /** + * 璇锋眰 + * + * @param url 璇锋眰閾炬帴 + * @param bodyData 璇锋眰body鏁版嵁 + * @param keyValues 杩炴帴鎼哄甫鍙傛暟 + * @param header 琛ㄥご鎼哄甫鍙傛暟 + * @param requestMethod 璇锋眰绫诲瀷锛岄粯璁わ細POST + * @param outTime 瓒呮椂鏃堕棿锛堟绉掞級,榛樿锛�300000 + * @return + */ + public static HttpHzResponse HttpURLUtilJson(String url, String bodyData, Map<String, Object> keyValues, Map<String, String> header, String requestMethod, Integer outTime) { + HttpHzResponse httpHzResponse = new HttpHzResponse(); + HttpURLConnection con = null; + try { + StringBuilder dataP = new StringBuilder(); + Iterator var9; + Map.Entry entry; + if (keyValues != null && !keyValues.isEmpty()) { + var9 = keyValues.entrySet().iterator(); + + while (var9.hasNext()) { + entry = (Map.Entry) var9.next(); + dataP.append((String) entry.getKey()).append("="); + dataP.append(entry.getValue()); + dataP.append("&"); + } + + dataP.deleteCharAt(dataP.length() - 1); + url = url + "?" + dataP; + } + + if (StringUtils.isEmpty(requestMethod)) { + requestMethod = METHOD_POST; + } + + if (outTime == null || outTime < 0) { + outTime = 300000; + } + + URL httpUrl = new URL(url); + con = (HttpURLConnection) httpUrl.openConnection(); + con.setRequestMethod(requestMethod); + con.setDoOutput(true); + con.setDoInput(true); + con.setUseCaches(false); + con.setReadTimeout(outTime); + con.setRequestProperty("Charset", CHARSET); + con.setRequestProperty("Content-Type", "application/json"); + if (header != null) { + var9 = header.entrySet().iterator(); + + while (var9.hasNext()) { + entry = (Map.Entry) var9.next(); + con.setRequestProperty((String) entry.getKey(), (String) entry.getValue()); + } + } + + if (bodyData != null) { + OutputStream os = con.getOutputStream(); + os.write(bodyData.getBytes(CHARSET)); + } + + httpHzResponse.setCode(con.getResponseCode() + ""); + if (con.getErrorStream() != null) { + httpHzResponse.setMsg(IOUtils.toString(con.getErrorStream(), CHARSET)); + } + if (HttpURLConnection.HTTP_OK == con.getResponseCode() || HttpURLConnection.HTTP_CREATED == con.getResponseCode()) { + httpHzResponse.setData(IOUtils.toString(con.getInputStream(), CHARSET)); + } + + }catch (SocketTimeoutException var15) { + httpHzResponse.setMsg(var15.getMessage()); + httpHzResponse.setCode(HttpHzResponse.CODE_TIME_OUT); + var15.printStackTrace(); + } catch (Exception var14) { + httpHzResponse.setMsg(var14.getMessage()); + var14.printStackTrace(); + } finally { + if (con != null) { + con.disconnect(); + } + + } + + return httpHzResponse; + } + +} diff --git a/hx_common/src/main/java/com/hz/util/http/dto/HttpHzResponse.java b/hx_common/src/main/java/com/hz/util/http/dto/HttpHzResponse.java new file mode 100644 index 0000000..036ba99 --- /dev/null +++ b/hx_common/src/main/java/com/hz/util/http/dto/HttpHzResponse.java @@ -0,0 +1,63 @@ +package com.hz.util.http.dto; + +import com.hx.exception.TipsException; + +/** + * 璇锋眰杩斿洖缁熶竴dto + */ +public class HttpHzResponse { + + /**璇锋眰鐘舵��*/ + private String code; + /**閿欒淇℃伅*/ + private String msg; + /**杩斿洖淇℃伅*/ + private String data; + + /**璇锋眰杩斿洖鐘舵��-鎴愬姛*/ + public static final String CODE_200 = "200"; + /**璇锋眰杩斿洖鐘舵��-鎴愬姛*/ + public static final String CODE_201 = "201"; + /**璇锋眰鐘舵��-瓒呮椂*/ + public static final String CODE_TIME_OUT = "time_out"; + + /**灏佽鏍¢獙璇锋眰鐮佹柟娉曪紝娌℃湁杩涜閿欒鎻愮ず*/ + public boolean checkRequesCode(){ + if(CODE_200.equals(code) || CODE_201.equals(code)){ + return true; + } + return false; + } + + /**灏佽鏍¢獙璇锋眰鐮佹柟娉曪紝杩涜閿欒鎻愮ず*/ + public void checkRequesThrow(){ + if(!CODE_200.equals(code) && !CODE_201.equals(code)){ + throw new TipsException("璇锋眰URL澶辫触锛�"+this.msg); + } + + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } +} diff --git a/hx_common/src/main/java/com/qq/weixin/mp/aes/AesException.java b/hx_common/src/main/java/com/qq/weixin/mp/aes/AesException.java new file mode 100644 index 0000000..63b2ed7 --- /dev/null +++ b/hx_common/src/main/java/com/qq/weixin/mp/aes/AesException.java @@ -0,0 +1,59 @@ +package com.qq.weixin.mp.aes; + +@SuppressWarnings("serial") +public class AesException extends Exception { + + public final static int OK = 0; + public final static int ValidateSignatureError = -40001; + public final static int ParseXmlError = -40002; + public final static int ComputeSignatureError = -40003; + public final static int IllegalAesKey = -40004; + public final static int ValidateCorpidError = -40005; + public final static int EncryptAESError = -40006; + public final static int DecryptAESError = -40007; + public final static int IllegalBuffer = -40008; + //public final static int EncodeBase64Error = -40009; + //public final static int DecodeBase64Error = -40010; + //public final static int GenReturnXmlError = -40011; + + private int code; + + private static String getMessage(int code) { + switch (code) { + case ValidateSignatureError: + return "绛惧悕楠岃瘉閿欒"; + case ParseXmlError: + return "xml瑙f瀽澶辫触"; + case ComputeSignatureError: + return "sha鍔犲瘑鐢熸垚绛惧悕澶辫触"; + case IllegalAesKey: + return "SymmetricKey闈炴硶"; + case ValidateCorpidError: + return "corpid鏍¢獙澶辫触"; + case EncryptAESError: + return "aes鍔犲瘑澶辫触"; + case DecryptAESError: + return "aes瑙e瘑澶辫触"; + case IllegalBuffer: + return "瑙e瘑鍚庡緱鍒扮殑buffer闈炴硶"; +// case EncodeBase64Error: +// return "base64鍔犲瘑閿欒"; +// case DecodeBase64Error: +// return "base64瑙e瘑閿欒"; +// case GenReturnXmlError: +// return "xml鐢熸垚澶辫触"; + default: + return null; // cannot be + } + } + + public int getCode() { + return code; + } + + AesException(int code) { + super(getMessage(code)); + this.code = code; + } + +} diff --git a/hx_common/src/main/java/com/qq/weixin/mp/aes/ByteGroup.java b/hx_common/src/main/java/com/qq/weixin/mp/aes/ByteGroup.java new file mode 100644 index 0000000..6ba4330 --- /dev/null +++ b/hx_common/src/main/java/com/qq/weixin/mp/aes/ByteGroup.java @@ -0,0 +1,26 @@ +package com.qq.weixin.mp.aes; + +import java.util.ArrayList; + +class ByteGroup { + ArrayList<Byte> byteContainer = new ArrayList<Byte>(); + + public byte[] toBytes() { + byte[] bytes = new byte[byteContainer.size()]; + for (int i = 0; i < byteContainer.size(); i++) { + bytes[i] = byteContainer.get(i); + } + return bytes; + } + + public ByteGroup addBytes(byte[] bytes) { + for (byte b : bytes) { + byteContainer.add(b); + } + return this; + } + + public int size() { + return byteContainer.size(); + } +} diff --git a/hx_common/src/main/java/com/qq/weixin/mp/aes/PKCS7Encoder.java b/hx_common/src/main/java/com/qq/weixin/mp/aes/PKCS7Encoder.java new file mode 100644 index 0000000..f1dd021 --- /dev/null +++ b/hx_common/src/main/java/com/qq/weixin/mp/aes/PKCS7Encoder.java @@ -0,0 +1,67 @@ +/** + * 瀵逛紒涓氬井淇″彂閫佺粰浼佷笟鍚庡彴鐨勬秷鎭姞瑙e瘑绀轰緥浠g爜. + * + * @copyright Copyright (c) 1998-2014 Tencent Inc. + */ + +// ------------------------------------------------------------------------ + +package com.qq.weixin.mp.aes; + +import java.nio.charset.Charset; +import java.util.Arrays; + +/** + * 鎻愪緵鍩轰簬PKCS7绠楁硶鐨勫姞瑙e瘑鎺ュ彛. + */ +class PKCS7Encoder { + static Charset CHARSET = Charset.forName("utf-8"); + static int BLOCK_SIZE = 32; + + /** + * 鑾峰緱瀵规槑鏂囪繘琛岃ˉ浣嶅~鍏呯殑瀛楄妭. + * + * @param count 闇�瑕佽繘琛屽~鍏呰ˉ浣嶆搷浣滅殑鏄庢枃瀛楄妭涓暟 + * @return 琛ラ綈鐢ㄧ殑瀛楄妭鏁扮粍 + */ + static byte[] encode(int count) { + // 璁$畻闇�瑕佸~鍏呯殑浣嶆暟 + int amountToPad = BLOCK_SIZE - (count % BLOCK_SIZE); + if (amountToPad == 0) { + amountToPad = BLOCK_SIZE; + } + // 鑾峰緱琛ヤ綅鎵�鐢ㄧ殑瀛楃 + char padChr = chr(amountToPad); + String tmp = new String(); + for (int index = 0; index < amountToPad; index++) { + tmp += padChr; + } + return tmp.getBytes(CHARSET); + } + + /** + * 鍒犻櫎瑙e瘑鍚庢槑鏂囩殑琛ヤ綅瀛楃 + * + * @param decrypted 瑙e瘑鍚庣殑鏄庢枃 + * @return 鍒犻櫎琛ヤ綅瀛楃鍚庣殑鏄庢枃 + */ + static byte[] decode(byte[] decrypted) { + int pad = (int) decrypted[decrypted.length - 1]; + if (pad < 1 || pad > 32) { + pad = 0; + } + return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad); + } + + /** + * 灏嗘暟瀛楄浆鍖栨垚ASCII鐮佸搴旂殑瀛楃锛岀敤浜庡鏄庢枃杩涜琛ョ爜 + * + * @param a 闇�瑕佽浆鍖栫殑鏁板瓧 + * @return 杞寲寰楀埌鐨勫瓧绗� + */ + static char chr(int a) { + byte target = (byte) (a & 0xFF); + return (char) target; + } + +} diff --git a/hx_common/src/main/java/com/qq/weixin/mp/aes/SHA1.java b/hx_common/src/main/java/com/qq/weixin/mp/aes/SHA1.java new file mode 100644 index 0000000..e460191 --- /dev/null +++ b/hx_common/src/main/java/com/qq/weixin/mp/aes/SHA1.java @@ -0,0 +1,61 @@ +/** + * 瀵逛紒涓氬井淇″彂閫佺粰浼佷笟鍚庡彴鐨勬秷鎭姞瑙e瘑绀轰緥浠g爜. + * + * @copyright Copyright (c) 1998-2014 Tencent Inc. + */ + +// ------------------------------------------------------------------------ + +package com.qq.weixin.mp.aes; + +import java.security.MessageDigest; +import java.util.Arrays; + +/** + * SHA1 class + * + * 璁$畻娑堟伅绛惧悕鎺ュ彛. + */ +class SHA1 { + + /** + * 鐢⊿HA1绠楁硶鐢熸垚瀹夊叏绛惧悕 + * @param token 绁ㄦ嵁 + * @param timestamp 鏃堕棿鎴� + * @param nonce 闅忔満瀛楃涓� + * @param encrypt 瀵嗘枃 + * @return 瀹夊叏绛惧悕 + * @throws AesException + */ + public static String getSHA1(String token, String timestamp, String nonce, String encrypt) throws AesException + { + try { + String[] array = new String[] { token, timestamp, nonce, encrypt }; + StringBuffer sb = new StringBuffer(); + // 瀛楃涓叉帓搴� + Arrays.sort(array); + for (int i = 0; i < 4; i++) { + sb.append(array[i]); + } + String str = sb.toString(); + // SHA1绛惧悕鐢熸垚 + MessageDigest md = MessageDigest.getInstance("SHA-1"); + md.update(str.getBytes()); + byte[] digest = md.digest(); + + StringBuffer hexstr = new StringBuffer(); + String shaHex = ""; + for (int i = 0; i < digest.length; i++) { + shaHex = Integer.toHexString(digest[i] & 0xFF); + if (shaHex.length() < 2) { + hexstr.append(0); + } + hexstr.append(shaHex); + } + return hexstr.toString(); + } catch (Exception e) { + e.printStackTrace(); + throw new AesException(AesException.ComputeSignatureError); + } + } +} diff --git a/hx_common/src/main/java/com/qq/weixin/mp/aes/WXBizMsgCrypt.java b/hx_common/src/main/java/com/qq/weixin/mp/aes/WXBizMsgCrypt.java new file mode 100644 index 0000000..308b1a0 --- /dev/null +++ b/hx_common/src/main/java/com/qq/weixin/mp/aes/WXBizMsgCrypt.java @@ -0,0 +1,296 @@ +/** + * 瀵逛紒涓氬井淇″彂閫佺粰浼佷笟鍚庡彴鐨勬秷鎭姞瑙e瘑绀轰緥浠g爜. + * + * @copyright Copyright (c) 1998-2014 Tencent Inc. + */ + +// ------------------------------------------------------------------------ + +/** + * 閽堝org.apache.commons.codec.binary.Base64锛� + * 闇�瑕佸鍏ユ灦鍖卌ommons-codec-1.9锛堟垨commons-codec-1.8绛夊叾浠栫増鏈級 + * 瀹樻柟涓嬭浇鍦板潃锛歨ttp://commons.apache.org/proper/commons-codec/download_codec.cgi + */ +package com.qq.weixin.mp.aes; + +import java.nio.charset.Charset; +import java.util.Arrays; +import java.util.Random; + +import javax.crypto.Cipher; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; + +import org.apache.commons.codec.binary.Base64; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * 鎻愪緵鎺ユ敹鍜屾帹閫佺粰浼佷笟寰俊娑堟伅鐨勫姞瑙e瘑鎺ュ彛(UTF8缂栫爜鐨勫瓧绗︿覆). + * <ol> + * <li>绗笁鏂瑰洖澶嶅姞瀵嗘秷鎭粰浼佷笟寰俊</li> + * <li>绗笁鏂规敹鍒颁紒涓氬井淇″彂閫佺殑娑堟伅锛岄獙璇佹秷鎭殑瀹夊叏鎬э紝骞跺娑堟伅杩涜瑙e瘑銆�</li> + * </ol> + * 璇存槑锛氬紓甯竕ava.security.InvalidKeyException:illegal Key Size鐨勮В鍐虫柟妗� + * <ol> + * <li>鍦ㄥ畼鏂圭綉绔欎笅杞絁CE鏃犻檺鍒舵潈闄愮瓥鐣ユ枃浠讹紙JDK7鐨勪笅杞藉湴鍧�锛� + * http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html</li> + * <li>涓嬭浇鍚庤В鍘嬶紝鍙互鐪嬪埌local_policy.jar鍜孶S_export_policy.jar浠ュ強readme.txt</li> + * <li>濡傛灉瀹夎浜咼RE锛屽皢涓や釜jar鏂囦欢鏀惧埌%JRE_HOME%\lib\security鐩綍涓嬭鐩栧師鏉ョ殑鏂囦欢</li> + * <li>濡傛灉瀹夎浜咼DK锛屽皢涓や釜jar鏂囦欢鏀惧埌%JDK_HOME%\jre\lib\security鐩綍涓嬭鐩栧師鏉ユ枃浠�</li> + * </ol> + */ +public class WXBizMsgCrypt { + + //log4j鏃ュ織 + private static Logger logger = LoggerFactory.getLogger(WXBizMsgCrypt.class.getName()); + + static Charset CHARSET = Charset.forName("utf-8"); + Base64 base64 = new Base64(); + byte[] aesKey; + String token; + String receiveid; + + /** + * 鏋勯�犲嚱鏁� + * @param token 浼佷笟寰俊鍚庡彴锛屽紑鍙戣�呰缃殑token + * @param encodingAesKey 浼佷笟寰俊鍚庡彴锛屽紑鍙戣�呰缃殑EncodingAESKey + * @param receiveid, 涓嶅悓鍦烘櫙鍚箟涓嶅悓锛岃瑙佹枃妗� + * + * @throws AesException 鎵ц澶辫触锛岃鏌ョ湅璇ュ紓甯哥殑閿欒鐮佸拰鍏蜂綋鐨勯敊璇俊鎭� + */ + public WXBizMsgCrypt(String token, String encodingAesKey, String receiveid) throws AesException { + if (encodingAesKey.length() != 43) { + throw new AesException(AesException.IllegalAesKey); + } + + this.token = token; + this.receiveid = receiveid; + aesKey = Base64.decodeBase64(encodingAesKey + "="); + } + + // 鐢熸垚4涓瓧鑺傜殑缃戠粶瀛楄妭搴� + byte[] getNetworkBytesOrder(int sourceNumber) { + byte[] orderBytes = new byte[4]; + orderBytes[3] = (byte) (sourceNumber & 0xFF); + orderBytes[2] = (byte) (sourceNumber >> 8 & 0xFF); + orderBytes[1] = (byte) (sourceNumber >> 16 & 0xFF); + orderBytes[0] = (byte) (sourceNumber >> 24 & 0xFF); + return orderBytes; + } + + // 杩樺師4涓瓧鑺傜殑缃戠粶瀛楄妭搴� + int recoverNetworkBytesOrder(byte[] orderBytes) { + int sourceNumber = 0; + for (int i = 0; i < 4; i++) { + sourceNumber <<= 8; + sourceNumber |= orderBytes[i] & 0xff; + } + return sourceNumber; + } + + // 闅忔満鐢熸垚16浣嶅瓧绗︿覆 + String getRandomStr() { + String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + Random random = new Random(); + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < 16; i++) { + int number = random.nextInt(base.length()); + sb.append(base.charAt(number)); + } + return sb.toString(); + } + + /** + * 瀵规槑鏂囪繘琛屽姞瀵�. + * + * @param text 闇�瑕佸姞瀵嗙殑鏄庢枃 + * @return 鍔犲瘑鍚巄ase64缂栫爜鐨勫瓧绗︿覆 + * @throws AesException aes鍔犲瘑澶辫触 + */ + String encrypt(String randomStr, String text) throws AesException { + ByteGroup byteCollector = new ByteGroup(); + byte[] randomStrBytes = randomStr.getBytes(CHARSET); + byte[] textBytes = text.getBytes(CHARSET); + byte[] networkBytesOrder = getNetworkBytesOrder(textBytes.length); + byte[] receiveidBytes = receiveid.getBytes(CHARSET); + + // randomStr + networkBytesOrder + text + receiveid + byteCollector.addBytes(randomStrBytes); + byteCollector.addBytes(networkBytesOrder); + byteCollector.addBytes(textBytes); + byteCollector.addBytes(receiveidBytes); + + // ... + pad: 浣跨敤鑷畾涔夌殑濉厖鏂瑰紡瀵规槑鏂囪繘琛岃ˉ浣嶅~鍏� + byte[] padBytes = PKCS7Encoder.encode(byteCollector.size()); + byteCollector.addBytes(padBytes); + + // 鑾峰緱鏈�缁堢殑瀛楄妭娴�, 鏈姞瀵� + byte[] unencrypted = byteCollector.toBytes(); + + try { + // 璁剧疆鍔犲瘑妯″紡涓篈ES鐨凜BC妯″紡 + Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); + SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES"); + IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16); + cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv); + + // 鍔犲瘑 + byte[] encrypted = cipher.doFinal(unencrypted); + + // 浣跨敤BASE64瀵瑰姞瀵嗗悗鐨勫瓧绗︿覆杩涜缂栫爜 + String base64Encrypted = base64.encodeToString(encrypted); + + return base64Encrypted; + } catch (Exception e) { + e.printStackTrace(); + throw new AesException(AesException.EncryptAESError); + } + } + + /** + * 瀵瑰瘑鏂囪繘琛岃В瀵�. + * + * @param text 闇�瑕佽В瀵嗙殑瀵嗘枃 + * @return 瑙e瘑寰楀埌鐨勬槑鏂� + * @throws AesException aes瑙e瘑澶辫触 + */ + String decrypt(String text) throws AesException { + byte[] original; + try { + // 璁剧疆瑙e瘑妯″紡涓篈ES鐨凜BC妯″紡 + Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); + SecretKeySpec key_spec = new SecretKeySpec(aesKey, "AES"); + IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(aesKey, 0, 16)); + cipher.init(Cipher.DECRYPT_MODE, key_spec, iv); + + // 浣跨敤BASE64瀵瑰瘑鏂囪繘琛岃В鐮� + byte[] encrypted = Base64.decodeBase64(text); + + // 瑙e瘑 + original = cipher.doFinal(encrypted); + } catch (Exception e) { + logger.info("aes瑙e瘑鎶ラ敊锛�",e); + e.printStackTrace(); + throw new AesException(AesException.DecryptAESError); + } + + String xmlContent, from_receiveid; + try { + // 鍘婚櫎琛ヤ綅瀛楃 + byte[] bytes = PKCS7Encoder.decode(original); + + // 鍒嗙16浣嶉殢鏈哄瓧绗︿覆,缃戠粶瀛楄妭搴忓拰receiveid + byte[] networkOrder = Arrays.copyOfRange(bytes, 16, 20); + + int xmlLength = recoverNetworkBytesOrder(networkOrder); + + xmlContent = new String(Arrays.copyOfRange(bytes, 20, 20 + xmlLength), CHARSET); + from_receiveid = new String(Arrays.copyOfRange(bytes, 20 + xmlLength, bytes.length), + CHARSET); + } catch (Exception e) { + e.printStackTrace(); + throw new AesException(AesException.IllegalBuffer); + } + + // receiveid涓嶇浉鍚岀殑鎯呭喌 + if (!from_receiveid.equals(receiveid)) { + throw new AesException(AesException.ValidateCorpidError); + } + return xmlContent; + + } + + /** + * 灏嗕紒涓氬井淇″洖澶嶇敤鎴风殑娑堟伅鍔犲瘑鎵撳寘. + * <ol> + * <li>瀵硅鍙戦�佺殑娑堟伅杩涜AES-CBC鍔犲瘑</li> + * <li>鐢熸垚瀹夊叏绛惧悕</li> + * <li>灏嗘秷鎭瘑鏂囧拰瀹夊叏绛惧悕鎵撳寘鎴恱ml鏍煎紡</li> + * </ol> + * + * @param replyMsg 浼佷笟寰俊寰呭洖澶嶇敤鎴风殑娑堟伅锛寈ml鏍煎紡鐨勫瓧绗︿覆 + * @param timeStamp 鏃堕棿鎴筹紝鍙互鑷繁鐢熸垚锛屼篃鍙互鐢║RL鍙傛暟鐨則imestamp + * @param nonce 闅忔満涓诧紝鍙互鑷繁鐢熸垚锛屼篃鍙互鐢║RL鍙傛暟鐨刵once + * + * @return 鍔犲瘑鍚庣殑鍙互鐩存帴鍥炲鐢ㄦ埛鐨勫瘑鏂囷紝鍖呮嫭msg_signature, timestamp, nonce, encrypt鐨剎ml鏍煎紡鐨勫瓧绗︿覆 + * @throws AesException 鎵ц澶辫触锛岃鏌ョ湅璇ュ紓甯哥殑閿欒鐮佸拰鍏蜂綋鐨勯敊璇俊鎭� + */ + public String EncryptMsg(String replyMsg, String timeStamp, String nonce) throws AesException { + // 鍔犲瘑 + String encrypt = encrypt(getRandomStr(), replyMsg); + + // 鐢熸垚瀹夊叏绛惧悕 + if (timeStamp == "") { + timeStamp = Long.toString(System.currentTimeMillis()); + } + + String signature = SHA1.getSHA1(token, timeStamp, nonce, encrypt); + + // System.out.println("鍙戦�佺粰骞冲彴鐨勭鍚嶆槸: " + signature[1].toString()); + // 鐢熸垚鍙戦�佺殑xml + String result = XMLParse.generate(encrypt, signature, timeStamp, nonce); + return result; + } + + /** + * 妫�楠屾秷鎭殑鐪熷疄鎬э紝骞朵笖鑾峰彇瑙e瘑鍚庣殑鏄庢枃. + * <ol> + * <li>鍒╃敤鏀跺埌鐨勫瘑鏂囩敓鎴愬畨鍏ㄧ鍚嶏紝杩涜绛惧悕楠岃瘉</li> + * <li>鑻ラ獙璇侀�氳繃锛屽垯鎻愬彇xml涓殑鍔犲瘑娑堟伅</li> + * <li>瀵规秷鎭繘琛岃В瀵�</li> + * </ol> + * + * @param msgSignature 绛惧悕涓诧紝瀵瑰簲URL鍙傛暟鐨刴sg_signature + * @param timeStamp 鏃堕棿鎴筹紝瀵瑰簲URL鍙傛暟鐨則imestamp + * @param nonce 闅忔満涓诧紝瀵瑰簲URL鍙傛暟鐨刵once + * @param postData 瀵嗘枃锛屽搴擯OST璇锋眰鐨勬暟鎹� + * + * @return 瑙e瘑鍚庣殑鍘熸枃 + * @throws AesException 鎵ц澶辫触锛岃鏌ョ湅璇ュ紓甯哥殑閿欒鐮佸拰鍏蜂綋鐨勯敊璇俊鎭� + */ + public String DecryptMsg(String msgSignature, String timeStamp, String nonce, String postData) + throws AesException { + + // 瀵嗛挜锛屽叕浼楄处鍙风殑app secret + // 鎻愬彇瀵嗘枃 + Object[] encrypt = XMLParse.extract(postData); + + // 楠岃瘉瀹夊叏绛惧悕 + String signature = SHA1.getSHA1(token, timeStamp, nonce, encrypt[1].toString()); + + // 鍜孶RL涓殑绛惧悕姣旇緝鏄惁鐩哥瓑 + // System.out.println("绗笁鏂规敹鍒癠RL涓殑绛惧悕锛�" + msg_sign); + // System.out.println("绗笁鏂规牎楠岀鍚嶏細" + signature); + if (!signature.equals(msgSignature)) { + throw new AesException(AesException.ValidateSignatureError); + } + + // 瑙e瘑 + String result = decrypt(encrypt[1].toString()); + return result; + } + + /** + * 楠岃瘉URL + * @param msgSignature 绛惧悕涓诧紝瀵瑰簲URL鍙傛暟鐨刴sg_signature + * @param timeStamp 鏃堕棿鎴筹紝瀵瑰簲URL鍙傛暟鐨則imestamp + * @param nonce 闅忔満涓诧紝瀵瑰簲URL鍙傛暟鐨刵once + * @param echoStr 闅忔満涓诧紝瀵瑰簲URL鍙傛暟鐨別chostr + * + * @return 瑙e瘑涔嬪悗鐨別chostr + * @throws AesException 鎵ц澶辫触锛岃鏌ョ湅璇ュ紓甯哥殑閿欒鐮佸拰鍏蜂綋鐨勯敊璇俊鎭� + */ + public String VerifyURL(String msgSignature, String timeStamp, String nonce, String echoStr) + throws AesException { + String signature = SHA1.getSHA1(token, timeStamp, nonce, echoStr); + + if (!signature.equals(msgSignature)) { + throw new AesException(AesException.ValidateSignatureError); + } + + String result = decrypt(echoStr); + return result; + } + +} \ No newline at end of file diff --git a/hx_common/src/main/java/com/qq/weixin/mp/aes/XMLParse.java b/hx_common/src/main/java/com/qq/weixin/mp/aes/XMLParse.java new file mode 100644 index 0000000..4e5b652 --- /dev/null +++ b/hx_common/src/main/java/com/qq/weixin/mp/aes/XMLParse.java @@ -0,0 +1,106 @@ +/** + * 瀵逛紒涓氬井淇″彂閫佺粰浼佷笟鍚庡彴鐨勬秷鎭姞瑙e瘑绀轰緥浠g爜. + * + * @copyright Copyright (c) 1998-2014 Tencent Inc. + */ + +// ------------------------------------------------------------------------ + +package com.qq.weixin.mp.aes; + +import java.io.StringReader; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; + +/** + * XMLParse class + * + * 鎻愪緵鎻愬彇娑堟伅鏍煎紡涓殑瀵嗘枃鍙婄敓鎴愬洖澶嶆秷鎭牸寮忕殑鎺ュ彛. + */ +class XMLParse { + + /** + * 鎻愬彇鍑簒ml鏁版嵁鍖呬腑鐨勫姞瀵嗘秷鎭� + * @param xmltext 寰呮彁鍙栫殑xml瀛楃涓� + * @return 鎻愬彇鍑虹殑鍔犲瘑娑堟伅瀛楃涓� + * @throws AesException + */ + public static Object[] extract(String xmltext) throws AesException { + Object[] result = new Object[3]; + try { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + + String FEATURE = null; + // This is the PRIMARY defense. If DTDs (doctypes) are disallowed, almost all XML entity attacks are prevented + // Xerces 2 only - http://xerces.apache.org/xerces2-j/features.html#disallow-doctype-decl + FEATURE = "http://apache.org/xml/features/disallow-doctype-decl"; + dbf.setFeature(FEATURE, true); + + // If you can't completely disable DTDs, then at least do the following: + // Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-general-entities + // Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-general-entities + // JDK7+ - http://xml.org/sax/features/external-general-entities + FEATURE = "http://xml.org/sax/features/external-general-entities"; + dbf.setFeature(FEATURE, false); + + // Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-parameter-entities + // Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-parameter-entities + // JDK7+ - http://xml.org/sax/features/external-parameter-entities + FEATURE = "http://xml.org/sax/features/external-parameter-entities"; + dbf.setFeature(FEATURE, false); + + // Disable external DTDs as well + FEATURE = "http://apache.org/xml/features/nonvalidating/load-external-dtd"; + dbf.setFeature(FEATURE, false); + + // and these as well, per Timothy Morgan's 2014 paper: "XML Schema, DTD, and Entity Attacks" + dbf.setXIncludeAware(false); + dbf.setExpandEntityReferences(false); + + // And, per Timothy Morgan: "If for some reason support for inline DOCTYPEs are a requirement, then + // ensure the entity settings are disabled (as shown above) and beware that SSRF attacks + // (http://cwe.mitre.org/data/definitions/918.html) and denial + // of service attacks (such as billion laughs or decompression bombs via "jar:") are a risk." + + // remaining parser logic + DocumentBuilder db = dbf.newDocumentBuilder(); + StringReader sr = new StringReader(xmltext); + InputSource is = new InputSource(sr); + Document document = db.parse(is); + + Element root = document.getDocumentElement(); + NodeList nodelist1 = root.getElementsByTagName("Encrypt"); + NodeList nodelist2 = root.getElementsByTagName("ToUserName"); + result[0] = 0; + result[1] = nodelist1.item(0).getTextContent(); + result[2] = nodelist2.item(0).getTextContent(); + return result; + } catch (Exception e) { + e.printStackTrace(); + throw new AesException(AesException.ParseXmlError); + } + } + + /** + * 鐢熸垚xml娑堟伅 + * @param encrypt 鍔犲瘑鍚庣殑娑堟伅瀵嗘枃 + * @param signature 瀹夊叏绛惧悕 + * @param timestamp 鏃堕棿鎴� + * @param nonce 闅忔満瀛楃涓� + * @return 鐢熸垚鐨剎ml瀛楃涓� + */ + public static String generate(String encrypt, String signature, String timestamp, String nonce) { + + String format = "<xml>\n" + "<Encrypt><![CDATA[%1$s]]></Encrypt>\n" + + "<MsgSignature><![CDATA[%2$s]]></MsgSignature>\n" + + "<TimeStamp>%3$s</TimeStamp>\n" + "<Nonce><![CDATA[%4$s]]></Nonce>\n" + "</xml>"; + return String.format(format, encrypt, signature, timestamp, nonce); + + } +} -- Gitblit v1.8.0