diff --git a/raincat-common/src/main/java/com/raincat/common/bean/TransactionInvocation.java b/raincat-common/src/main/java/com/raincat/common/bean/TransactionInvocation.java index 0ca82b2b..7487c6fb 100644 --- a/raincat-common/src/main/java/com/raincat/common/bean/TransactionInvocation.java +++ b/raincat-common/src/main/java/com/raincat/common/bean/TransactionInvocation.java @@ -15,6 +15,7 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.bean; import lombok.AllArgsConstructor; @@ -25,33 +26,38 @@ import java.io.Serializable; /** + * TransactionInvocation. * @author xiaoyu */ @Data @AllArgsConstructor @NoArgsConstructor public class TransactionInvocation implements Serializable { + private static final long serialVersionUID = 7722060715819141844L; + /** - * 事务执行器 + * 事务执行器. */ @Getter private Class targetClazz; + /** - * 方法 + * 方法. */ @Getter private String method; + /** - * 参数值 + * 参数值. */ @Getter private Object[] argumentValues; + /** - * 参数类型 + * 参数类型. */ @Getter private Class[] argumentTypes; - } diff --git a/raincat-common/src/main/java/com/raincat/common/bean/TransactionRecover.java b/raincat-common/src/main/java/com/raincat/common/bean/TransactionRecover.java index 74683f0b..50fa6730 100644 --- a/raincat-common/src/main/java/com/raincat/common/bean/TransactionRecover.java +++ b/raincat-common/src/main/java/com/raincat/common/bean/TransactionRecover.java @@ -15,8 +15,8 @@ * along with this distribution; if not, see . * */ -package com.raincat.common.bean; +package com.raincat.common.bean; import com.raincat.common.enums.TransactionStatusEnum; import lombok.Data; @@ -25,57 +25,56 @@ import java.util.Date; /** + * TransactionRecover. * @author xiaoyu */ @Data public class TransactionRecover implements Serializable { private static final long serialVersionUID = -3262858695515766275L; + /** - * 主键id + * 主键id. */ private String id; - /** - * 重试次数, + * 重试次数. */ - private int retriedCount = 0; + private int retriedCount; /** - * 创建时间 + * 创建时间. */ private Date createTime = new Date(); - /** - * 创建时间 + * 创建时间. */ private Date lastTime = new Date(); /** - * 版本控制 防止并发问题 + * 版本控制 防止并发问题. */ private int version = 1; /** - * 事务组id + * 事务组id. */ private String groupId; /** - * 任务id + * 任务id. */ private String taskId; /** - * 事务执行方法 + * 事务执行方法. */ private TransactionInvocation transactionInvocation; - /** - * {@linkplain TransactionStatusEnum} + * 状态. {@linkplain TransactionStatusEnum} */ private int status; diff --git a/raincat-common/src/main/java/com/raincat/common/bean/TransactionXid.java b/raincat-common/src/main/java/com/raincat/common/bean/TransactionXid.java deleted file mode 100644 index bfa685c9..00000000 --- a/raincat-common/src/main/java/com/raincat/common/bean/TransactionXid.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * - * Copyright 2017-2018 549477611@qq.com(xiaoyu) - * - * This copyrighted material is made available to anyone wishing to use, modify, - * copy, or redistribute it subject to the terms and conditions of the GNU - * Lesser General Public License, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this distribution; if not, see . - * - */ -package com.raincat.common.bean; - - -import javax.transaction.xa.Xid; -import java.io.Serializable; -import java.nio.ByteBuffer; -import java.util.Arrays; -import java.util.UUID; - -/** - * @author xiaoyu - */ -public class TransactionXid implements Xid, Serializable { - - private static final long serialVersionUID = -6817267250789142043L; - - private int formatId = 1; - - private byte[] globalTransactionId; - - private byte[] branchQualifier; - - public TransactionXid() { - globalTransactionId = uuidToByteArray(UUID.randomUUID()); - branchQualifier = uuidToByteArray(UUID.randomUUID()); - } - - public void setGlobalTransactionId(byte[] globalTransactionId) { - this.globalTransactionId = globalTransactionId; - } - - public void setBranchQualifier(byte[] branchQualifier) { - this.branchQualifier = branchQualifier; - } - - public TransactionXid(byte[] globalTransactionId) { - this.globalTransactionId = globalTransactionId; - branchQualifier = uuidToByteArray(UUID.randomUUID()); - } - - public TransactionXid(byte[] globalTransactionId, byte[] branchQualifier) { - this.globalTransactionId = globalTransactionId; - this.branchQualifier = branchQualifier; - } - - @Override - public int getFormatId() { - return formatId; - } - - @Override - public byte[] getGlobalTransactionId() { - return globalTransactionId; - } - - @Override - public byte[] getBranchQualifier() { - return branchQualifier; - } - - @Override - public String toString() { - - return "globalTransactionId:" + UUID.nameUUIDFromBytes(globalTransactionId).toString() + - "," + "branchQualifier:" + UUID.nameUUIDFromBytes(branchQualifier).toString(); - } - - @Override - public TransactionXid clone() { - - byte[] cloneGlobalTransactionId = null; - byte[] cloneBranchQualifier = null; - - if (globalTransactionId != null) { - cloneGlobalTransactionId = new byte[globalTransactionId.length]; - System.arraycopy(globalTransactionId, 0, cloneGlobalTransactionId, 0, globalTransactionId.length); - } - - if (branchQualifier != null) { - cloneBranchQualifier = new byte[branchQualifier.length]; - System.arraycopy(branchQualifier, 0, cloneBranchQualifier, 0, branchQualifier.length); - } - - TransactionXid clone = new TransactionXid(cloneGlobalTransactionId, cloneBranchQualifier); - return clone; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + this.getFormatId(); - result = prime * result + Arrays.hashCode(branchQualifier); - result = prime * result + Arrays.hashCode(globalTransactionId); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } else if (obj == null) { - return false; - } else if (getClass() != obj.getClass()) { - return false; - } - TransactionXid other = (TransactionXid) obj; - if (this.getFormatId() != other.getFormatId()) { - return false; - } else if (Arrays.equals(branchQualifier, other.branchQualifier) == false) { - return false; - } else if (Arrays.equals(globalTransactionId, other.globalTransactionId) == false) { - return false; - } - return true; - } - - public static byte[] uuidToByteArray(UUID uuid) { - ByteBuffer bb = ByteBuffer.wrap(new byte[16]); - bb.putLong(uuid.getMostSignificantBits()); - bb.putLong(uuid.getLeastSignificantBits()); - return bb.array(); - } - - public static UUID byteArrayToUUID(byte[] bytes) { - ByteBuffer bb = ByteBuffer.wrap(bytes); - long firstLong = bb.getLong(); - long secondLong = bb.getLong(); - return new UUID(firstLong, secondLong); - } -} - - diff --git a/raincat-common/src/main/java/com/raincat/common/bean/TxTransactionInfo.java b/raincat-common/src/main/java/com/raincat/common/bean/TxTransactionInfo.java index 53cfd744..93cc15de 100644 --- a/raincat-common/src/main/java/com/raincat/common/bean/TxTransactionInfo.java +++ b/raincat-common/src/main/java/com/raincat/common/bean/TxTransactionInfo.java @@ -15,6 +15,7 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.bean; import com.raincat.common.enums.PropagationEnum; @@ -22,37 +23,35 @@ import lombok.Getter; /** + * TxTransactionInfo. * @author xiaoyu */ @AllArgsConstructor public class TxTransactionInfo { /** - * 补偿方法对象 + * 补偿方法对象. */ @Getter private TransactionInvocation invocation; - /** - * 分布式事务组 + * 分布式事务组. */ @Getter private String txGroupId; /** - * 事务补偿id + * 事务补偿id. */ @Getter private String compensationId; - /** - * 事务等待时间 + * 事务等待时间. */ @Getter - private int waitMaxTime = 60; - + private int waitMaxTime; @Getter private PropagationEnum propagationEnum; diff --git a/raincat-common/src/main/java/com/raincat/common/bean/adapter/MongoAdapter.java b/raincat-common/src/main/java/com/raincat/common/bean/adapter/MongoAdapter.java index a4d90636..ab46313e 100644 --- a/raincat-common/src/main/java/com/raincat/common/bean/adapter/MongoAdapter.java +++ b/raincat-common/src/main/java/com/raincat/common/bean/adapter/MongoAdapter.java @@ -15,6 +15,7 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.bean.adapter; import lombok.Data; @@ -23,6 +24,7 @@ import java.io.Serializable; /** + * MongoAdapter. * @author xiaoyu */ @Data diff --git a/raincat-common/src/main/java/com/raincat/common/bean/adapter/TransactionRecoverAdapter.java b/raincat-common/src/main/java/com/raincat/common/bean/adapter/TransactionRecoverAdapter.java index 52db9873..9df5579f 100644 --- a/raincat-common/src/main/java/com/raincat/common/bean/adapter/TransactionRecoverAdapter.java +++ b/raincat-common/src/main/java/com/raincat/common/bean/adapter/TransactionRecoverAdapter.java @@ -24,73 +24,64 @@ import java.util.Date; /** - *

Description: .

- * + * TransactionRecoverAdapter. * @author xiaoyu(Myth) - * @version 1.0 - * @date 2017/10/30 10:39 - * @since JDK 1.8 */ @Data public class TransactionRecoverAdapter { - /** - * 事务主键id + * 事务主键id. */ private String transId; - /** - * 重试次数, + * 重试次数. */ - private int retriedCount = 0; + private int retriedCount; /** - * 创建时间 + * 创建时间. */ private Date createTime = new Date(); - /** - * 创建时间 + * 创建时间. */ private Date lastTime = new Date(); /** - * 版本控制 防止并发问题 + * 版本控制 防止并发问题. */ private int version = 1; /** - * 事务组id + * 事务组id. */ private String groupId; /** - * 任务id + * 任务id. */ private String taskId; /** - * 序列化后的二进制信息 + * 序列化后的二进制信息. */ private byte[] contents; /** - * {@linkplain TransactionStatusEnum} + * 状态. {@linkplain TransactionStatusEnum} */ private int status; - /** - * 调用接口名称 + * 调用接口名称. */ private String targetClass; - /** - * 调用方法名称 + * 调用方法名称. */ private String targetMethod; diff --git a/raincat-common/src/main/java/com/raincat/common/config/TxConfig.java b/raincat-common/src/main/java/com/raincat/common/config/TxConfig.java index fd306590..b19a9212 100644 --- a/raincat-common/src/main/java/com/raincat/common/config/TxConfig.java +++ b/raincat-common/src/main/java/com/raincat/common/config/TxConfig.java @@ -15,6 +15,7 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.config; import com.raincat.common.enums.BlockingQueueTypeEnum; @@ -24,132 +25,120 @@ import lombok.Data; /** + * TxConfig. * @author xiaoyu */ @Data public class TxConfig { /** - * 提供不同的序列化对象 {@linkplain SerializeProtocolEnum} + * 提供不同的序列化对象. {@linkplain SerializeProtocolEnum} */ private String serializer = "kryo"; - /** - * netty 传输的序列化协议 + * netty 传输的序列化协议. */ private String nettySerializer = "kryo"; - /** - * 延迟时间 + * 延迟时间. */ private int delayTime = 30; - /** - * 执行事务的线程数大小 + * 执行事务的线程数大小. */ private int transactionThreadMax = Runtime.getRuntime().availableProcessors() << 1; - /** - * netty 工作线程大小 + * netty 工作线程大小. */ private int nettyThreadMax = Runtime.getRuntime().availableProcessors() << 1; /** - * 心跳时间 默认10秒 + * 心跳时间 默认10秒. */ private int heartTime = 10; - /** - * 线程池的拒绝策略 {@linkplain RejectedPolicyTypeEnum} + * 线程池的拒绝策略. {@linkplain RejectedPolicyTypeEnum} */ private String rejectPolicy = "Abort"; /** - * 线程池的队列类型 {@linkplain BlockingQueueTypeEnum} + * 线程池的队列类型. {@linkplain BlockingQueueTypeEnum} */ private String blockingQueueType = "Linked"; /** - * 是否需要补偿 + * 是否需要补偿. */ private Boolean compensation = false; /** - * 补偿存储类型 {@linkplain CompensationCacheTypeEnum} + * 补偿存储类型. {@linkplain CompensationCacheTypeEnum} */ private String compensationCacheType; - /** - * 回滚队列大小 + * 回滚队列大小. */ private int compensationQueueMax = 5000; + /** - * 监听回滚队列线程数 + * 监听回滚队列线程数. */ private int compensationThreadMax = Runtime.getRuntime().availableProcessors() << 1; - /** - * 补偿恢复时间 单位秒 + * 补偿恢复时间 单位秒. */ private int compensationRecoverTime = 60; - /** - * 更新tmInfo 的时间间隔 + * 更新tmInfo 的时间间隔. */ private int refreshInterval = 60; - /** - * 最大重试次数 + * 最大重试次数. */ private int retryMax = 10; - /** - * 事务恢复间隔时间 单位秒(注意 此时间表示本地事务创建的时间多少秒以后才会执行) + * 事务恢复间隔时间 单位秒(注意 此时间表示本地事务创建的时间多少秒以后才会执行). */ private int recoverDelayTime = 60; - /** - * txManagerUrl服务地址 + * txManagerUrl服务地址. */ private String txManagerUrl; - /** - * db存储方式时候 数据库配置信息 + * db存储方式时候 数据库配置信息. */ private TxDbConfig txDbConfig; /** - * mongo存储方式时候的 mongo配置信息 + * mongo存储方式时候的 mongo配置信息. */ private TxMongoConfig txMongoConfig; - /** - * redis存储方式时候的 redis配置信息 + * redis存储方式时候的 redis配置信息. */ private TxRedisConfig txRedisConfig; /** - * 文件存储配置 + * 文件存储配置. */ private TxFileConfig txFileConfig; /** - * zookeeper 存储的配置 + * zookeeper 存储的配置. */ private TxZookeeperConfig txZookeeperConfig; - } diff --git a/raincat-common/src/main/java/com/raincat/common/config/TxDbConfig.java b/raincat-common/src/main/java/com/raincat/common/config/TxDbConfig.java index 91d937ea..585f6ef6 100644 --- a/raincat-common/src/main/java/com/raincat/common/config/TxDbConfig.java +++ b/raincat-common/src/main/java/com/raincat/common/config/TxDbConfig.java @@ -15,107 +15,98 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.config; import lombok.Data; /** + * TxDbConfig. * @author xiaoyu */ @Data public class TxDbConfig { /** - * Mysql 驱动 + * Mysql 驱动. */ private String driverClassName = "com.mysql.jdbc.Driver"; /** - * url + * url. */ private String url; /** - * 用户名 + * 用户名. */ private String username; /** - * 密码 + * 密码. */ private String password; - /** - * 初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时 + * 初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时. */ private int initialSize = 10; - /** - * 最大连接池数量 + * 最大连接池数量. */ private int maxActive = 100; /** - * 最小连接池数量 + * 最小连接池数量. */ private int minIdle = 20; - /** - * 配置获取连接等待超时的时间 + * 配置获取连接等待超时的时间. */ private int maxWait = 60000; - /** - * 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 + * 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒. */ private int timeBetweenEvictionRunsMillis = 60000; - /** - * 配置一个连接在池中最小生存的时间,单位是毫秒 + * 配置一个连接在池中最小生存的时间,单位是毫秒. */ private int minEvictableIdleTimeMillis = 300000; - private String validationQuery = " SELECT 1 "; - /** - * 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。 + * 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能. */ private Boolean testOnBorrow = false; - /** - * 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。 + * 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能. */ private Boolean testOnReturn = false; - /** * 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测, * 如果空闲时间大于timeBetweenEvictionRunsMillis, - * 执行validationQuery检测连接是否有效 + * 执行validationQuery检测连接是否有效. */ private Boolean testWhileIdle = true; - /** * 是否缓存preparedStatement,也就是PSCache。 - * PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭 + * PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭. */ - private Boolean poolPreparedStatements=false; - + private Boolean poolPreparedStatements = false; /** * 要启用PSCache,必须配置大于0,当大于0时,poolPreparedStatements自动触发修改为true。 * 在Druid中, - * 不会存在Oracle下PSCache占用内存过多的问题,可以把这个数值配置大一些,比如说100 + * 不会存在Oracle下PSCache占用内存过多的问题,可以把这个数值配置大一些,比如说100. */ - private int maxPoolPreparedStatementPerConnectionSize=100; + private int maxPoolPreparedStatementPerConnectionSize = 100; } diff --git a/raincat-common/src/main/java/com/raincat/common/config/TxFileConfig.java b/raincat-common/src/main/java/com/raincat/common/config/TxFileConfig.java index bcf382e3..8e31434b 100644 --- a/raincat-common/src/main/java/com/raincat/common/config/TxFileConfig.java +++ b/raincat-common/src/main/java/com/raincat/common/config/TxFileConfig.java @@ -15,25 +15,26 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.config; import lombok.Data; /** + * TxFileConfig. * @author xiaoyu */ @Data public class TxFileConfig { /** - * 文件保存路径 + * 文件保存路径. */ private String path; /** - * 文件前缀 + * 文件前缀. */ private String prefix; - } diff --git a/raincat-common/src/main/java/com/raincat/common/config/TxMongoConfig.java b/raincat-common/src/main/java/com/raincat/common/config/TxMongoConfig.java index 6c3b166c..3d54c315 100644 --- a/raincat-common/src/main/java/com/raincat/common/config/TxMongoConfig.java +++ b/raincat-common/src/main/java/com/raincat/common/config/TxMongoConfig.java @@ -15,32 +15,35 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.config; import lombok.Data; /** + * TxMongoConfig. * @author xiaoyu */ @Data public class TxMongoConfig { /** - * mongo数据库设置 + * mongo数据库设置. */ private String mongoDbName; /** - * mongo数据库URL + * mongo数据库URL. */ private String mongoDbUrl; + /** - * mongo数据库用户名 + * mongo数据库用户名. */ private String mongoUserName; /** - * mongo数据库密码 + * mongo数据库密码. */ private String mongoUserPwd; diff --git a/raincat-common/src/main/java/com/raincat/common/config/TxRedisConfig.java b/raincat-common/src/main/java/com/raincat/common/config/TxRedisConfig.java index 173a8aff..108a334a 100644 --- a/raincat-common/src/main/java/com/raincat/common/config/TxRedisConfig.java +++ b/raincat-common/src/main/java/com/raincat/common/config/TxRedisConfig.java @@ -15,42 +15,60 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.config; import lombok.Data; /** + * TxRedisConfig. * @author xiaoyu */ @Data public class TxRedisConfig { /** - * 是否集群模式 + * 是否集群模式. */ private Boolean cluster = false; /** - * 集群url ip:port;ip:port + * 集群url ip:port;ip:port. */ private String clusterUrl; private String hostName; + private int port; + private String password; + private int maxTotal = 8; + private int maxIdle = 8; - private int minIdle = 0; + + private int minIdle; + private long maxWaitMillis = -1L; + private long minEvictableIdleTimeMillis = 1800000L; + private long softMinEvictableIdleTimeMillis = 1800000L; + private int numTestsPerEvictionRun = 3; + private Boolean testOnCreate = false; + private Boolean testOnBorrow = false; + private Boolean testOnReturn = false; + private Boolean testWhileIdle = false; + private long timeBetweenEvictionRunsMillis = -1L; + private Boolean blockWhenExhausted = true; + private int timeOut = 10000; } diff --git a/raincat-common/src/main/java/com/raincat/common/config/TxZookeeperConfig.java b/raincat-common/src/main/java/com/raincat/common/config/TxZookeeperConfig.java index 0a47cf19..b430df99 100644 --- a/raincat-common/src/main/java/com/raincat/common/config/TxZookeeperConfig.java +++ b/raincat-common/src/main/java/com/raincat/common/config/TxZookeeperConfig.java @@ -15,11 +15,13 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.config; import lombok.Data; /** + * TxZookeeperConfig. * @author xiaoyu */ @Data diff --git a/raincat-common/src/main/java/com/raincat/common/constant/CommonConstant.java b/raincat-common/src/main/java/com/raincat/common/constant/CommonConstant.java index 68006721..25f66101 100644 --- a/raincat-common/src/main/java/com/raincat/common/constant/CommonConstant.java +++ b/raincat-common/src/main/java/com/raincat/common/constant/CommonConstant.java @@ -19,21 +19,15 @@ package com.raincat.common.constant; /** - *

Description: .

- * + * CommonConstant. * @author xiaoyu(Myth) - * @version 1.0 - * @date 2017/10/18 15:36 - * @since JDK 1.8 */ public interface CommonConstant { - String REDIS_PRE_FIX = "transaction:group:%s"; String REDIS_KEYS = "transaction:group:*"; - String REDIS_KEY_SET = "transaction:group"; double REDIS_SCOPE = 10.0; @@ -44,7 +38,6 @@ public interface CommonConstant { String RECOVER_REDIS_KEY_PRE = "transaction:recover:%s"; - String DB_MYSQL = "mysql"; String DB_SQLSERVER = "sqlserver"; diff --git a/raincat-common/src/main/java/com/raincat/common/entity/TxManagerServer.java b/raincat-common/src/main/java/com/raincat/common/entity/TxManagerServer.java index 6d06baf2..26ebfb71 100644 --- a/raincat-common/src/main/java/com/raincat/common/entity/TxManagerServer.java +++ b/raincat-common/src/main/java/com/raincat/common/entity/TxManagerServer.java @@ -15,25 +15,26 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.entity; import lombok.Data; /** + * TxManagerServer. * @author xiaoyu */ @Data public class TxManagerServer { /** - * TxManagerServer host + * TxManagerServer host. */ private String host; /** - * TxManagerServer port + * TxManagerServer port. */ private Integer port; - } diff --git a/raincat-common/src/main/java/com/raincat/common/entity/TxManagerServiceDTO.java b/raincat-common/src/main/java/com/raincat/common/entity/TxManagerServiceDTO.java index 4babe7d0..3b63bb11 100644 --- a/raincat-common/src/main/java/com/raincat/common/entity/TxManagerServiceDTO.java +++ b/raincat-common/src/main/java/com/raincat/common/entity/TxManagerServiceDTO.java @@ -15,12 +15,13 @@ * along with this distribution; if not, see . * */ -package com.raincat.common.entity; +package com.raincat.common.entity; import lombok.Data; /** + * TxManagerServiceDTO. * @author xiaoyu */ @Data diff --git a/raincat-common/src/main/java/com/raincat/common/enums/BlockingQueueTypeEnum.java b/raincat-common/src/main/java/com/raincat/common/enums/BlockingQueueTypeEnum.java index 2a4f1efc..1a397d59 100644 --- a/raincat-common/src/main/java/com/raincat/common/enums/BlockingQueueTypeEnum.java +++ b/raincat-common/src/main/java/com/raincat/common/enums/BlockingQueueTypeEnum.java @@ -15,14 +15,13 @@ * along with this distribution; if not, see . * */ -package com.raincat.common.enums; +package com.raincat.common.enums; import java.util.Arrays; import java.util.Objects; import java.util.Optional; - /** * The enum Blocking queue type enum. * @author xiaoyu @@ -45,7 +44,7 @@ public enum BlockingQueueTypeEnum { private String value; - BlockingQueueTypeEnum(String value) { + BlockingQueueTypeEnum(final String value) { this.value = value; } @@ -64,7 +63,7 @@ public String getValue() { * @param value the value * @return the blocking queue type enum */ - public static BlockingQueueTypeEnum fromString(String value) { + public static BlockingQueueTypeEnum fromString(final String value) { Optional blockingQueueTypeEnum = Arrays.stream(BlockingQueueTypeEnum.values()) .filter(v -> Objects.equals(v.getValue(), value)) diff --git a/raincat-common/src/main/java/com/raincat/common/enums/CompensationActionEnum.java b/raincat-common/src/main/java/com/raincat/common/enums/CompensationActionEnum.java index fbe98607..8a8d81a0 100644 --- a/raincat-common/src/main/java/com/raincat/common/enums/CompensationActionEnum.java +++ b/raincat-common/src/main/java/com/raincat/common/enums/CompensationActionEnum.java @@ -15,6 +15,7 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.enums; /** @@ -26,32 +27,30 @@ public enum CompensationActionEnum { /** * Save compensate action enum. */ - SAVE(0,"保存"), + SAVE(0, "保存"), /** * Delete compensate action enum. */ - DELETE(1,"删除"), + DELETE(1, "删除"), /** * Update compensate action enum. */ - UPDATE(2,"更新"), + UPDATE(2, "更新"), /** * Compensate compensate action enum. */ - COMPENSATE(3,"补偿"), - - ; + COMPENSATE(3, "补偿"); private int code; private String desc; - CompensationActionEnum(int code,String desc){ - this.code=code; - this.desc=desc; + CompensationActionEnum(final int code, final String desc) { + this.code = code; + this.desc = desc; } /** @@ -68,7 +67,7 @@ public int getCode() { * * @param code the code */ - public void setCode(int code) { + public void setCode(final int code) { this.code = code; } @@ -86,7 +85,7 @@ public String getDesc() { * * @param desc the desc */ - public void setDesc(String desc) { + public void setDesc(final String desc) { this.desc = desc; } } diff --git a/raincat-common/src/main/java/com/raincat/common/enums/CompensationCacheTypeEnum.java b/raincat-common/src/main/java/com/raincat/common/enums/CompensationCacheTypeEnum.java index efc48c5c..67ddd431 100644 --- a/raincat-common/src/main/java/com/raincat/common/enums/CompensationCacheTypeEnum.java +++ b/raincat-common/src/main/java/com/raincat/common/enums/CompensationCacheTypeEnum.java @@ -15,6 +15,7 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.enums; import java.util.Arrays; @@ -22,6 +23,7 @@ import java.util.Optional; /** + * CompensationCacheTypeEnum. * @author xiaoyu */ public enum CompensationCacheTypeEnum { @@ -53,7 +55,7 @@ public enum CompensationCacheTypeEnum { private String compensationCacheType; - CompensationCacheTypeEnum(String compensationCacheType) { + CompensationCacheTypeEnum(final String compensationCacheType) { this.compensationCacheType = compensationCacheType; } @@ -63,7 +65,7 @@ public enum CompensationCacheTypeEnum { * @param compensationCacheType the compensate cache type * @return the compensate cache type enum */ - public static CompensationCacheTypeEnum acquireCompensationCacheType(String compensationCacheType) { + public static CompensationCacheTypeEnum acquireCompensationCacheType(final String compensationCacheType) { Optional serializeProtocolEnum = Arrays.stream(CompensationCacheTypeEnum.values()) .filter(v -> Objects.equals(v.getCompensationCacheType(), compensationCacheType)) @@ -85,7 +87,7 @@ public String getCompensationCacheType() { * * @param compensationCacheType the compensate cache type */ - public void setCompensationCacheType(String compensationCacheType) { + public void setCompensationCacheType(final String compensationCacheType) { this.compensationCacheType = compensationCacheType; } } diff --git a/raincat-common/src/main/java/com/raincat/common/enums/NettyMessageActionEnum.java b/raincat-common/src/main/java/com/raincat/common/enums/NettyMessageActionEnum.java index 2ea245e7..3b473941 100644 --- a/raincat-common/src/main/java/com/raincat/common/enums/NettyMessageActionEnum.java +++ b/raincat-common/src/main/java/com/raincat/common/enums/NettyMessageActionEnum.java @@ -15,15 +15,16 @@ * along with this distribution; if not, see . * */ -package com.raincat.common.enums; +package com.raincat.common.enums; import java.util.Arrays; import java.util.Objects; import java.util.Optional; - /** + * NettyMessageActionEnum. + * * @author xiaoyu */ public enum NettyMessageActionEnum { @@ -33,7 +34,6 @@ public enum NettyMessageActionEnum { */ CREATE_GROUP(0, "创建事务组"), - /** * Add transaction netty message action enum. */ @@ -49,7 +49,6 @@ public enum NettyMessageActionEnum { */ PRE_COMMIT(3, "预提交"), - /** * Complete commit netty message action enum. */ @@ -72,33 +71,28 @@ public enum NettyMessageActionEnum { /** * Send netty message action enum. */ - SEND(8,"发送"), + SEND(8, "发送"), /** * Receive netty message action enum. */ - RECEIVE(9,"接收"), - + RECEIVE(9, "接收"), /** * Get transaction group netty message action enum. */ - GET_TRANSACTION_GROUP_STATUS(10,"获取事务组状态"), - - - - FIND_TRANSACTION_GROUP_INFO(11,"获取事务组信息"), - - - + GET_TRANSACTION_GROUP_STATUS(10, "获取事务组状态"), + /** + * Find transaction group info netty message action enum. + */ + FIND_TRANSACTION_GROUP_INFO(11, "获取事务组信息"); - ; private int code; private String desc; - NettyMessageActionEnum(int code, String desc) { + NettyMessageActionEnum(final int code, final String desc) { this.code = code; this.desc = desc; } @@ -110,13 +104,12 @@ public enum NettyMessageActionEnum { * @param code the code * @return the netty message action enum */ - public static NettyMessageActionEnum acquireByCode(int code) { + public static NettyMessageActionEnum acquireByCode(final int code) { Optional actionEnum = Arrays.stream(NettyMessageActionEnum.values()) .filter(v -> Objects.equals(v.getCode(), code)) .findFirst(); return actionEnum.orElse(NettyMessageActionEnum.HEART); - } /** @@ -133,7 +126,7 @@ public int getCode() { * * @param code the code */ - public void setCode(int code) { + public void setCode(final int code) { this.code = code; } @@ -151,7 +144,7 @@ public String getDesc() { * * @param desc the desc */ - public void setDesc(String desc) { + public void setDesc(final String desc) { this.desc = desc; } } diff --git a/raincat-common/src/main/java/com/raincat/common/enums/NettyResultEnum.java b/raincat-common/src/main/java/com/raincat/common/enums/NettyResultEnum.java index 3bb71228..dec2b49d 100644 --- a/raincat-common/src/main/java/com/raincat/common/enums/NettyResultEnum.java +++ b/raincat-common/src/main/java/com/raincat/common/enums/NettyResultEnum.java @@ -15,15 +15,16 @@ * along with this distribution; if not, see . * */ -package com.raincat.common.enums; +package com.raincat.common.enums; import java.util.Arrays; import java.util.Objects; import java.util.Optional; - /** + * NettyResultEnum. + * * @author xiaoyu */ public enum NettyResultEnum { @@ -33,25 +34,21 @@ public enum NettyResultEnum { */ SUCCESS(0, "成功"), - /** * Fail netty result enum. */ FAIL(1, "失败"), - - TIME_OUT(-1,"tmManager未连接或者响应超时!"), - - - ; - - + /** + * Time out netty result enum. + */ + TIME_OUT(-1,"tmManager未连接或者响应超时!"); private int code; private String desc; - NettyResultEnum(int code, String desc) { + NettyResultEnum(final int code, final String desc) { this.code = code; this.desc = desc; } @@ -63,7 +60,7 @@ public enum NettyResultEnum { * @param code the code * @return the netty result enum */ - public static NettyResultEnum acquireByCode(int code) { + public static NettyResultEnum acquireByCode(final int code) { Optional actionEnum = Arrays.stream(NettyResultEnum.values()) .filter(v -> Objects.equals(v.getCode(), code)) @@ -86,7 +83,7 @@ public int getCode() { * * @param code the code */ - public void setCode(int code) { + public void setCode(final int code) { this.code = code; } @@ -104,7 +101,7 @@ public String getDesc() { * * @param desc the desc */ - public void setDesc(String desc) { + public void setDesc(final String desc) { this.desc = desc; } } diff --git a/raincat-common/src/main/java/com/raincat/common/enums/PropagationEnum.java b/raincat-common/src/main/java/com/raincat/common/enums/PropagationEnum.java index be0864fd..085f5f2c 100644 --- a/raincat-common/src/main/java/com/raincat/common/enums/PropagationEnum.java +++ b/raincat-common/src/main/java/com/raincat/common/enums/PropagationEnum.java @@ -15,10 +15,11 @@ * along with this distribution; if not, see . * */ -package com.raincat.common.enums; +package com.raincat.common.enums; /** + * PropagationEnum. * @author xiaoyu */ public enum PropagationEnum { @@ -61,7 +62,7 @@ public enum PropagationEnum { private final int value; - PropagationEnum(int value) { + PropagationEnum(final int value) { this.value = value; } @@ -74,9 +75,4 @@ public int getValue() { return this.value; } - - - - - } diff --git a/raincat-common/src/main/java/com/raincat/common/enums/SerializeProtocolEnum.java b/raincat-common/src/main/java/com/raincat/common/enums/SerializeProtocolEnum.java index d68d5a06..e324c75b 100644 --- a/raincat-common/src/main/java/com/raincat/common/enums/SerializeProtocolEnum.java +++ b/raincat-common/src/main/java/com/raincat/common/enums/SerializeProtocolEnum.java @@ -15,6 +15,7 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.enums; import java.util.Arrays; @@ -22,9 +23,9 @@ import java.util.Optional; /** + * SerializeProtocolEnum. * @author xiaoyu */ - public enum SerializeProtocolEnum { /** @@ -49,7 +50,7 @@ public enum SerializeProtocolEnum { private String serializeProtocol; - SerializeProtocolEnum(String serializeProtocol) { + SerializeProtocolEnum(final String serializeProtocol) { this.serializeProtocol = serializeProtocol; } @@ -59,13 +60,12 @@ public enum SerializeProtocolEnum { * @param serializeProtocol the serialize protocol * @return the serialize protocol enum */ - public static SerializeProtocolEnum acquireSerializeProtocol(String serializeProtocol) { + public static SerializeProtocolEnum acquireSerializeProtocol(final String serializeProtocol) { Optional serializeProtocolEnum = Arrays.stream(SerializeProtocolEnum.values()) .filter(v -> Objects.equals(v.getSerializeProtocol(), serializeProtocol)) .findFirst(); return serializeProtocolEnum.orElse(SerializeProtocolEnum.KRYO); - } /** @@ -77,14 +77,4 @@ public String getSerializeProtocol() { return serializeProtocol; } - /** - * Sets serialize protocol. - * - * @param serializeProtocol the serialize protocol - */ - public void setSerializeProtocol(String serializeProtocol) { - this.serializeProtocol = serializeProtocol; - } - - } diff --git a/raincat-common/src/main/java/com/raincat/common/enums/TransactionRoleEnum.java b/raincat-common/src/main/java/com/raincat/common/enums/TransactionRoleEnum.java index 0502c389..b40e9e11 100644 --- a/raincat-common/src/main/java/com/raincat/common/enums/TransactionRoleEnum.java +++ b/raincat-common/src/main/java/com/raincat/common/enums/TransactionRoleEnum.java @@ -15,6 +15,7 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.enums; import java.util.Arrays; @@ -28,35 +29,31 @@ */ public enum TransactionRoleEnum { - /** * Start transaction role enum. */ START(0, "发起者"), - /** * Actor transaction role enum. */ ACTOR(1, "参与者"), /** - * 事务组 + * 事务组. */ - GROUP(2,"事务组") - ; - + GROUP(2, "事务组"); private int code; private String desc; - TransactionRoleEnum(int code, String desc) { + TransactionRoleEnum(final int code, final String desc) { this.code = code; this.desc = desc; } - public static TransactionRoleEnum acquireByCode(int code) { + public static TransactionRoleEnum acquireByCode(final int code) { Optional roleEnum = Arrays.stream(TransactionRoleEnum.values()) .filter(v -> Objects.equals(v.getCode(), code)) @@ -65,7 +62,7 @@ public static TransactionRoleEnum acquireByCode(int code) { } - public static String acquireDescByCode(int code) { + public static String acquireDescByCode(final int code) { return acquireByCode(code).getDesc(); } @@ -84,7 +81,7 @@ public int getCode() { * * @param code the code */ - public void setCode(int code) { + public void setCode(final int code) { this.code = code; } @@ -102,7 +99,7 @@ public String getDesc() { * * @param desc the desc */ - public void setDesc(String desc) { + public void setDesc(final String desc) { this.desc = desc; } } diff --git a/raincat-common/src/main/java/com/raincat/common/enums/TransactionStatusEnum.java b/raincat-common/src/main/java/com/raincat/common/enums/TransactionStatusEnum.java index d7525484..77e93363 100644 --- a/raincat-common/src/main/java/com/raincat/common/enums/TransactionStatusEnum.java +++ b/raincat-common/src/main/java/com/raincat/common/enums/TransactionStatusEnum.java @@ -15,6 +15,7 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.enums; import java.util.Arrays; @@ -22,9 +23,9 @@ import java.util.Optional; /** + * TransactionStatusEnum. * @author xiaoyu */ - public enum TransactionStatusEnum { /** @@ -68,13 +69,12 @@ public enum TransactionStatusEnum { private String desc; - TransactionStatusEnum(int code, String desc) { + TransactionStatusEnum(final int code, final String desc) { this.code = code; this.desc = desc; } - - public static TransactionStatusEnum acquireByCode(int code) { + public static TransactionStatusEnum acquireByCode(final int code) { Optional transactionStatusEnum = Arrays.stream(TransactionStatusEnum.values()) .filter(v -> Objects.equals(v.getCode(), code)) @@ -83,7 +83,7 @@ public static TransactionStatusEnum acquireByCode(int code) { } - public static String acquireDescByCode(int code) { + public static String acquireDescByCode(final int code) { return acquireByCode(code).getDesc(); } @@ -101,7 +101,7 @@ public int getCode() { * * @param code the code */ - public void setCode(int code) { + public void setCode(final int code) { this.code = code; } @@ -119,7 +119,7 @@ public String getDesc() { * * @param desc the desc */ - public void setDesc(String desc) { + public void setDesc(final String desc) { this.desc = desc; } } diff --git a/raincat-common/src/main/java/com/raincat/common/enums/TransactionTypeEnum.java b/raincat-common/src/main/java/com/raincat/common/enums/TransactionTypeEnum.java deleted file mode 100644 index 32b7d06d..00000000 --- a/raincat-common/src/main/java/com/raincat/common/enums/TransactionTypeEnum.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * - * Copyright 2017-2018 549477611@qq.com(xiaoyu) - * - * This copyrighted material is made available to anyone wishing to use, modify, - * copy, or redistribute it subject to the terms and conditions of the GNU - * Lesser General Public License, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this distribution; if not, see . - * - */ -package com.raincat.common.enums; - - -/** - * The enum Transaction type enum. - * @author xiaoyu - */ -public enum TransactionTypeEnum { - - /** - * Root transaction type enum. - */ - ROOT(1), - /** - * Branch transaction type enum. - */ - BRANCH(2); - - /** - * The Id. - */ - int id; - - TransactionTypeEnum(int id) { - this.id = id; - } - - /** - * Gets id. - * - * @return the id - */ - public int getId() { - return id; - } - - /** - * Value of transaction type enum. - * - * @param id the id - * @return the transaction type enum - */ - public static TransactionTypeEnum valueOf(int id) { - switch (id) { - case 1: - return ROOT; - case 2: - return BRANCH; - default: - return null; - } - } - -} diff --git a/raincat-common/src/main/java/com/raincat/common/exception/TransactionException.java b/raincat-common/src/main/java/com/raincat/common/exception/TransactionException.java index 704b6c4a..c9d34d84 100644 --- a/raincat-common/src/main/java/com/raincat/common/exception/TransactionException.java +++ b/raincat-common/src/main/java/com/raincat/common/exception/TransactionException.java @@ -15,9 +15,11 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.exception; /** + * TransactionException. * @author xiaoyu */ public class TransactionException extends Exception { @@ -26,15 +28,15 @@ public class TransactionException extends Exception { public TransactionException() { } - public TransactionException(String message) { + public TransactionException(final String message) { super(message); } - public TransactionException(String message, Throwable cause) { + public TransactionException(final String message, final Throwable cause) { super(message, cause); } - public TransactionException(Throwable cause) { + public TransactionException(final Throwable cause) { super(cause); } } diff --git a/raincat-common/src/main/java/com/raincat/common/exception/TransactionIoException.java b/raincat-common/src/main/java/com/raincat/common/exception/TransactionIoException.java index 68c68b0a..2ab8f369 100644 --- a/raincat-common/src/main/java/com/raincat/common/exception/TransactionIoException.java +++ b/raincat-common/src/main/java/com/raincat/common/exception/TransactionIoException.java @@ -15,20 +15,22 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.exception; /** + * TransactionIoException. * @author xiaoyu */ public class TransactionIoException extends RuntimeException { private static final long serialVersionUID = 6508064607297986329L; - public TransactionIoException(String message) { + public TransactionIoException(final String message) { super(message); } - public TransactionIoException(Throwable e) { + public TransactionIoException(final Throwable e) { super(e); } } diff --git a/raincat-common/src/main/java/com/raincat/common/exception/TransactionRuntimeException.java b/raincat-common/src/main/java/com/raincat/common/exception/TransactionRuntimeException.java index ac227fe2..466e0154 100644 --- a/raincat-common/src/main/java/com/raincat/common/exception/TransactionRuntimeException.java +++ b/raincat-common/src/main/java/com/raincat/common/exception/TransactionRuntimeException.java @@ -15,9 +15,11 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.exception; /** + * TransactionRuntimeException. * @author xiaoyu */ public class TransactionRuntimeException extends RuntimeException { @@ -26,15 +28,15 @@ public class TransactionRuntimeException extends RuntimeException { public TransactionRuntimeException() { } - public TransactionRuntimeException(String message) { + public TransactionRuntimeException(final String message) { super(message); } - public TransactionRuntimeException(String message, Throwable cause) { + public TransactionRuntimeException(final String message, final Throwable cause) { super(message, cause); } - public TransactionRuntimeException(Throwable cause) { + public TransactionRuntimeException(final Throwable cause) { super(cause); } } diff --git a/raincat-common/src/main/java/com/raincat/common/holder/Assert.java b/raincat-common/src/main/java/com/raincat/common/holder/Assert.java index dc8aea13..d9d5454a 100644 --- a/raincat-common/src/main/java/com/raincat/common/holder/Assert.java +++ b/raincat-common/src/main/java/com/raincat/common/holder/Assert.java @@ -17,11 +17,10 @@ */ package com.raincat.common.holder; - import com.raincat.common.exception.TransactionRuntimeException; - /** + * Assert. * @author xiaoyu */ public class Assert { diff --git a/raincat-common/src/main/java/com/raincat/common/holder/BeanMapUtils.java b/raincat-common/src/main/java/com/raincat/common/holder/BeanMapUtils.java deleted file mode 100644 index a0a11438..00000000 --- a/raincat-common/src/main/java/com/raincat/common/holder/BeanMapUtils.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * - * Copyright 2017-2018 549477611@qq.com(xiaoyu) - * - * This copyrighted material is made available to anyone wishing to use, modify, - * copy, or redistribute it subject to the terms and conditions of the GNU - * Lesser General Public License, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this distribution; if not, see . - * - */ -package com.raincat.common.holder; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import org.springframework.cglib.beans.BeanMap; - -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -/** - * @author xiaoyu - */ -public class BeanMapUtils { - - /** - * 将对象装换为map - * - * @param bean - * @return - */ - public static Map beanToMap(T bean) { - Map map = Maps.newHashMap(); - if (bean != null) { - BeanMap beanMap = BeanMap.create(bean); - for (Object key : beanMap.keySet()) { - if (Objects.nonNull(beanMap.get(key))) { - map.put(key + "", beanMap.get(key)); - } - - } - } - return map; - } - - /** - * 将map装换为javabean对象 - * - * @param map - * @param bean - * @return - */ - public static T mapToBean(Map map, T bean) { - BeanMap beanMap = BeanMap.create(bean); - beanMap.putAll(map); - return bean; - } - - - public static T objectMapToBean(Map map, T bean) { - BeanMap beanMap = BeanMap.create(bean); - beanMap.putAll(map); - return bean; - } - - - - - - /** - * 将map装换为javabean对象 - * - * @param map key value 为string 的map - * @param bean - * @return - */ - public static T stringMapToBean(Map map, T bean) { - BeanMap beanMap = BeanMap.create(bean); - beanMap.putAll(map); - return bean; - } - - /** - * 将List转换为List> - * - * @param objList - * @return - * @throws IOException - */ - public static List> objectsToMaps(List objList) throws IOException { - List> list = Lists.newArrayList(); - if (objList != null && objList.size() > 0) { - Map map; - T bean; - for (int i = 0, size = objList.size(); i < size; i++) { - bean = objList.get(i); - map = beanToMap(bean); - list.add(map); - } - } - return list; - } - - /** - * 将List>转换为List - * - * @param maps - * @param clazz - * @return - * @throws InstantiationException - * @throws IllegalAccessException - */ - public static List mapsToObjects(List> maps, Class clazz) throws InstantiationException, IllegalAccessException { - List list = Lists.newArrayList(); - if (maps != null && maps.size() > 0) { - Map map = null; - T bean = null; - for (int i = 0, size = maps.size(); i < size; i++) { - map = maps.get(i); - bean = clazz.newInstance(); - mapToBean(map, bean); - list.add(bean); - } - } - return list; - } - - - /** - * 将List>转换为List - * - * @param maps - * @param clazz - * @return - * @throws InstantiationException - * @throws IllegalAccessException - */ - public static List listToBean(List maps, Class clazz) throws InstantiationException, IllegalAccessException { - List list = Lists.newArrayList(); - if (maps != null && maps.size() > 0) { - Object map; - T bean; - for (int i = 0, size = maps.size(); i < size; i++) { - map = maps.get(i); - bean = clazz.newInstance(); - - BeanMap beanMap = BeanMap.create(bean); - list.add(bean); - } - } - return list; - } - - - - /** - * 将List>转换为List - * - * @param maps - * @param clazz - * @return - * @throws InstantiationException - * @throws IllegalAccessException - */ - public static List objectMapsToObjects(List> maps, Class clazz) throws InstantiationException, IllegalAccessException { - List list = Lists.newArrayList(); - if (maps != null && maps.size() > 0) { - Map map; - T bean; - for (int i = 0, size = maps.size(); i < size; i++) { - map = maps.get(i); - bean = clazz.newInstance(); - objectMapToBean(map, bean); - list.add(bean); - } - } - return list; - } -} diff --git a/raincat-common/src/main/java/com/raincat/common/holder/ConfigHelper.java b/raincat-common/src/main/java/com/raincat/common/holder/ConfigHelper.java deleted file mode 100644 index 99aba64a..00000000 --- a/raincat-common/src/main/java/com/raincat/common/holder/ConfigHelper.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * - * Copyright 2017-2018 549477611@qq.com(xiaoyu) - * - * This copyrighted material is made available to anyone wishing to use, modify, - * copy, or redistribute it subject to the terms and conditions of the GNU - * Lesser General Public License, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this distribution; if not, see . - * - */ -package com.raincat.common.holder; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.configuration.PropertiesConfiguration; - -/** - * @author xiaoyu - */ -public class ConfigHelper { - - - private PropertiesConfiguration propertiesConfiguration = null; - - public String getStringValue(String key) { - return propertiesConfiguration.getString(key); - } - - public void setProperty(String key, Object val) { - propertiesConfiguration.setProperty(key, val); - try { - propertiesConfiguration.save(); - } catch (ConfigurationException e) { - e.printStackTrace(); - } - } - - public int getIntValue(String key) { - return propertiesConfiguration.getInt(key); - } - - public float getFloatValue(String key) { - return propertiesConfiguration.getFloat(key); - } - - public ConfigHelper(String propertyPath) { - try { - propertiesConfiguration = new PropertiesConfiguration(propertyPath); - } catch (Exception e) { - throw new RuntimeException( - "Please configure check file: " + propertyPath); - } - } - -} diff --git a/raincat-common/src/main/java/com/raincat/common/holder/ConfigUtils.java b/raincat-common/src/main/java/com/raincat/common/holder/ConfigUtils.java deleted file mode 100644 index 6c45184a..00000000 --- a/raincat-common/src/main/java/com/raincat/common/holder/ConfigUtils.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * - * Copyright 2017-2018 549477611@qq.com(xiaoyu) - * - * This copyrighted material is made available to anyone wishing to use, modify, - * copy, or redistribute it subject to the terms and conditions of the GNU - * Lesser General Public License, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this distribution; if not, see . - * - */ -package com.raincat.common.holder; - - - -/** - * @author xiaoyu - */ -public class ConfigUtils { - - public static String getString(String filePath, String key) { - ConfigHelper helper = new ConfigHelper(filePath); - return helper.getStringValue(key); - } - - public static int getInt(String filePath, String key) { - ConfigHelper helper = new ConfigHelper(filePath); - return helper.getIntValue(key); - } - - public static void setProperty(String filePath, String key, Object val) { - ConfigHelper helper = new ConfigHelper(filePath); - helper.setProperty(key, val); - } - -} diff --git a/raincat-common/src/main/java/com/raincat/common/holder/DateUtils.java b/raincat-common/src/main/java/com/raincat/common/holder/DateUtils.java index 0eb0caa3..5bf8ebe9 100644 --- a/raincat-common/src/main/java/com/raincat/common/holder/DateUtils.java +++ b/raincat-common/src/main/java/com/raincat/common/holder/DateUtils.java @@ -1,25 +1,11 @@ -/* - * - * Copyright 2017-2018 549477611@qq.com(xiaoyu) - * - * This copyrighted material is made available to anyone wishing to use, modify, - * copy, or redistribute it subject to the terms and conditions of the GNU - * Lesser General Public License, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this distribution; if not, see . - * - */ package com.raincat.common.holder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.sql.Timestamp; import java.text.ParseException; -import java.text.SimpleDateFormat; import java.time.Clock; import java.time.DayOfWeek; import java.time.Instant; @@ -36,56 +22,112 @@ import java.util.Date; /** - * 时间操作类 + * 日期操作类. * - * @author yu.xiao @happylifeplat.com - * @version 1.0 - * @date 2017 /3/1 11:52 - * @since JDK 1.8 - **/ + * @author xiaoyu + */ public class DateUtils { + public static final Logger LOGGER = LoggerFactory.getLogger(DateUtils.class); + /** - * 要用到的DATE Format的定义 + * 要用到的DATE Format的定义. */ public static final String DATE_FORMAT_DATEONLY = "yyyy-MM-dd"; + public static final String DATE_FORMAT_DATETIME = "yyyy-MM-dd HH:mm:ss"; + public static final String DATE_FORMAT_DATETIME14 = "yyyyMMddHHmmss"; + public static final String SHORTDATEFORMAT = "yyyyMMdd"; + public static final String HMS_FORMAT = "HH:mm:ss"; + private static final ZoneId UTC_ZONE = ZoneOffset.UTC.normalized(); + + private static final ZoneId DEFAULT_ZONE = ZoneId.systemDefault(); + + private static final Integer QUARTER_FIRST = 1; + + private static final Integer QUARTER_SECOND = 2; + + private static final Integer QUARTER_THIRD = 3; + + private static final Integer QUARTER_FOURTH = 4; /** - * 把字符串转成日期类型 + * 把字符串转成日期类型. * 输入的日期格式:yyyy-MM-dd HH:mm:ss * * @param str 日期字符串 * @return 转换后的日期 - * @throws ParseException + * @throws ParseException 异常 * @see LocalDateTime */ - public static LocalDateTime parseLocalDateTime(String str) throws ParseException { + public static LocalDateTime parseLocalDateTime(final String str) throws ParseException { return LocalDateTime.parse(str, DateTimeFormatter.ofPattern(DATE_FORMAT_DATETIME)); } + /** + * 把字符串转成特定格式的日期类型. + * 输入的日期格式:yyyy-MM-dd HH:mm:ss + * @param dateFormat 日期字符串 + * @param str 日期字符串 + * @return 转换后的日期 + * @throws ParseException 转换异常 + * @see LocalDateTime + */ + public static LocalDateTime parseLocalDateTime(final String str, final String dateFormat) throws ParseException { + LocalDateTime localDateTime = LocalDateTime.parse(str, DateTimeFormatter.ofPattern(DATE_FORMAT_DATETIME)); + DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern(dateFormat); + return LocalDateTime.parse(localDateTime.format(ofPattern), ofPattern); + } - public static Date getDateYYYY() throws ParseException{ - LocalDateTime localDateTime = parseLocalDateTime(getCurrentDateTime()); - ZoneId zone = ZoneId.systemDefault(); - Instant instant = localDateTime.atZone(zone).toInstant(); - return Date.from(instant); + /** + * 把字符串转成日期类型. + * 输入的日期格式:yyyy-MM-dd + * + * @param str 日期字符串 + * @return 转换后的日期 + * @throws ParseException 异常 + * @see LocalDateTime + */ + public static LocalDateTime parseLocalDateTime10(final String str) throws ParseException { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_FORMAT_DATEONLY); + LocalDateTime time = LocalDateTime.from(LocalDate.parse(str, formatter).atStartOfDay()); + return time; } - public static String parseDate(Date date) { - Instant instant = date.toInstant(); - ZoneId zone = ZoneId.systemDefault(); - LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone); - return formaterLocalDateTime(localDateTime); + /** + * 把字符串转成日期类型. + * 输入的日期格式:yyyy-MM-dd + * + * @param str 日期字符串 + * @return 转换后的日期 + * @throws ParseException 异常 + * @see LocalDateTime + */ + public static LocalDate parseLocalDate(final String str) throws ParseException { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_FORMAT_DATEONLY); + return LocalDate.parse(str, formatter); } + /** + * 把字符串转成日期类型. + * + * @param str 日期字符串 + * @param format 日期格式 + * @return 转换后的日期 + * @throws ParseException 异常 + * @see LocalDateTime + */ + public static LocalDate parseLocalDate(final String str, final String format) throws ParseException { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format); + return LocalDate.parse(str, formatter); + } /** - * 获得当前的日期毫秒 + * 获得当前的日期毫秒. * * @return 当前毫秒数 */ @@ -94,7 +136,7 @@ public static long nowTimeMillis() { } /** - * 获取从1970年到现在的秒数 + * 获取从1970年到现在的秒数. * * @return 秒数 */ @@ -103,7 +145,7 @@ public static long nowEpochSecond() { } /** - * 获得当前的时间戳 + * 获得当前的时间戳. * * @return 时间点 */ @@ -112,7 +154,7 @@ public static Instant nowTimestamp() { } /** - * yyyy-MM-dd 当前日期 + * yyyy-MM-dd 当前日期. * * @return 当前日期 yyyy-MM-dd */ @@ -121,7 +163,7 @@ public static String getCurrentDate() { } /** - * 获取当前日期时间 yyyy-MM-dd HH:mm:ss + * 获取当前日期时间 yyyy-MM-dd HH:mm:ss. * * @return 获取当前日期时间 yyyy-MM-dd HH:mm:ss */ @@ -130,17 +172,17 @@ public static String getCurrentDateTime() { } /** - * 获取当前日期时间 + * 获取当前日期时间. * * @param format 格式字符串 * @return 获取当前日期时间 */ - public static String getCurrentDateTime(String format) { + public static String getCurrentDateTime(final String format) { return LocalDateTime.now().format(DateTimeFormatter.ofPattern(format)); } /** - * 获取当前时间 HH:mm:ss + * 获取当前时间 HH:mm:ss. * * @return 获取当前时间 HH:mm:ss */ @@ -149,225 +191,262 @@ public static String getCurrentTime() { } /** - * yyyy-MM-dd 格式化传入日期 + * yyyy-MM-dd 格式化传入日期. * * @param date 日期 * @return yyyy-MM-dd 日期 */ - public static String formaterDate(LocalDate date) { + public static String formaterDate(final LocalDate date) { return date.format(DateTimeFormatter.ofPattern(DATE_FORMAT_DATEONLY)); } /** - * yyyyMMdd 格式化传入日期 + * 将localDateTime 格式化成特定格式的字符串. + * + * @param time 时间 + * @param dateFormat 格式化 + * @return String + */ + public static String formaterTime(final LocalTime time, final String dateFormat) { + return time.format(DateTimeFormatter.ofPattern(dateFormat)); + } + + /** + * yyyyMMdd 格式化传入日期. * * @param date 传入的日期 * @return yyyyMMdd 字符串 */ - public static String formaterDateToyyyyMMdd(LocalDate date) { + public static String formaterDateToyyyyMMdd(final LocalDate date) { return date.format(DateTimeFormatter.ofPattern(SHORTDATEFORMAT)); } /** - * 将localDateTime 格式化成yyyy-MM-dd HH:mm:ss + * 将localDateTime 格式化成yyyy-MM-dd HH:mm:ss. * - * @param dateTime - * @return + * @param dateTime 时间 + * @return String */ - public static String formaterLocalDateTime(LocalDateTime dateTime) { + public static String formaterLocalDateTime(final LocalDateTime dateTime) { return dateTime.format(DateTimeFormatter.ofPattern(DATE_FORMAT_DATETIME)); } /** - * yyyy-MM-dd HH:mm:ss + * 将localDateTime 格式化成特定格式的字符串. + * + * @param dateTime 时间 + * @param dateFormat 格式化 + * @return string + */ + public static String formaterLocalDateTime(final LocalDateTime dateTime, final String dateFormat) { + return dateTime.format(DateTimeFormatter.ofPattern(dateFormat)); + } + + /** + * yyyy-MM-dd HH:mm:ss. * 时间点转换成日期字符串 * * @param instant 时间点. * @return 日期时间 yyyy-MM-dd HH:mm:ss + * @throws ParseException 异常 */ - public static String parseInstantToDataStr(Instant instant) throws ParseException { + public static String parseInstantToDataStr(final Instant instant) throws ParseException { return LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern(DATE_FORMAT_DATETIME)); } /** - * 得到时间戳格式字串 + * 得到时间戳格式字串. * * @param date 长日期 * @return UTC 格式的时间戳字符串 */ - public static String getTimeStampStr(LocalDateTime date) { + public static String getTimeStampStr(final LocalDateTime date) { return date.toInstant(ZoneOffset.UTC).toString(); } /** - * 计算 second 秒后的时间 + * 计算 second 秒后的时间. * * @param date 长日期 * @param second 需要增加的秒数 * @return 增加后的日期 */ - public static LocalDateTime addSecond(LocalDateTime date, int second) { + public static LocalDateTime addSecond(final LocalDateTime date, final int second) { return date.plusSeconds(second); } /** - * 计算 minute 分钟后的时间 + * 计算 minute 分钟后的时间. * * @param date 长日期 * @param minute 需要增加的分钟数 * @return 增加后的日期 */ - public static LocalDateTime addMinute(LocalDateTime date, int minute) { + public static LocalDateTime addMinute(final LocalDateTime date, final int minute) { return date.plusMinutes(minute); } /** - * 计算 hour 小时后的时间 + * 计算 hour 小时后的时间. * * @param date 长日期 * @param hour 增加的小时数 * @return 增加后的日期 */ - public static LocalDateTime addHour(LocalDateTime date, int hour) { + public static LocalDateTime addHour(final LocalDateTime date, final int hour) { return date.plusHours(hour); } /** - * 计算 day 天后的时间 + * 计算 day 天后的时间. * * @param date 长日期 * @param day 增加的天数 * @return 增加后的日期 */ - public static LocalDateTime addDay(LocalDateTime date, int day) { + public static LocalDateTime addDay(final LocalDateTime date, final int day) { return date.plusDays(day); } /** - * 计算 month 月后的时间 + * 计算 month 月后的时间. * * @param date 长日期 * @param month 需要增加的月数 * @return 增加后的日期 */ - public static LocalDateTime addMoth(LocalDateTime date, int month) { + public static LocalDateTime addMoth(final LocalDateTime date, final int month) { return date.plusMonths(month); } /** - * 计算 year 年后的时间 + * 计算 year 年后的时间. * * @param date 长日期 * @param year 需要增加的年数 * @return 增加后的日期 */ - public static LocalDateTime addYear(LocalDateTime date, int year) { + public static LocalDateTime addYear(final LocalDateTime date, final int year) { return date.plusYears(year); } /** - * 得到day的起始时间点。 + * 得到day的起始时间点. * 一天开始的时间为 0:0:0 * * @param date 短日期 * @return yyyy-MM-dd HH:mm:ss 字符串 */ - public static String getDayStart(LocalDate date) { + public static LocalDateTime getDayStart(final LocalDate date) { LocalDateTime localDateTime = LocalDateTime.of(date, LocalTime.of(0, 0, 0)); - return localDateTime.format(DateTimeFormatter.ofPattern(DATE_FORMAT_DATETIME)); + return localDateTime; } /** - * 得到day的结束时间点。 + * 得到day的结束时间点。. * 一天结束的时间为 23:59:59 * * @param date date 短日期 * @return yyyy-MM-dd HH:mm:ss 字符串 */ - public static String getDayEnd(LocalDate date) { + public static LocalDateTime getDayEnd(final LocalDate date) { LocalDateTime localDateTime = LocalDateTime.of(date, LocalTime.of(23, 59, 59)); - return localDateTime.format(DateTimeFormatter.ofPattern(DATE_FORMAT_DATETIME)); + return localDateTime; } /** - * 根据日期字符串获取时间戳 + * 根据日期字符串获取时间戳. * * @param dateStr yyyy-MM-dd HH:mm:ss * @return 时间信息 + * @throws ParseException 异常 */ - public static Instant parseDataStrToInstant(String dateStr) throws ParseException { + public static Instant parseDataStrToInstant(final String dateStr) throws ParseException { return parseLocalDateTime(dateStr).toInstant(ZoneOffset.UTC); } /** - * 取得两个日期之间相差的年数 + * 两个日期是否为同一天. + * + * @param date1 时间 + * @param date2 时间 + * @return boolean + */ + public static boolean isSameDate(final LocalDateTime date1, final LocalDateTime date2) { + String date1Str = date1.format(DateTimeFormatter.ofPattern(DATE_FORMAT_DATEONLY)); + String date2Str = date2.format(DateTimeFormatter.ofPattern(DATE_FORMAT_DATEONLY)); + return date1Str.equals(date2Str); + } + + /** + * 取得两个日期之间相差的年数. * getYearsBetween * * @param t1 开始时间 * @param t2 结果时间 * @return t1到t2间的年数,如果t2在 t1之后,返回正数,否则返回负数 */ - public static long getYearsBetween(LocalDate t1, LocalDate t2) { + public static long getYearsBetween(final LocalDate t1, final LocalDate t2) { return t1.until(t2, ChronoUnit.YEARS); } /** - * 取得两个日期之间相差的日数 + * 取得两个日期之间相差的日数. * * @param t1 开始日期 * @param t2 结束日期 * @return t1到t2间的日数,如果t2 在 t1之后,返回正数,否则返回负数 */ - public static long getDaysBetween(LocalDate t1, LocalDate t2) { + public static long getDaysBetween(final LocalDate t1, final LocalDate t2) { return t1.until(t2, ChronoUnit.DAYS); } /** - * 取得两个日期之间相差的月数 + * 取得两个日期之间相差的月数. * * @param t1 开始日期 * @param t2 结束日期 * @return t1到t2间的日数,如果t2 在 t1之后,返回正数,否则返回负数 */ - public static long getMonthsBetween(LocalDate t1, LocalDate t2) { + public static long getMonthsBetween(final LocalDate t1, final LocalDate t2) { return t1.until(t2, ChronoUnit.MONTHS); } /** - * 取得两个日期之间相差的小时数 + * 取得两个日期之间相差的小时数. * * @param t1 开始长日期 * @param t2 结束长日期 * @return t1到t2间的日数,如果t2 在 t1之后,返回正数,否则返回负数 */ - public static long getHoursBetween(LocalDateTime t1, LocalDateTime t2) { + public static long getHoursBetween(final LocalDateTime t1, final LocalDateTime t2) { return t1.until(t2, ChronoUnit.HOURS); } /** - * 取得两个日期之间相差的秒数 + * 取得两个日期之间相差的秒数. * * @param t1 开始长日期 * @param t2 结束长日期 * @return t1到t2间的日数,如果t2 在 t1之后,返回正数,否则返回负数 */ - public static long getSecondsBetween(LocalDateTime t1, LocalDateTime t2) { + public static long getSecondsBetween(final LocalDateTime t1, final LocalDateTime t2) { return t1.until(t2, ChronoUnit.SECONDS); } /** - * 取得两个日期之间相差的分钟 + * 取得两个日期之间相差的分钟. * * @param t1 开始长日期 * @param t2 结束长日期 * @return t1到t2间的日数,如果t2 在 t1之后,返回正数,否则返回负数 */ - public static long getMinutesBetween(LocalDateTime t1, LocalDateTime t2) { + public static long getMinutesBetween(final LocalDateTime t1, final LocalDateTime t2) { return t1.until(t2, ChronoUnit.MINUTES); } /** - * 获取今天是星期几 + * 获取今天是星期几. * * @return 返回今天是周几 * @see DayOfWeek @@ -377,14 +456,29 @@ public static DayOfWeek getWeek() { } /** - * 判断时间是否在制定的时间段之类 + * 判断时间是否在指定的时间段之类. + * + * @param date 需要判断的时间 + * @param start 时间段的起始时间 + * @param end 时间段的截止时间 + * @return true or false + */ + public static boolean isBetween(final LocalDateTime date, final LocalDateTime start, final LocalDateTime end) { + if (date == null || start == null || end == null) { + throw new IllegalArgumentException("日期不能为空"); + } + return date.isAfter(start) && date.isBefore(end); + } + + /** + * 判断时间是否在指定的时间段之类. * * @param date 需要判断的时间 * @param start 时间段的起始时间 * @param end 时间段的截止时间 * @return true or false */ - public static boolean isBetween(LocalDateTime date, LocalDateTime start, LocalDateTime end) { + public static boolean isBetween(final LocalTime date, final LocalTime start, final LocalTime end) { if (date == null || start == null || end == null) { throw new IllegalArgumentException("日期不能为空"); } @@ -392,126 +486,115 @@ public static boolean isBetween(LocalDateTime date, LocalDateTime start, LocalDa } /** - * 得到传入日期,周起始时间 + * 得到传入日期,周起始时间. * 这个方法定义:周一为一个星期开始的第一天 * * @param date 日期 * @return 返回一周的第一天 */ - public static LocalDate getWeekStart(LocalDate date) { + public static LocalDate getWeekStart(final LocalDate date) { return date.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)); } /** - * 得到当前周截止时间 + * 得到当前周截止时间. * 这个方法定义:周日为一个星期开始的最后一天 * * @param date 日期 * @return 返回一周的最后一天 */ - public static LocalDate getWeekEnd(LocalDate date) { + public static LocalDate getWeekEnd(final LocalDate date) { return date.with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY)); } /** - * 得到month的终止时间点. + * 得到month的终止时间点.. * * @param date 日期 * @return 传入的日期当月的结束日期 */ - public static LocalDate getMonthEnd(LocalDate date) { + public static LocalDate getMonthEnd(final LocalDate date) { return date.with(TemporalAdjusters.lastDayOfMonth()); } /** - * 得到当月起始时间 + * 得到当月起始时间. * * @param date 日期 * @return 传入的日期当月的开始日期 */ - public static LocalDate getMonthStart(LocalDate date) { + public static LocalDate getMonthStart(final LocalDate date) { return date.with(TemporalAdjusters.firstDayOfMonth()); } /** - * 得到当前年起始时间 + * 得到当前年起始时间. * * @param date 日期 * @return 传入的日期当年的开始日期 */ - public static LocalDate getYearStart(LocalDate date) { + public static LocalDate getYearStart(final LocalDate date) { return date.with(TemporalAdjusters.firstDayOfYear()); } /** - * 得到当前年最后一天 + * 得到当前年最后一天. * * @param date 日期 * @return 传入的日期当年的结束日期 */ - public static LocalDate getYearEnd(LocalDate date) { + public static LocalDate getYearEnd(final LocalDate date) { return date.with(TemporalAdjusters.lastDayOfYear()); } /** - * 取得季度第一天 + * 取得季度第一天. * * @param date 日期 * @return 传入的日期当季的开始日期 */ - public static LocalDate getSeasonStart(LocalDate date) { + public static LocalDate getSeasonStart(final LocalDate date) { return getSeasonDate(date)[0]; } /** - * 取得季度最后一天 + * 取得季度最后一天. * * @param date 日期 * @return 传入的日期当季的结束日期 */ - public static LocalDate getSeasonEnd(LocalDate date) { + public static LocalDate getSeasonEnd(final LocalDate date) { return getSeasonDate(date)[2].with(TemporalAdjusters.lastDayOfMonth()); } - private static final int FIRST_QUARTER = 1; - - - public static final int SECOND_QUARTER = 2; - - public static final int THREE_QUARTER = 3; - - - public static final int FOUR_QUARTER = 4; - - /** - * 取得季度月的第一天 + * 取得季度月的第一天. * * @param date 日期 * @return 返回一个当前季度月的数组 */ - public static LocalDate[] getSeasonDate(LocalDate date) { + public static LocalDate[] getSeasonDate(final LocalDate date) { LocalDate[] season = new LocalDate[3]; int nSeason = getSeason(date); int year = date.getYear(); - // 第一季度 - if (nSeason == FIRST_QUARTER) { + if (nSeason == QUARTER_FIRST) { + // 第一季度 season[0] = LocalDate.of(year, Month.JANUARY, 1); season[1] = LocalDate.of(year, Month.FEBRUARY, 1); season[2] = LocalDate.of(year, Month.MARCH, 1); + } else if (nSeason == QUARTER_SECOND) { // 第二季度 - } else if (nSeason == SECOND_QUARTER) { season[0] = LocalDate.of(year, Month.APRIL, 1); season[1] = LocalDate.of(year, Month.MAY, 1); season[2] = LocalDate.of(year, Month.JUNE, 1); + } else if (nSeason == QUARTER_THIRD) { // 第三季度 - } else if (nSeason ==THREE_QUARTER) { season[0] = LocalDate.of(year, Month.JULY, 1); season[1] = LocalDate.of(year, Month.AUGUST, 1); season[2] = LocalDate.of(year, Month.SEPTEMBER, 1); + } else if (nSeason == QUARTER_FOURTH) { // 第四季度 - } else if (nSeason == FOUR_QUARTER) { season[0] = LocalDate.of(year, Month.OCTOBER, 1); season[1] = LocalDate.of(year, Month.NOVEMBER, 1); season[2] = LocalDate.of(year, Month.DECEMBER, 1); @@ -520,12 +603,12 @@ public static LocalDate[] getSeasonDate(LocalDate date) { } /** - * 判断当前期为每几个季度 + * 判断当前期为每几个季度. * * @param date 日期 * @return 1 第一季度 2 第二季度 3 第三季度 4 第四季度 */ - public static int getSeason(LocalDate date) { + public static int getSeason(final LocalDate date) { int season = 0; @@ -559,29 +642,29 @@ public static int getSeason(LocalDate date) { } /** - * 获取当前时间的前多少,yyyy-MM-dd + * 获取当前时间的前多少,yyyy-MM-dd. * * @param days 天数 * @return yyyy-MM-dd */ - public static String subDays(int days) { + public static String subDays(final int days) { return LocalDate.now().minusDays(days).format(DateTimeFormatter.ofPattern(DATE_FORMAT_DATEONLY)); } /** - * 判断开始时间和结束时间,是否超出了当前时间的一定的间隔数限制 如:开始时间和结束时间,不能超出距离当前时间90天 + * 判断开始时间和结束时间,是否超出了当前时间的一定的间隔数限制 如:开始时间和结束时间,不能超出距离当前时间90天. * * @param startDate 开始时间 * @param endDate 结束时间按 * @param interval 间隔数 * @return true or false */ - public static boolean isOverIntervalLimit(LocalDate startDate, LocalDate endDate, int interval) { + public static boolean isOverIntervalLimit(final LocalDate startDate, final LocalDate endDate, final int interval) { return getDaysBetween(startDate, endDate) >= interval; } /** - * 获取昨天的日期 格式串:yyyy-MM-dd + * 获取昨天的日期 格式串:yyyy-MM-dd. * * @return yyyy-MM-dd */ @@ -590,16 +673,16 @@ public static String getYesterday() { } /** - * 获取昨天的日期 格式串:yyyy-MM-dd - * + * 获取昨天的日期 格式串:yyyy-MM-dd. + * @param date 时间 * @return yyyy-MM-dd */ - public static String getYesterday(LocalDate date) { + public static String getYesterday(final LocalDate date) { return date.minusDays(1).format(DateTimeFormatter.ofPattern(DATE_FORMAT_DATEONLY)); } /** - * 上月第一天 + * 上月第一天. * * @return 日期 */ @@ -609,7 +692,7 @@ public static LocalDate getPreviousMonthFirstDay() { } /** - * 上月最后一天 + * 上月最后一天. * * @return 日期 */ @@ -618,8 +701,9 @@ public static LocalDate getPreviousMonthLastDay() { } /** - * 获得当天0点时间 - * @return Date + * 获得当天0点时间. + * + * @return 日期 */ public static Date getTimesmorning() { Calendar cal = Calendar.getInstance(); @@ -631,8 +715,9 @@ public static Date getTimesmorning() { } /** - * 获得当天近一周 - * @return LocalDateTime + * 获得当天近一周. + * + * @return 日期 */ public static LocalDateTime getAWeekFromNow() { LocalDateTime date = LocalDateTime.now(); @@ -641,8 +726,9 @@ public static LocalDateTime getAWeekFromNow() { } /** - * 获得当天近一月 - * @return LocalDateTime + * 获得当天近一月. + * + * @return 日期 */ public static LocalDateTime getAMonthFromNow() { LocalDateTime date = LocalDateTime.now(); @@ -651,8 +737,9 @@ public static LocalDateTime getAMonthFromNow() { } /** - * 获得当天近一年 - * @return LocalDateTime + * 获得当天近一年. + * + * @return 日期 */ public static LocalDateTime getAYearFromNow() { LocalDateTime date = LocalDateTime.now(); @@ -660,22 +747,52 @@ public static LocalDateTime getAYearFromNow() { return date.plusYears(-1); } + + /** + * 获取utc时间. + * + * @return LocalDateTime + */ + public static LocalDateTime getUTCLocalDateTime() { + return LocalDateTime.now(UTC_ZONE); + } + + + /** + * 将当前时区时间转成UTC时间. + * + * @param dateTime 时间 + * @return LocalDateTime + */ + public static LocalDateTime toUTCDateTime(final LocalDateTime dateTime) { + if (dateTime == null) { + return null; + } else { + Instant instant = dateTime.toInstant(DEFAULT_ZONE.getRules().getOffset(dateTime)); + return LocalDateTime.ofEpochSecond(instant.getEpochSecond(), instant.getNano(), ZoneOffset.UTC); + } + } + + /** - * 比较两个日期大小(比较年月日时分秒),com1大于com2返回1,反之返回-1,相等则返回0 + * 将UTC时间转成当前时区时间. * - * @param date1 - * @param date2 - * @return + * @param dateTime 时间 + * @return LocalDateTime */ - public static int compareDateOfSecond(Date date1, Date date2) { - Calendar c1 = Calendar.getInstance(); - c1.setTime(date1); - c1.set(Calendar.MILLISECOND, 0); - Calendar c2 = Calendar.getInstance(); - c2.setTime(date2); - c2.set(Calendar.MILLISECOND, 0); - return c1.compareTo(c2); + public static LocalDateTime toDefaultDateTime(final LocalDateTime dateTime) { + return dateTime == null ? null : LocalDateTime.ofInstant(dateTime.toInstant(ZoneOffset.UTC), DEFAULT_ZONE); + } + + /** + * 将数据库时间改成当前时区时间. + * @param timestamp 时间 + * @return time + * @date 2018/5/9 18:25 + */ + public static LocalDateTime toDefaultDateTime(final Timestamp timestamp) { + return timestamp == null ? null : toDefaultDateTime(timestamp.toLocalDateTime()); } @Override @@ -683,4 +800,12 @@ public String toString() { return super.toString(); } + /*public static void main(String[] args) throws Exception { + LocalDateTime t1 = LocalDateTime.now(); + LocalDateTime t2 = LocalDateTime.now().plusDays(1); + System.out.println(t1.isAfter(t2)); + System.out.println(getUTCLocalDateTime()); + System.out.println(LocalDateTime.now()); + } +*/ } diff --git a/raincat-common/src/main/java/com/raincat/common/holder/DbTypeUtils.java b/raincat-common/src/main/java/com/raincat/common/holder/DbTypeUtils.java index 9a7391f9..a171d87e 100644 --- a/raincat-common/src/main/java/com/raincat/common/holder/DbTypeUtils.java +++ b/raincat-common/src/main/java/com/raincat/common/holder/DbTypeUtils.java @@ -21,16 +21,17 @@ import com.raincat.common.constant.CommonConstant; /** - *

Description: .

- * + * DbTypeUtils. * @author xiaoyu(Myth) - * @version 1.0 - * @date 2017/10/20 11:39 - * @since JDK 1.8 */ public class DbTypeUtils { - public static String buildByDriverClassName(String driverClassName) { + /** + * 判断是什么类型的数据库. + * @param driverClassName 驱动名称 + * @return mysql sqlserver oracle . + */ + public static String buildByDriverClassName(final String driverClassName) { String dbType = "mysql"; if (driverClassName.contains(CommonConstant.DB_MYSQL)) { dbType = "mysql"; @@ -42,5 +43,4 @@ public static String buildByDriverClassName(String driverClassName) { return dbType; } - } diff --git a/raincat-common/src/main/java/com/raincat/common/holder/IdWorkerUtils.java b/raincat-common/src/main/java/com/raincat/common/holder/IdWorkerUtils.java index 54dea347..a7a80f4a 100644 --- a/raincat-common/src/main/java/com/raincat/common/holder/IdWorkerUtils.java +++ b/raincat-common/src/main/java/com/raincat/common/holder/IdWorkerUtils.java @@ -15,11 +15,13 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.holder; import java.util.UUID; /** + * IdWorkerUtils. * @author xiaoyu */ public final class IdWorkerUtils { diff --git a/raincat-common/src/main/java/com/raincat/common/holder/LogUtil.java b/raincat-common/src/main/java/com/raincat/common/holder/LogUtil.java index 0856eea2..a117664b 100644 --- a/raincat-common/src/main/java/com/raincat/common/holder/LogUtil.java +++ b/raincat-common/src/main/java/com/raincat/common/holder/LogUtil.java @@ -15,6 +15,7 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.holder; import org.slf4j.Logger; @@ -22,15 +23,15 @@ import java.util.Objects; import java.util.function.Supplier; - /** + * LogUtil. * @author xiaoyu */ -public class LogUtil { +public final class LogUtil { - public static final LogUtil LOG_UTIL = new LogUtil(); + private static final LogUtil LOG_UTIL = new LogUtil(); - private LogUtil(){ + private LogUtil() { } @@ -40,64 +41,59 @@ public static LogUtil getInstance() { /** - * debug 打印日志 - * @param logger 日志 - * @param format 日志信息 - * @param supplier supplier接口 + * debug 打印日志. + * + * @param logger 日志 + * @param format 日志信息 + * @param supplier supplier接口 */ - public static void debug(Logger logger ,String format,Supplier supplier){ - if(logger.isDebugEnabled()){ - logger.debug(format,supplier.get()); + public static void debug(Logger logger, String format, Supplier supplier) { + if (logger.isDebugEnabled()) { + logger.debug(format, supplier.get()); } } - public static void debug(Logger logger ,Supplier supplier){ - if(logger.isDebugEnabled()){ + public static void debug(Logger logger, Supplier supplier) { + if (logger.isDebugEnabled()) { logger.debug(Objects.toString(supplier.get())); } } - - public static void info(Logger logger,String format,Supplier supplier){ - if(logger.isInfoEnabled()){ - logger.info(format,supplier.get()); + public static void info(Logger logger, String format, Supplier supplier) { + if (logger.isInfoEnabled()) { + logger.info(format, supplier.get()); } } - - public static void info(Logger logger,Supplier supplier){ - if(logger.isInfoEnabled()){ + public static void info(Logger logger, Supplier supplier) { + if (logger.isInfoEnabled()) { logger.info(Objects.toString(supplier.get())); } } - - - public static void error(Logger logger,String format,Supplier supplier){ - if(logger.isErrorEnabled()){ - logger.error(format,supplier.get()); + public static void error(Logger logger, String format, Supplier supplier) { + if (logger.isErrorEnabled()) { + logger.error(format, supplier.get()); } } - public static void error(Logger logger,Supplier supplier){ - if(logger.isErrorEnabled()){ + public static void error(Logger logger, Supplier supplier) { + if (logger.isErrorEnabled()) { logger.error(Objects.toString(supplier.get())); } } - public static void warn(Logger logger,String format,Supplier supplier){ - if(logger.isWarnEnabled()){ - logger.warn(format,supplier.get()); + public static void warn(Logger logger, String format, Supplier supplier) { + if (logger.isWarnEnabled()) { + logger.warn(format, supplier.get()); } } - public static void warn(Logger logger,Supplier supplier){ - if(logger.isWarnEnabled()){ + public static void warn(Logger logger, Supplier supplier) { + if (logger.isWarnEnabled()) { logger.warn(Objects.toString(supplier.get())); } } - - } diff --git a/raincat-common/src/main/java/com/raincat/common/holder/RedisKeyUtils.java b/raincat-common/src/main/java/com/raincat/common/holder/RedisKeyUtils.java index 988f4838..ca5720f8 100644 --- a/raincat-common/src/main/java/com/raincat/common/holder/RedisKeyUtils.java +++ b/raincat-common/src/main/java/com/raincat/common/holder/RedisKeyUtils.java @@ -19,12 +19,8 @@ package com.raincat.common.holder; /** - *

Description: .

- * + * RedisKeyUtils. * @author xiaoyu(Myth) - * @version 1.0 - * @date 2017/10/19 11:24 - * @since JDK 1.8 */ public class RedisKeyUtils { diff --git a/raincat-common/src/main/java/com/raincat/common/holder/RepositoryPathUtils.java b/raincat-common/src/main/java/com/raincat/common/holder/RepositoryPathUtils.java index 3d4098f8..0d1ecb10 100644 --- a/raincat-common/src/main/java/com/raincat/common/holder/RepositoryPathUtils.java +++ b/raincat-common/src/main/java/com/raincat/common/holder/RepositoryPathUtils.java @@ -21,27 +21,19 @@ import com.raincat.common.constant.CommonConstant; /** - *

Description: .

- * 获取资源路径的工具类 - * + * RepositoryPathUtils. * @author xiaoyu(Myth) - * @version 1.0 - * @date 2017/10/19 10:58 - * @since JDK 1.8 */ public class RepositoryPathUtils { - public static String buildFilePath(String applicationName) { return String.join("/", CommonConstant.PATH_SUFFIX, applicationName.replaceAll("-", "_")); } - public static String buildDbTableName(String applicationName) { return CommonConstant.DB_SUFFIX + applicationName.replaceAll("-", "_"); } - public static String buildMongoTableName(String applicationName) { return CommonConstant.DB_SUFFIX + applicationName.replaceAll("-", "_"); } @@ -54,5 +46,4 @@ public static String buildZookeeperPath(String applicationName) { return String.join("_", CommonConstant.PATH_SUFFIX, applicationName); } - } diff --git a/raincat-common/src/main/java/com/raincat/common/holder/ServiceBootstrap.java b/raincat-common/src/main/java/com/raincat/common/holder/ServiceBootstrap.java index ad153265..c4e1b124 100644 --- a/raincat-common/src/main/java/com/raincat/common/holder/ServiceBootstrap.java +++ b/raincat-common/src/main/java/com/raincat/common/holder/ServiceBootstrap.java @@ -15,18 +15,19 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.holder; import java.util.Iterator; import java.util.ServiceLoader; /** + * ServiceBootstrap. * @author xiaoyu */ public class ServiceBootstrap { - - public static S loadFirst(Class clazz) { + public static S loadFirst(final Class clazz) { final ServiceLoader loader = loadAll(clazz); final Iterator iterator = loader.iterator(); if (!iterator.hasNext()) { @@ -37,7 +38,7 @@ public static S loadFirst(Class clazz) { return iterator.next(); } - public static ServiceLoader loadAll(Class clazz) { + public static ServiceLoader loadAll(final Class clazz) { return ServiceLoader.load(clazz); } } diff --git a/raincat-common/src/main/java/com/raincat/common/holder/TransactionRecoverUtils.java b/raincat-common/src/main/java/com/raincat/common/holder/TransactionRecoverUtils.java index 7977f2fb..764d6828 100644 --- a/raincat-common/src/main/java/com/raincat/common/holder/TransactionRecoverUtils.java +++ b/raincat-common/src/main/java/com/raincat/common/holder/TransactionRecoverUtils.java @@ -25,18 +25,12 @@ import com.raincat.common.serializer.ObjectSerializer; /** - *

Description: .

- * + * TransactionRecoverUtils. * @author xiaoyu(Myth) - * @version 1.0 - * @date 2017/10/30 11:04 - * @since JDK 1.8 */ public class TransactionRecoverUtils { - - public static byte[] convert(TransactionRecover transactionRecover, - ObjectSerializer objectSerializer) throws TransactionException { + public static byte[] convert(final TransactionRecover transactionRecover, final ObjectSerializer objectSerializer) throws TransactionException { TransactionRecoverAdapter adapter = new TransactionRecoverAdapter(); final TransactionInvocation transactionInvocation = transactionRecover.getTransactionInvocation(); adapter.setGroupId(transactionRecover.getGroupId()); @@ -53,16 +47,9 @@ public static byte[] convert(TransactionRecover transactionRecover, return objectSerializer.serialize(adapter); } - - - public static TransactionRecover transformVO(byte[] contents, - ObjectSerializer objectSerializer) throws TransactionException { + public static TransactionRecover transformVO(final byte[] contents, final ObjectSerializer objectSerializer) throws TransactionException { TransactionRecover transactionRecover = new TransactionRecover(); - - final TransactionRecoverAdapter adapter = - objectSerializer.deSerialize(contents, TransactionRecoverAdapter.class); - - + final TransactionRecoverAdapter adapter = objectSerializer.deSerialize(contents, TransactionRecoverAdapter.class); transactionRecover.setLastTime(adapter.getLastTime()); transactionRecover.setRetriedCount(adapter.getRetriedCount()); transactionRecover.setCreateTime(adapter.getCreateTime()); @@ -70,25 +57,14 @@ public static TransactionRecover transformVO(byte[] contents, transactionRecover.setId(adapter.getTransId()); transactionRecover.setTaskId(adapter.getTaskId()); transactionRecover.setStatus(adapter.getStatus()); - transactionRecover.setVersion(adapter.getVersion()); return transactionRecover; - - } - - - public static TransactionRecover transformBean(byte[] contents, - ObjectSerializer objectSerializer) throws TransactionException { + public static TransactionRecover transformBean(final byte[] contents, final ObjectSerializer objectSerializer) throws TransactionException { TransactionRecover transactionRecover = new TransactionRecover(); - - final TransactionRecoverAdapter adapter = - objectSerializer.deSerialize(contents, TransactionRecoverAdapter.class); - - TransactionInvocation transactionInvocation = - objectSerializer.deSerialize(adapter.getContents(), TransactionInvocation.class); - + final TransactionRecoverAdapter adapter = objectSerializer.deSerialize(contents, TransactionRecoverAdapter.class); + TransactionInvocation transactionInvocation = objectSerializer.deSerialize(adapter.getContents(), TransactionInvocation.class); transactionRecover.setLastTime(adapter.getLastTime()); transactionRecover.setRetriedCount(adapter.getRetriedCount()); transactionRecover.setCreateTime(adapter.getCreateTime()); @@ -99,7 +75,5 @@ public static TransactionRecover transformBean(byte[] contents, transactionRecover.setTransactionInvocation(transactionInvocation); transactionRecover.setVersion(adapter.getVersion()); return transactionRecover; - - } } diff --git a/raincat-common/src/main/java/com/raincat/common/holder/httpclient/AjaxResponse.java b/raincat-common/src/main/java/com/raincat/common/holder/httpclient/AjaxResponse.java index e5db9016..3c4c22fe 100644 --- a/raincat-common/src/main/java/com/raincat/common/holder/httpclient/AjaxResponse.java +++ b/raincat-common/src/main/java/com/raincat/common/holder/httpclient/AjaxResponse.java @@ -1,44 +1,39 @@ /* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * - * Copyright 2017-2018 549477611@qq.com(xiaoyu) - * - * This copyrighted material is made available to anyone wishing to use, modify, - * copy, or redistribute it subject to the terms and conditions of the GNU - * Lesser General Public License, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this distribution; if not, see . + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package com.raincat.common.holder.httpclient; - import java.io.Serializable; /** + * AjaxResponse. * @author xiaoyu - * @version 1.0 - * @date 2017 /3/1 11:52 - * @since JDK 1.8 **/ public class AjaxResponse implements Serializable { private static final long serialVersionUID = -2792556188993845048L; - protected int code; - protected String message; + private int code; + + private String message; + private Object data; - /** - * @param code 非-1的数 - */ - protected AjaxResponse(int code, String message, Object data) { + public AjaxResponse(int code, String message, Object data) { this.code = code; this.message = message; this.data = data; @@ -64,13 +59,6 @@ public static AjaxResponse error(String msg) { return error(CommonErrorCode.ERROR, msg); } - /** - * 响应错误 - * - * @param code 非-1的数 - * @param msg - * @return - */ public static AjaxResponse error(int code, String msg) { return get(code, msg, null); } diff --git a/raincat-common/src/main/java/com/raincat/common/holder/httpclient/CommonErrorCode.java b/raincat-common/src/main/java/com/raincat/common/holder/httpclient/CommonErrorCode.java index e262d04a..a60379c8 100644 --- a/raincat-common/src/main/java/com/raincat/common/holder/httpclient/CommonErrorCode.java +++ b/raincat-common/src/main/java/com/raincat/common/holder/httpclient/CommonErrorCode.java @@ -1,64 +1,47 @@ /* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * - * Copyright 2017-2018 549477611@qq.com(xiaoyu) - * - * This copyrighted material is made available to anyone wishing to use, modify, - * copy, or redistribute it subject to the terms and conditions of the GNU - * Lesser General Public License, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this distribution; if not, see . + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package com.raincat.common.holder.httpclient; - import org.apache.commons.lang3.StringUtils; /** - * 错误码定义类 - * 所有错误码使用10进制进行定义,0-20为系统全局保留使用, - * 其它各子系统分配99个错误码使用.
- * 错误码组成:由系统编码:+4位顺序号组成:0000+0000共8位 - * 错误码定义范围
- * 负数为非明确定义错误 + * 错误码定义类. * @author xiaoyu - * @version 1.0 - * @date 2017 /3/1 11:52 - * @since JDK 1.8 **/ public class CommonErrorCode { - /** - * 操作失败全局定义定义 + * 操作失败全局定义定义. */ public static final int ERROR = -2; /** - * 成功 + * 成功. */ public static final int SUCCESSFUL = 200; /** - * 传入的参数错误 - */ - public static final int PARAMS_ERROR = 10000002; - - - /** - * 获取错误码描述信息 + * 获取错误码描述信息. * * @param code 错误码枚举的name,指向自定义的信息 * @return 描述信息 */ - public static final String getErrorMsg(int code) { + public static String getErrorMsg(final int code) { //获取错误信息 String msg = System.getProperty(String.valueOf(code)); if (StringUtils.isBlank(msg)) { diff --git a/raincat-common/src/main/java/com/raincat/common/holder/httpclient/OkHttpTools.java b/raincat-common/src/main/java/com/raincat/common/holder/httpclient/OkHttpTools.java index 4f5f834c..d98316ef 100644 --- a/raincat-common/src/main/java/com/raincat/common/holder/httpclient/OkHttpTools.java +++ b/raincat-common/src/main/java/com/raincat/common/holder/httpclient/OkHttpTools.java @@ -1,20 +1,20 @@ /* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * - * Copyright 2017-2018 549477611@qq.com(xiaoyu) - * - * This copyrighted material is made available to anyone wishing to use, modify, - * copy, or redistribute it subject to the terms and conditions of the GNU - * Lesser General Public License, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this distribution; if not, see . + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package com.raincat.common.holder.httpclient; import com.google.gson.Gson; @@ -30,14 +30,16 @@ import java.util.Map; /** + * OkHttpTools. * @author xiaoyu */ -public class OkHttpTools { +public final class OkHttpTools { + + public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); private static final OkHttpTools OK_HTTP_TOOLS = new OkHttpTools(); - public static final MediaType JSON - = MediaType.parse("application/json; charset=utf-8"); + private static final Gson GOSN = new Gson(); private OkHttpTools() { @@ -47,20 +49,13 @@ public static OkHttpTools getInstance() { return OK_HTTP_TOOLS; } - - private Gson gson = new Gson(); - public Request buildPost(String url, Map params) { - - MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded"); - FormBody.Builder formBuilder = new FormBody.Builder(); if (params != null) { for (String key : params.keySet()) { formBuilder.add(key, params.get(key)); } } - return new Request.Builder() .url(url) .addHeader("Content-Type", "application/json; charset=utf-8") @@ -68,7 +63,6 @@ public Request buildPost(String url, Map params) { .build(); } - public String post(String url,String json) throws IOException { OkHttpClient client = new OkHttpClient(); RequestBody body = RequestBody.create(JSON, json); @@ -85,17 +79,15 @@ public T get(String url, Map params, Class classOfT) thro return execute(buildPost(url, params), classOfT); } - public T get(String url, Type type) throws IOException { return execute(buildPost(url, null), type); } - private T execute(Request request, Class classOfT) throws IOException { OkHttpClient client = new OkHttpClient(); Response response = client.newCall(request).execute(); - return gson.fromJson(response.body().string(), classOfT); + return GOSN.fromJson(response.body().string(), classOfT); } private String execute(Request request) throws IOException { @@ -105,11 +97,9 @@ private String execute(Request request) throws IOException { } public T execute(Request request, Type type) throws IOException { - OkHttpClient client = new OkHttpClient(); Response response = client.newCall(request).execute(); - return gson.fromJson(response.body().string(), type); - + return GOSN.fromJson(response.body().string(), type); } } diff --git a/raincat-common/src/main/java/com/raincat/common/jedis/JedisClient.java b/raincat-common/src/main/java/com/raincat/common/jedis/JedisClient.java index f85a4b39..c6c58f8a 100644 --- a/raincat-common/src/main/java/com/raincat/common/jedis/JedisClient.java +++ b/raincat-common/src/main/java/com/raincat/common/jedis/JedisClient.java @@ -1,19 +1,18 @@ /* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * - * Copyright 2017-2018 549477611@qq.com(xiaoyu) - * - * This copyrighted material is made available to anyone wishing to use, modify, - * copy, or redistribute it subject to the terms and conditions of the GNU - * Lesser General Public License, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this distribution; if not, see . + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package com.raincat.common.jedis; @@ -21,48 +20,43 @@ import java.util.Set; /** - *

Description: .

- * + * JedisClient. * @author xiaoyu(Myth) - * @version 1.0 - * @date 2017/10/26 14:48 - * @since JDK 1.8 */ public interface JedisClient { - /** - * set 操作 + * set 操作. * @param key key * @param value key - * @return + * @return String */ String set(String key, String value); /** - * set 操作 + * set 操作. * @param key key * @param value key - * @return + * @return String */ String set(String key, byte[] value); /** - * 批量删除key + * 批量删除key. * @param keys key集合 * @return 数量 */ Long del(String... keys); /** - * 根据key获取 + * 根据key获取. * @param key redis key * @return String */ String get(String key); /** - * 根据key获取 + * 根据key获取. * @param key redis key * @return byte[] */ @@ -70,21 +64,21 @@ public interface JedisClient { /** - * 根据key 模糊匹配 + * 根据key 模糊匹配. * @param pattern redis key - * @return Set + * @return Set byte[] */ - Set keys(final byte[] pattern); + Set keys(byte[] pattern); /** - * 根据key 模糊匹配 + * 根据key 模糊匹配. * @param key redis key - * @return Set + * @return Set String */ Set keys(String key); /** - * hash set值 + * hash set值. * @param key redis key * @param item hash key * @param value 值 @@ -93,7 +87,7 @@ public interface JedisClient { Long hset(String key, String item, String value); /** - * hash get 值 + * hash get 值. * @param key key * @param item hash key * @return value @@ -101,7 +95,7 @@ public interface JedisClient { String hget(String key, String item); /** - * hash del 值 + * hash del 值. * @param key key * @param item hash key * @return 数量 @@ -109,14 +103,14 @@ public interface JedisClient { Long hdel(String key, String item); /** - * 增加 + * 增加. * @param key key * @return Long */ Long incr(String key); /** - * 减少 + * 减少. * @param key key * @return Long */ @@ -124,22 +118,20 @@ public interface JedisClient { /** - * 设置key的过期时间 + * 设置key的过期时间. * @param key key * @param second 过期时间 秒 * @return Long */ Long expire(String key, int second); - /** - * 分页获取zsort + * 分页获取zsort. * @param key key * @param start 开始 * @param end 结束 - * @return Set + * @return Set String */ Set zrange(String key, long start, long end); - } diff --git a/raincat-common/src/main/java/com/raincat/common/jedis/JedisClientCluster.java b/raincat-common/src/main/java/com/raincat/common/jedis/JedisClientCluster.java index b6ace614..a30f5a0d 100644 --- a/raincat-common/src/main/java/com/raincat/common/jedis/JedisClientCluster.java +++ b/raincat-common/src/main/java/com/raincat/common/jedis/JedisClientCluster.java @@ -1,19 +1,18 @@ /* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * - * Copyright 2017-2018 549477611@qq.com(xiaoyu) - * - * This copyrighted material is made available to anyone wishing to use, modify, - * copy, or redistribute it subject to the terms and conditions of the GNU - * Lesser General Public License, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this distribution; if not, see . + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package com.raincat.common.jedis; @@ -23,91 +22,85 @@ import java.util.Set; /** - *

Description: .

- * + * JedisClientCluster. * @author xiaoyu(Myth) - * @version 1.0 - * @date 2017/10/26 15:35 - * @since JDK 1.8 */ public class JedisClientCluster implements JedisClient { - private JedisCluster jedisCluster; - public JedisClientCluster(JedisCluster jedisCluster) { + public JedisClientCluster(final JedisCluster jedisCluster) { this.jedisCluster = jedisCluster; } @Override - public String set(String key, String value) { + public String set(final String key, final String value) { return jedisCluster.set(key, value); } @Override - public String set(String key, byte[] value) { - return jedisCluster.set(key.getBytes(),value); + public String set(final String key, final byte[] value) { + return jedisCluster.set(key.getBytes(), value); } @Override - public Long del(String... keys) { + public Long del(final String... keys) { return jedisCluster.del(keys); } @Override - public String get(String key) { + public String get(final String key) { return jedisCluster.get(key); } @Override - public byte[] get(byte[] key) { + public byte[] get(final byte[] key) { return jedisCluster.get(key); } @Override - public Set keys(byte[] pattern) { + public Set keys(final byte[] pattern) { return jedisCluster.hkeys(pattern); } @Override - public Set keys(String key) { + public Set keys(final String key) { return jedisCluster.hkeys(key); } @Override - public Long hset(String key, String item, String value) { + public Long hset(final String key, final String item, final String value) { return jedisCluster.hset(key, item, value); } @Override - public String hget(String key, String item) { + public String hget(final String key, final String item) { return jedisCluster.hget(key, item); } @Override - public Long hdel(String key, String item) { + public Long hdel(final String key, final String item) { return jedisCluster.hdel(key, item); } @Override - public Long incr(String key) { + public Long incr(final String key) { return jedisCluster.incr(key); } @Override - public Long decr(String key) { + public Long decr(final String key) { return jedisCluster.decr(key); } @Override - public Long expire(String key, int second) { + public Long expire(final String key, final int second) { return jedisCluster.expire(key, second); } @Override - public Set zrange(String key, long start, long end) { - return jedisCluster.zrange(key,start,end); + public Set zrange(final String key, final long start, final long end) { + return jedisCluster.zrange(key, start, end); } - } diff --git a/raincat-common/src/main/java/com/raincat/common/jedis/JedisClientSingle.java b/raincat-common/src/main/java/com/raincat/common/jedis/JedisClientSingle.java index 85ced389..838de2b6 100644 --- a/raincat-common/src/main/java/com/raincat/common/jedis/JedisClientSingle.java +++ b/raincat-common/src/main/java/com/raincat/common/jedis/JedisClientSingle.java @@ -1,19 +1,18 @@ /* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * - * Copyright 2017-2018 549477611@qq.com(xiaoyu) - * - * This copyrighted material is made available to anyone wishing to use, modify, - * copy, or redistribute it subject to the terms and conditions of the GNU - * Lesser General Public License, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this distribution; if not, see . + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package com.raincat.common.jedis; @@ -24,135 +23,113 @@ import java.util.Set; /** - *

Description: .

- * + * JedisClientSingle. * @author xiaoyu(Myth) - * @version 1.0 - * @date 2017/10/26 14:50 - * @since JDK 1.8 */ public class JedisClientSingle implements JedisClient { private JedisPool jedisPool; - - public JedisClientSingle(JedisPool jedisPool) { + public JedisClientSingle(final JedisPool jedisPool) { this.jedisPool = jedisPool; } @Override - public String set(String key, String value) { + public String set(final String key, final String value) { try (Jedis jedis = jedisPool.getResource()) { return jedis.set(key, value); } - } @Override - public String set(String key, byte[] value) { + public String set(final String key, final byte[] value) { try (Jedis jedis = jedisPool.getResource()) { return jedis.set(key.getBytes(), value); } - } @Override - public Long del(String... keys) { + public Long del(final String... keys) { try (Jedis jedis = jedisPool.getResource()) { return jedis.del(keys); } - } @Override - public String get(String key) { + public String get(final String key) { try (Jedis jedis = jedisPool.getResource()) { return jedis.get(key); } - } @Override - public byte[] get(byte[] key) { + public byte[] get(final byte[] key) { try (Jedis jedis = jedisPool.getResource()) { return jedis.get(key); } } @Override - public Set keys(byte[] pattern) { - + public Set keys(final byte[] pattern) { try (Jedis jedis = jedisPool.getResource()) { return jedis.keys(pattern); } - } @Override - public Set keys(String key) { + public Set keys(final String key) { try (Jedis jedis = jedisPool.getResource()) { return jedis.keys(key); } } @Override - public Long hset(String key, String item, String value) { + public Long hset(final String key, final String item, final String value) { try (Jedis jedis = jedisPool.getResource()) { return jedis.hset(key, item, value); } - } @Override - public String hget(String key, String item) { + public String hget(final String key, final String item) { try (Jedis jedis = jedisPool.getResource()) { return jedis.hget(key, item); } } @Override - public Long hdel(String key, String item) { - + public Long hdel(final String key, final String item) { try (Jedis jedis = jedisPool.getResource()) { return jedis.hdel(key, item); } - } @Override - public Long incr(String key) { - + public Long incr(final String key) { try (Jedis jedis = jedisPool.getResource()) { return jedis.incr(key); } - } @Override - public Long decr(String key) { - + public Long decr(final String key) { try (Jedis jedis = jedisPool.getResource()) { - return jedis.decr(key); } - } @Override - public Long expire(String key, int second) { - + public Long expire(final String key, final int second) { try (Jedis jedis = jedisPool.getResource()) { return jedis.expire(key, second); } - } @Override - public Set zrange(String key, long start, long end) { + public Set zrange(final String key, final long start, final long end) { try (Jedis jedis = jedisPool.getResource()) { return jedis.zrange(key, start, end); } } - } diff --git a/raincat-common/src/main/java/com/raincat/common/netty/MessageCodecService.java b/raincat-common/src/main/java/com/raincat/common/netty/MessageCodecService.java index 19371c62..1172454e 100644 --- a/raincat-common/src/main/java/com/raincat/common/netty/MessageCodecService.java +++ b/raincat-common/src/main/java/com/raincat/common/netty/MessageCodecService.java @@ -15,6 +15,7 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.netty; import io.netty.buffer.ByteBuf; @@ -22,35 +23,27 @@ import java.io.IOException; /** + * MessageCodecService. * @author xiaoyu */ public interface MessageCodecService { /** - * 消息定长 + * 消息定长. */ int MESSAGE_LENGTH = 4; - /** - * netty 将java对象转成byteBuf + * netty 将java对象转成byteBuf. * * @param out 输出byteBuf * @param message 对象信息 * @throws IOException io异常 */ - void encode(final ByteBuf out, final Object message) throws IOException; - - - /** - * netty 将java对象转成byteBuf - * @param out 输出byteBuf - * @param message 对象信息 - * @throws IOException io异常 - */ + void encode(ByteBuf out, Object message) throws IOException; /** - * netty 将byteBuf转成java对象 + * netty 将byteBuf转成java对象. * * @param body byte数组 * @return Object diff --git a/raincat-common/src/main/java/com/raincat/common/netty/NettyPipelineInit.java b/raincat-common/src/main/java/com/raincat/common/netty/NettyPipelineInit.java index 1ed13762..7ba2359a 100644 --- a/raincat-common/src/main/java/com/raincat/common/netty/NettyPipelineInit.java +++ b/raincat-common/src/main/java/com/raincat/common/netty/NettyPipelineInit.java @@ -15,6 +15,7 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.netty; import com.raincat.common.enums.SerializeProtocolEnum; @@ -31,10 +32,17 @@ import io.netty.channel.ChannelPipeline; /** + * NettyPipelineInit. * @author xiaoyu */ public class NettyPipelineInit { - public static void serializePipeline(SerializeProtocolEnum serializeProtocol, ChannelPipeline pipeline) { + + /** + * add encoder and decoder in NettyPipeline. + * @param serializeProtocol {@linkplain SerializeProtocolEnum} + * @param pipeline {@linkplain ChannelPipeline} + */ + public static void serializePipeline(final SerializeProtocolEnum serializeProtocol, final ChannelPipeline pipeline) { switch (serializeProtocol) { case KRYO: KryoCodecServiceImpl kryoCodecServiceImpl = new KryoCodecServiceImpl(KryoPoolFactory.getKryoPoolInstance()); diff --git a/raincat-common/src/main/java/com/raincat/common/netty/NettyTransferSerialize.java b/raincat-common/src/main/java/com/raincat/common/netty/NettyTransferSerialize.java index 13c48b36..28229d75 100644 --- a/raincat-common/src/main/java/com/raincat/common/netty/NettyTransferSerialize.java +++ b/raincat-common/src/main/java/com/raincat/common/netty/NettyTransferSerialize.java @@ -15,6 +15,7 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.netty; import java.io.IOException; @@ -22,12 +23,13 @@ import java.io.OutputStream; /** + * NettyTransferSerialize. * @author xiaoyu */ public interface NettyTransferSerialize { /** - * netty 将object序列化成 OutputStream + * netty 将object序列化成 OutputStream. * * @param output OutputStream * @param object 对象 @@ -36,7 +38,7 @@ public interface NettyTransferSerialize { void serialize(OutputStream output, Object object) throws IOException; /** - * netty 将 InputStream 反序列成对象 + * netty 将 InputStream 反序列成对象. * * @param input 输出流 * @return object diff --git a/raincat-common/src/main/java/com/raincat/common/netty/bean/HeartBeat.java b/raincat-common/src/main/java/com/raincat/common/netty/bean/HeartBeat.java index e0254fd5..8339fce4 100644 --- a/raincat-common/src/main/java/com/raincat/common/netty/bean/HeartBeat.java +++ b/raincat-common/src/main/java/com/raincat/common/netty/bean/HeartBeat.java @@ -15,6 +15,7 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.netty.bean; import com.raincat.common.enums.NettyMessageActionEnum; @@ -24,6 +25,7 @@ import java.io.Serializable; /** + * HeartBeat. * @author xiaoyu */ @Data @@ -31,30 +33,24 @@ public class HeartBeat implements Serializable { private static final long serialVersionUID = 4183978848464761529L; - /** - * 执行动作 {@linkplain NettyMessageActionEnum} + * 执行动作. {@linkplain NettyMessageActionEnum} */ private int action; - /** - * 执行发送数据任务task key + * 执行发送数据任务task key. */ private String key; - /** - * {@linkplain NettyResultEnum} + * result. {@linkplain NettyResultEnum} */ private int result; - /** - * 事务组信息 + * 事务组信息. */ private TxTransactionGroup txTransactionGroup; - - } diff --git a/raincat-common/src/main/java/com/raincat/common/netty/bean/TxTransactionGroup.java b/raincat-common/src/main/java/com/raincat/common/netty/bean/TxTransactionGroup.java index a4bf5172..396702ef 100644 --- a/raincat-common/src/main/java/com/raincat/common/netty/bean/TxTransactionGroup.java +++ b/raincat-common/src/main/java/com/raincat/common/netty/bean/TxTransactionGroup.java @@ -15,6 +15,7 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.netty.bean; import com.raincat.common.enums.TransactionStatusEnum; @@ -23,31 +24,30 @@ import java.io.Serializable; import java.util.List; - /** + * TxTransactionGroup. * @author xiaoyu */ @Data public class TxTransactionGroup implements Serializable { - private static final long serialVersionUID = -8826219545126676832L; /** - * 事务组id + * 事务组id. */ private String id; /** - * 事务等待时间 + * 事务等待时间. */ private int waitTime; /** - * 事务状态 {@linkplain TransactionStatusEnum} + * 事务状态. {@linkplain TransactionStatusEnum} */ private int status; - private List itemList; + private List itemList; } diff --git a/raincat-common/src/main/java/com/raincat/common/netty/bean/TxTransactionItem.java b/raincat-common/src/main/java/com/raincat/common/netty/bean/TxTransactionItem.java index b0fbd939..3243bb0a 100644 --- a/raincat-common/src/main/java/com/raincat/common/netty/bean/TxTransactionItem.java +++ b/raincat-common/src/main/java/com/raincat/common/netty/bean/TxTransactionItem.java @@ -15,6 +15,7 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.netty.bean; import com.raincat.common.enums.TransactionRoleEnum; @@ -23,80 +24,78 @@ import java.io.Serializable; - /** + * TxTransactionItem. * @author xiaoyu */ @Data public class TxTransactionItem implements Serializable { private static final long serialVersionUID = -983809184773470584L; + /** - * taskKey + * taskKey. */ private String taskKey; /** - * 参与事务id + * 参与事务id. */ private String transId; /** - * 事务状态 {@linkplain TransactionStatusEnum} + * 事务状态. {@linkplain TransactionStatusEnum} */ private int status; /** - * 事务角色 {@linkplain TransactionRoleEnum} + * 事务角色. {@linkplain TransactionRoleEnum} */ private int role; /** - * 模块信息 + * 模块信息. */ private String modelName; /** - * tm 的域名信息 + * tm 的域名信息. */ private String tmDomain; - /** - * 存放事务组id + * 存放事务组id. */ private String txGroupId; /** - * 创建时间 + * 创建时间. */ private String createDate; /** - * 事务最大等待时间 单位秒 + * 事务最大等待时间 单位秒. */ private Integer waitMaxTime; - /** - * 执行类名称 + * 执行类名称. */ private String targetClass; + /** - * 执行方法 + * 执行方法. */ private String targetMethod; /** - * 耗时 秒 + * 耗时 秒. */ private Long consumeTime; - /** - * 操作结果信息 + * 操作结果信息. */ private Object message; - } diff --git a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/AbstractMessageDecoder.java b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/AbstractMessageDecoder.java index 06468f9f..0b0b3c04 100644 --- a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/AbstractMessageDecoder.java +++ b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/AbstractMessageDecoder.java @@ -15,6 +15,7 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.netty.serizlize; import com.raincat.common.netty.MessageCodecService; @@ -28,36 +29,34 @@ import java.util.logging.Logger; /** + * AbstractMessageDecoder. * @author xiaoyu */ -public abstract class AbstractMessageDecoder extends ByteToMessageDecoder { +public abstract class AbstractMessageDecoder extends ByteToMessageDecoder { + + private static final int MESSAGE_LENGTH = MessageCodecService.MESSAGE_LENGTH; - final private static int MESSAGE_LENGTH = MessageCodecService.MESSAGE_LENGTH; - private MessageCodecService util = null; + private MessageCodecService util; public AbstractMessageDecoder(final MessageCodecService service) { this.util = service; } @Override - protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) { + protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List out) { if (in.readableBytes() < AbstractMessageDecoder.MESSAGE_LENGTH) { return; } - in.markReaderIndex(); int messageLength = in.readInt(); - if (messageLength < 0) { ctx.close(); } - if (in.readableBytes() < messageLength) { in.resetReaderIndex(); } else { byte[] messageBody = new byte[messageLength]; in.readBytes(messageBody); - try { Object obj = util.decode(messageBody); out.add(obj); diff --git a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/AbstractMessageEncoder.java b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/AbstractMessageEncoder.java index 79234439..9c7b6c05 100644 --- a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/AbstractMessageEncoder.java +++ b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/AbstractMessageEncoder.java @@ -15,6 +15,7 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.netty.serizlize; import com.raincat.common.netty.MessageCodecService; @@ -23,11 +24,12 @@ import io.netty.handler.codec.MessageToByteEncoder; /** + * AbstractMessageEncoder. * @author xiaoyu */ public abstract class AbstractMessageEncoder extends MessageToByteEncoder { - private MessageCodecService util = null; + private MessageCodecService util; public AbstractMessageEncoder(final MessageCodecService util) { this.util = util; diff --git a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/hessian/HessianCodecServiceImpl.java b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/hessian/HessianCodecServiceImpl.java index a9042727..c75338bc 100644 --- a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/hessian/HessianCodecServiceImpl.java +++ b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/hessian/HessianCodecServiceImpl.java @@ -15,6 +15,7 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.netty.serizlize.hessian; import com.google.common.io.Closer; @@ -26,13 +27,14 @@ import java.io.IOException; /** + * HessianCodecServiceImpl. * @author xiaoyu */ public class HessianCodecServiceImpl implements MessageCodecService { - private HessianSerializePool pool = HessianSerializePool.getHessianPoolInstance(); private static Closer closer = Closer.create(); + private HessianSerializePool pool = HessianSerializePool.getHessianPoolInstance(); @Override public void encode(final ByteBuf out, final Object message) throws IOException { @@ -52,7 +54,7 @@ public void encode(final ByteBuf out, final Object message) throws IOException { } @Override - public Object decode(byte[] body) throws IOException { + public Object decode(final byte[] body) throws IOException { try { ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body); closer.register(byteArrayInputStream); diff --git a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/hessian/HessianDecoder.java b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/hessian/HessianDecoder.java index 596936f0..e9b32589 100644 --- a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/hessian/HessianDecoder.java +++ b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/hessian/HessianDecoder.java @@ -15,18 +15,19 @@ * along with this distribution; if not, see . * */ -package com.raincat.common.netty.serizlize.hessian; +package com.raincat.common.netty.serizlize.hessian; import com.raincat.common.netty.MessageCodecService; import com.raincat.common.netty.serizlize.AbstractMessageDecoder; /** + * HessianDecoder. * @author xiaoyu */ public class HessianDecoder extends AbstractMessageDecoder { - public HessianDecoder(MessageCodecService util) { + public HessianDecoder(final MessageCodecService util) { super(util); } } diff --git a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/hessian/HessianEncoder.java b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/hessian/HessianEncoder.java index 95940efc..bc684fd9 100644 --- a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/hessian/HessianEncoder.java +++ b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/hessian/HessianEncoder.java @@ -15,18 +15,19 @@ * along with this distribution; if not, see . * */ -package com.raincat.common.netty.serizlize.hessian; +package com.raincat.common.netty.serizlize.hessian; import com.raincat.common.netty.MessageCodecService; import com.raincat.common.netty.serizlize.AbstractMessageEncoder; /** + * HessianEncoder. * @author xiaoyu */ public class HessianEncoder extends AbstractMessageEncoder { - public HessianEncoder(MessageCodecService util) { + public HessianEncoder(final MessageCodecService util) { super(util); } } diff --git a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/hessian/HessianSerialize.java b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/hessian/HessianSerialize.java index 6ad08bde..e9229cb6 100644 --- a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/hessian/HessianSerialize.java +++ b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/hessian/HessianSerialize.java @@ -15,6 +15,7 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.netty.serizlize.hessian; import com.caucho.hessian.io.Hessian2Input; @@ -26,12 +27,13 @@ import java.io.OutputStream; /** + * HessianSerialize. * @author xiaoyu */ public class HessianSerialize implements NettyTransferSerialize { @Override - public void serialize(OutputStream output, Object object) { + public void serialize(final OutputStream output, final Object object) { Hessian2Output ho = new Hessian2Output(output); try { ho.startMessage(); @@ -45,7 +47,7 @@ public void serialize(OutputStream output, Object object) { } @Override - public Object deserialize(InputStream input) { + public Object deserialize(final InputStream input) { Object result = null; try { Hessian2Input hi = new Hessian2Input(input); @@ -59,4 +61,5 @@ public Object deserialize(InputStream input) { } return result; } + } diff --git a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/hessian/HessianSerializeFactory.java b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/hessian/HessianSerializeFactory.java index 315ac333..fbabb2ce 100644 --- a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/hessian/HessianSerializeFactory.java +++ b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/hessian/HessianSerializeFactory.java @@ -15,6 +15,7 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.netty.serizlize.hessian; import org.apache.commons.pool2.BasePooledObjectFactory; @@ -22,17 +23,18 @@ import org.apache.commons.pool2.impl.DefaultPooledObject; /** + * HessianSerializeFactory. * @author xiaoyu */ public class HessianSerializeFactory extends BasePooledObjectFactory { @Override - public HessianSerialize create() throws Exception { + public HessianSerialize create() { return createHessian(); } @Override - public PooledObject wrap(HessianSerialize hessian) { + public PooledObject wrap(final HessianSerialize hessian) { return new DefaultPooledObject<>(hessian); } diff --git a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/hessian/HessianSerializePool.java b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/hessian/HessianSerializePool.java index 3e88fb04..b469a463 100644 --- a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/hessian/HessianSerializePool.java +++ b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/hessian/HessianSerializePool.java @@ -15,24 +15,36 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.netty.serizlize.hessian; import org.apache.commons.pool2.impl.GenericObjectPool; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; - /** + * HessianSerializePool. * @author xiaoyu */ public class HessianSerializePool { + private static volatile HessianSerializePool poolFactory; + private GenericObjectPool hessianPool; - private static volatile HessianSerializePool poolFactory = null; private HessianSerializePool() { hessianPool = new GenericObjectPool<>(new HessianSerializeFactory()); } + public HessianSerializePool(final int maxTotal, final int minIdle, final long maxWaitMillis, final long minEvictableIdleTimeMillis) { + hessianPool = new GenericObjectPool<>(new HessianSerializeFactory()); + GenericObjectPoolConfig config = new GenericObjectPoolConfig(); + config.setMaxTotal(maxTotal); + config.setMinIdle(minIdle); + config.setMaxWaitMillis(maxWaitMillis); + config.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); + hessianPool.setConfig(config); + } + public static HessianSerializePool getHessianPoolInstance() { if (poolFactory == null) { synchronized (HessianSerializePool.class) { @@ -44,19 +56,6 @@ public static HessianSerializePool getHessianPoolInstance() { return poolFactory; } - public HessianSerializePool(final int maxTotal, final int minIdle, final long maxWaitMillis, final long minEvictableIdleTimeMillis) { - hessianPool = new GenericObjectPool<>(new HessianSerializeFactory()); - - GenericObjectPoolConfig config = new GenericObjectPoolConfig(); - - config.setMaxTotal(maxTotal); - config.setMinIdle(minIdle); - config.setMaxWaitMillis(maxWaitMillis); - config.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); - - hessianPool.setConfig(config); - } - public HessianSerialize borrow() { try { return getHessianPool().borrowObject(); diff --git a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/kryo/KryoCodecServiceImpl.java b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/kryo/KryoCodecServiceImpl.java index 7cc07f79..4b3ecc37 100644 --- a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/kryo/KryoCodecServiceImpl.java +++ b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/kryo/KryoCodecServiceImpl.java @@ -15,6 +15,7 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.netty.serizlize.kryo; import com.esotericsoftware.kryo.pool.KryoPool; @@ -27,19 +28,21 @@ import java.io.IOException; /** + * KryoCodecServiceImpl. * @author xiaoyu */ public class KryoCodecServiceImpl implements MessageCodecService { - private KryoPool pool; private static Closer closer = Closer.create(); - public KryoCodecServiceImpl(KryoPool pool) { + private KryoPool pool; + + public KryoCodecServiceImpl(final KryoPool pool) { this.pool = pool; } @Override - public void encode(ByteBuf out, Object message) throws IOException { + public void encode(final ByteBuf out, final Object message) throws IOException { try { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); closer.register(byteArrayOutputStream); @@ -55,14 +58,14 @@ public void encode(ByteBuf out, Object message) throws IOException { } @Override - public Object decode(byte[] body) throws IOException { + public Object decode(final byte[] body) throws IOException { try { ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body); closer.register(byteArrayInputStream); KryoSerialize kryoSerialization = new KryoSerialize(pool); return kryoSerialization.deserialize(byteArrayInputStream); } finally { - // closer.close(); + closer.close(); } } } diff --git a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/kryo/KryoDecoder.java b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/kryo/KryoDecoder.java index 4cdba395..42fb7cc7 100644 --- a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/kryo/KryoDecoder.java +++ b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/kryo/KryoDecoder.java @@ -15,17 +15,19 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.netty.serizlize.kryo; import com.raincat.common.netty.MessageCodecService; import com.raincat.common.netty.serizlize.AbstractMessageDecoder; /** + * KryoDecoder. * @author xiaoyu */ public class KryoDecoder extends AbstractMessageDecoder { - public KryoDecoder(MessageCodecService service) { + public KryoDecoder(final MessageCodecService service) { super(service); } } diff --git a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/kryo/KryoEncoder.java b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/kryo/KryoEncoder.java index d088b53c..7a83562d 100644 --- a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/kryo/KryoEncoder.java +++ b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/kryo/KryoEncoder.java @@ -15,17 +15,19 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.netty.serizlize.kryo; import com.raincat.common.netty.MessageCodecService; import com.raincat.common.netty.serizlize.AbstractMessageEncoder; /** + * KryoEncoder. * @author xiaoyu */ public class KryoEncoder extends AbstractMessageEncoder { - public KryoEncoder(MessageCodecService util) { + public KryoEncoder(final MessageCodecService util) { super(util); } } diff --git a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/kryo/KryoPoolFactory.java b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/kryo/KryoPoolFactory.java index 40233a39..09a3bc69 100644 --- a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/kryo/KryoPoolFactory.java +++ b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/kryo/KryoPoolFactory.java @@ -15,8 +15,8 @@ * along with this distribution; if not, see . * */ -package com.raincat.common.netty.serizlize.kryo; +package com.raincat.common.netty.serizlize.kryo; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.pool.KryoFactory; @@ -25,11 +25,12 @@ import org.objenesis.strategy.StdInstantiatorStrategy; /** + * KryoPoolFactory. * @author xiaoyu */ -public class KryoPoolFactory { +public final class KryoPoolFactory { - private static volatile KryoPoolFactory poolFactory = null; + private static volatile KryoPoolFactory poolFactory; private KryoFactory factory = () -> { Kryo kryo = new Kryo(); diff --git a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/kryo/KryoSerialize.java b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/kryo/KryoSerialize.java index 5f18eaf2..7e8d97c7 100644 --- a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/kryo/KryoSerialize.java +++ b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/kryo/KryoSerialize.java @@ -15,6 +15,7 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.netty.serizlize.kryo; import com.esotericsoftware.kryo.Kryo; @@ -28,18 +29,19 @@ import java.io.OutputStream; /** + * KryoSerialize. * @author xiaoyu */ public class KryoSerialize implements NettyTransferSerialize { - private KryoPool pool = null; + private KryoPool pool; public KryoSerialize(final KryoPool pool) { this.pool = pool; } @Override - public void serialize(OutputStream output, Object object) throws IOException { + public void serialize(final OutputStream output, final Object object) throws IOException { Kryo kryo = pool.borrow(); Output out = new Output(output); kryo.writeClassAndObject(out, object); @@ -49,13 +51,15 @@ public void serialize(OutputStream output, Object object) throws IOException { } @Override - public Object deserialize(InputStream input) throws IOException { - Kryo kryo = pool.borrow(); - Input in = new Input(input); - Object result = kryo.readClassAndObject(in); - in.close(); - input.close(); - pool.release(kryo); - return result; + public Object deserialize(final InputStream input) throws IOException { + Kryo kryo; + kryo = pool.borrow(); + try (Input in = new Input(input)) { + return kryo.readClassAndObject(in); + } finally { + input.close(); + pool.release(kryo); + } } + } diff --git a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/protostuff/ProtostuffCodecServiceImpl.java b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/protostuff/ProtostuffCodecServiceImpl.java index 5802e54f..c4734e86 100644 --- a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/protostuff/ProtostuffCodecServiceImpl.java +++ b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/protostuff/ProtostuffCodecServiceImpl.java @@ -15,6 +15,7 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.netty.serizlize.protostuff; import com.google.common.io.Closer; @@ -26,11 +27,15 @@ import java.io.IOException; /** + * ProtostuffCodecServiceImpl. * @author xiaoyu */ public class ProtostuffCodecServiceImpl implements MessageCodecService { + private static Closer closer = Closer.create(); + private ProtostuffSerializePool pool = ProtostuffSerializePool.getProtostuffPoolInstance(); + @Override public void encode(final ByteBuf out, final Object message) throws IOException { try { @@ -49,7 +54,7 @@ public void encode(final ByteBuf out, final Object message) throws IOException { } @Override - public Object decode(byte[] body) throws IOException { + public Object decode(final byte[] body) { try { ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body); closer.register(byteArrayInputStream); @@ -58,7 +63,11 @@ public Object decode(byte[] body) throws IOException { pool.restore(protostuffSerialization); return obj; } finally { - //closer.close(); + try { + closer.close(); + } catch (IOException e) { + e.printStackTrace(); + } } } } diff --git a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/protostuff/ProtostuffDecoder.java b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/protostuff/ProtostuffDecoder.java index e8810de9..fb45769f 100644 --- a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/protostuff/ProtostuffDecoder.java +++ b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/protostuff/ProtostuffDecoder.java @@ -15,18 +15,19 @@ * along with this distribution; if not, see . * */ -package com.raincat.common.netty.serizlize.protostuff; +package com.raincat.common.netty.serizlize.protostuff; import com.raincat.common.netty.MessageCodecService; import com.raincat.common.netty.serizlize.AbstractMessageDecoder; /** + * ProtostuffDecoder. * @author xiaoyu */ public class ProtostuffDecoder extends AbstractMessageDecoder { - public ProtostuffDecoder(MessageCodecService util) { + public ProtostuffDecoder(final MessageCodecService util) { super(util); } } diff --git a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/protostuff/ProtostuffEncoder.java b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/protostuff/ProtostuffEncoder.java index 9c08dc14..cfbee006 100644 --- a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/protostuff/ProtostuffEncoder.java +++ b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/protostuff/ProtostuffEncoder.java @@ -15,18 +15,19 @@ * along with this distribution; if not, see . * */ -package com.raincat.common.netty.serizlize.protostuff; +package com.raincat.common.netty.serizlize.protostuff; import com.raincat.common.netty.MessageCodecService; import com.raincat.common.netty.serizlize.AbstractMessageEncoder; /** + * ProtostuffEncoder. * @author xiaoyu */ public class ProtostuffEncoder extends AbstractMessageEncoder { - public ProtostuffEncoder(MessageCodecService util) { + public ProtostuffEncoder(final MessageCodecService util) { super(util); } } diff --git a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/protostuff/ProtostuffSerialize.java b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/protostuff/ProtostuffSerialize.java index 1961d476..e4bb8428 100644 --- a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/protostuff/ProtostuffSerialize.java +++ b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/protostuff/ProtostuffSerialize.java @@ -15,6 +15,7 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.netty.serizlize.protostuff; import com.dyuproject.protostuff.LinkedBuffer; @@ -29,18 +30,21 @@ import java.io.OutputStream; /** + * ProtostuffSerialize. * @author xiaoyu */ public class ProtostuffSerialize implements NettyTransferSerialize { + private static SchemaCache cachedSchema = SchemaCache.getInstance(); + private static Objenesis objenesis = new ObjenesisStd(true); - private static Schema getSchema(Class cls) { + private static Schema getSchema(final Class cls) { return (Schema) cachedSchema.get(cls); } @Override - public Object deserialize(InputStream input) { + public Object deserialize(final InputStream input) { try { HeartBeat message = objenesis.newInstance(HeartBeat.class); Schema schema = getSchema(HeartBeat.class); @@ -52,7 +56,7 @@ public Object deserialize(InputStream input) { } @Override - public void serialize(OutputStream output, Object object) { + public void serialize(final OutputStream output, final Object object) { Class cls = object.getClass(); LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE); try { diff --git a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/protostuff/ProtostuffSerializeFactory.java b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/protostuff/ProtostuffSerializeFactory.java index 48e67c35..0f353f60 100644 --- a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/protostuff/ProtostuffSerializeFactory.java +++ b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/protostuff/ProtostuffSerializeFactory.java @@ -15,6 +15,7 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.netty.serizlize.protostuff; import org.apache.commons.pool2.BasePooledObjectFactory; @@ -22,17 +23,18 @@ import org.apache.commons.pool2.impl.DefaultPooledObject; /** + * ProtostuffSerializeFactory. * @author xiaoyu */ public class ProtostuffSerializeFactory extends BasePooledObjectFactory { @Override - public ProtostuffSerialize create() throws Exception { + public ProtostuffSerialize create() { return createProtostuff(); } @Override - public PooledObject wrap(ProtostuffSerialize protostuffSerialize) { + public PooledObject wrap(final ProtostuffSerialize protostuffSerialize) { return new DefaultPooledObject<>(protostuffSerialize); } diff --git a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/protostuff/ProtostuffSerializePool.java b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/protostuff/ProtostuffSerializePool.java index 5dab7f8c..a79be2ba 100644 --- a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/protostuff/ProtostuffSerializePool.java +++ b/raincat-common/src/main/java/com/raincat/common/netty/serizlize/protostuff/ProtostuffSerializePool.java @@ -15,21 +15,34 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.netty.serizlize.protostuff; import org.apache.commons.pool2.impl.GenericObjectPool; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; /** + * ProtostuffSerializePool. * @author xiaoyu */ public class ProtostuffSerializePool { - private GenericObjectPool protostuffpool; - private static volatile ProtostuffSerializePool poolFactory = null; + private static volatile ProtostuffSerializePool poolFactory; + + private GenericObjectPool protostuffPool; private ProtostuffSerializePool() { - protostuffpool = new GenericObjectPool<>(new ProtostuffSerializeFactory()); + protostuffPool = new GenericObjectPool<>(new ProtostuffSerializeFactory()); + } + + public ProtostuffSerializePool(final int maxTotal, final int minIdle, final long maxWaitMillis, final long minEvictableIdleTimeMillis) { + protostuffPool = new GenericObjectPool<>(new ProtostuffSerializeFactory()); + GenericObjectPoolConfig config = new GenericObjectPoolConfig(); + config.setMaxTotal(maxTotal); + config.setMinIdle(minIdle); + config.setMaxWaitMillis(maxWaitMillis); + config.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); + protostuffPool.setConfig(config); } public static ProtostuffSerializePool getProtostuffPoolInstance() { @@ -43,22 +56,9 @@ public static ProtostuffSerializePool getProtostuffPoolInstance() { return poolFactory; } - public ProtostuffSerializePool(final int maxTotal, final int minIdle, final long maxWaitMillis, final long minEvictableIdleTimeMillis) { - protostuffpool = new GenericObjectPool<>(new ProtostuffSerializeFactory()); - - GenericObjectPoolConfig config = new GenericObjectPoolConfig(); - - config.setMaxTotal(maxTotal); - config.setMinIdle(minIdle); - config.setMaxWaitMillis(maxWaitMillis); - config.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); - - protostuffpool.setConfig(config); - } - public ProtostuffSerialize borrow() { try { - return getProtostuffpool().borrowObject(); + return getProtostuffPool().borrowObject(); } catch (final Exception ex) { ex.printStackTrace(); return null; @@ -66,11 +66,11 @@ public ProtostuffSerialize borrow() { } public void restore(final ProtostuffSerialize object) { - getProtostuffpool().returnObject(object); + getProtostuffPool().returnObject(object); } - public GenericObjectPool getProtostuffpool() { - return protostuffpool; + public GenericObjectPool getProtostuffPool() { + return protostuffPool; } } diff --git a/raincat-common/src/main/java/com/raincat/common/serializer/HessianSerializer.java b/raincat-common/src/main/java/com/raincat/common/serializer/HessianSerializer.java index b6a9c7d5..85172b55 100644 --- a/raincat-common/src/main/java/com/raincat/common/serializer/HessianSerializer.java +++ b/raincat-common/src/main/java/com/raincat/common/serializer/HessianSerializer.java @@ -1,20 +1,20 @@ /* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * - * Copyright 2017-2018 549477611@qq.com(xiaoyu) - * - * This copyrighted material is made available to anyone wishing to use, modify, - * copy, or redistribute it subject to the terms and conditions of the GNU - * Lesser General Public License, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this distribution; if not, see . + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package com.raincat.common.serializer; import com.caucho.hessian.io.Hessian2Input; @@ -27,27 +27,27 @@ import java.io.IOException; /** + * HessianSerializer. * @author xiaoyu */ @SuppressWarnings("unchecked") public class HessianSerializer implements ObjectSerializer { + @Override - public byte[] serialize(Object obj) throws TransactionException { - ByteArrayOutputStream baos; - try { - baos = new ByteArrayOutputStream(); - Hessian2Output hos = new Hessian2Output(baos); + public byte[] serialize(final Object obj) throws TransactionException { + Hessian2Output hos; + try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { + hos = new Hessian2Output(bos); hos.writeObject(obj); hos.flush(); - hos.close(); + return bos.toByteArray(); } catch (IOException ex) { throw new TransactionException("Hessian serialize error " + ex.getMessage()); } - return baos.toByteArray(); } @Override - public T deSerialize(byte[] param, Class clazz) throws TransactionException { + public T deSerialize(final byte[] param, final Class clazz) throws TransactionException { ByteArrayInputStream bios; try { bios = new ByteArrayInputStream(param); @@ -59,7 +59,7 @@ public T deSerialize(byte[] param, Class clazz) throws TransactionExcepti } /** - * 设置scheme + * 设置scheme. * * @return scheme 命名 */ diff --git a/raincat-common/src/main/java/com/raincat/common/serializer/JavaSerializer.java b/raincat-common/src/main/java/com/raincat/common/serializer/JavaSerializer.java index f0dbf480..5bca87ad 100644 --- a/raincat-common/src/main/java/com/raincat/common/serializer/JavaSerializer.java +++ b/raincat-common/src/main/java/com/raincat/common/serializer/JavaSerializer.java @@ -1,22 +1,21 @@ /* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * - * Copyright 2017-2018 549477611@qq.com(xiaoyu) - * - * This copyrighted material is made available to anyone wishing to use, modify, - * copy, or redistribute it subject to the terms and conditions of the GNU - * Lesser General Public License, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this distribution; if not, see . + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.raincat.common.serializer; +package com.raincat.common.serializer; import com.raincat.common.enums.SerializeProtocolEnum; import com.raincat.common.exception.TransactionException; @@ -30,38 +29,34 @@ import java.io.ObjectOutputStream; /** + * JavaSerializer. * @author xiaoyu */ @SuppressWarnings("unchecked") public class JavaSerializer implements ObjectSerializer { + @Override - public byte[] serialize(Object obj) throws TransactionException { - ByteArrayOutputStream arrayOutputStream; - try { - arrayOutputStream = new ByteArrayOutputStream(); - ObjectOutput objectOutput = new ObjectOutputStream(arrayOutputStream); + public byte[] serialize(final Object obj) throws TransactionException { + try (ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = new ObjectOutputStream(arrayOutputStream)) { objectOutput.writeObject(obj); objectOutput.flush(); - objectOutput.close(); + return arrayOutputStream.toByteArray(); } catch (IOException e) { - throw new TransactionException("JAVA serialize error " + e.getMessage()); + throw new TransactionException("java serialize error " + e.getMessage()); } - return arrayOutputStream.toByteArray(); } @Override - public T deSerialize(byte[] param, Class clazz) throws TransactionException { - ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(param); - try { - ObjectInput input = new ObjectInputStream(arrayInputStream); + public T deSerialize(final byte[] param, final Class clazz) throws TransactionException { + try (ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(param); ObjectInput input = new ObjectInputStream(arrayInputStream)) { return (T) input.readObject(); } catch (IOException | ClassNotFoundException e) { - throw new TransactionException("JAVA deSerialize error " + e.getMessage()); + throw new TransactionException("java deSerialize error " + e.getMessage()); } } /** - * 设置scheme + * 设置scheme. * * @return scheme 命名 */ diff --git a/raincat-common/src/main/java/com/raincat/common/serializer/KryoSerializer.java b/raincat-common/src/main/java/com/raincat/common/serializer/KryoSerializer.java index 7c62fcd8..39d3d890 100644 --- a/raincat-common/src/main/java/com/raincat/common/serializer/KryoSerializer.java +++ b/raincat-common/src/main/java/com/raincat/common/serializer/KryoSerializer.java @@ -1,20 +1,20 @@ /* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * - * Copyright 2017-2018 549477611@qq.com(xiaoyu) - * - * This copyrighted material is made available to anyone wishing to use, modify, - * copy, or redistribute it subject to the terms and conditions of the GNU - * Lesser General Public License, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this distribution; if not, see . + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package com.raincat.common.serializer; import com.esotericsoftware.kryo.Kryo; @@ -28,63 +28,42 @@ import java.io.IOException; /** + * KryoSerializer. * @author xiaoyu */ public class KryoSerializer implements ObjectSerializer { - /** - * 序列化 - * - * @param obj 需要序更列化的对象 - * @return 序列化后的byte 数组 - * @throws TransactionException - */ + @Override - public byte[] serialize(Object obj) throws TransactionException { + public byte[] serialize(final Object obj) throws TransactionException { byte[] bytes; - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - try { + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Output output = new Output(outputStream)) { //获取kryo对象 Kryo kryo = new Kryo(); - Output output = new Output(outputStream); kryo.writeObject(output, obj); bytes = output.toBytes(); output.flush(); - } catch (Exception ex) { + } catch (IOException ex) { throw new TransactionException("kryo serialize error" + ex.getMessage()); - } finally { - try { - outputStream.flush(); - outputStream.close(); - } catch (IOException e) { - - } } return bytes; } - /** - * 反序列化 - * - * @param param 需要反序列化的byte [] - * @return 序列化对象 - * @throws TransactionException - */ @Override - public T deSerialize(byte[] param, Class clazz) throws TransactionException { + public T deSerialize(final byte[] param, final Class clazz) throws TransactionException { T object; - try(ByteArrayInputStream inputStream=new ByteArrayInputStream(param)) { + try (ByteArrayInputStream inputStream = new ByteArrayInputStream(param)) { Kryo kryo = new Kryo(); Input input = new Input(inputStream); object = kryo.readObject(input, clazz); input.close(); - } catch (Exception e) { + } catch (IOException e) { throw new TransactionException("kryo deSerialize error" + e.getMessage()); } return object; } /** - * 设置scheme + * 设置scheme. * * @return scheme 命名 */ diff --git a/raincat-common/src/main/java/com/raincat/common/serializer/ObjectSerializer.java b/raincat-common/src/main/java/com/raincat/common/serializer/ObjectSerializer.java index 361e6011..6a6e7ce2 100644 --- a/raincat-common/src/main/java/com/raincat/common/serializer/ObjectSerializer.java +++ b/raincat-common/src/main/java/com/raincat/common/serializer/ObjectSerializer.java @@ -1,58 +1,54 @@ /* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * - * Copyright 2017-2018 549477611@qq.com(xiaoyu) - * - * This copyrighted material is made available to anyone wishing to use, modify, - * copy, or redistribute it subject to the terms and conditions of the GNU - * Lesser General Public License, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this distribution; if not, see . + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package com.raincat.common.serializer; + import com.raincat.common.exception.TransactionException; /** + * ObjectSerializer. * @author xiaoyu */ public interface ObjectSerializer { + /** - * 序列化对象 + * 序列化对象. * * @param obj 需要序更列化的对象 * @return byte [] - * @throws TransactionException 异常 + * @throws TransactionException 异常信息 */ byte[] serialize(Object obj) throws TransactionException; - /** - * 反序列化对象 - * - * @param param 需要反序列化的byte [] - * @return 对象 - * @throws TransactionException 异常 - */ /** - * 反序列化对象 + * 反序列化对象. * * @param param 需要反序列化的byte [] - * @param clazz 序列化后对应的java class - * @param 泛型 - * @return - * @throws TransactionException 异常 + * @param clazz java对象 + * @param 泛型支持 + * @return 对象 + * @throws TransactionException 异常信息 */ T deSerialize(byte[] param, Class clazz) throws TransactionException; /** - * 设置scheme + * 设置scheme. * * @return scheme 命名 */ diff --git a/raincat-common/src/main/java/com/raincat/common/serializer/ProtostuffSerializer.java b/raincat-common/src/main/java/com/raincat/common/serializer/ProtostuffSerializer.java index 100f05dc..0ba688e2 100644 --- a/raincat-common/src/main/java/com/raincat/common/serializer/ProtostuffSerializer.java +++ b/raincat-common/src/main/java/com/raincat/common/serializer/ProtostuffSerializer.java @@ -1,20 +1,20 @@ /* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * - * Copyright 2017-2018 549477611@qq.com(xiaoyu) - * - * This copyrighted material is made available to anyone wishing to use, modify, - * copy, or redistribute it subject to the terms and conditions of the GNU - * Lesser General Public License, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this distribution; if not, see . + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package com.raincat.common.serializer; import com.dyuproject.protostuff.LinkedBuffer; @@ -27,66 +27,53 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; +import java.io.IOException; /** + * ProtostuffSerializer. * @author xiaoyu */ +@SuppressWarnings("unchecked") public class ProtostuffSerializer implements ObjectSerializer { + private static final SchemaCache CACHED_SCHEMA = SchemaCache.getInstance(); - private static final Objenesis OBJENESIS_STD = new ObjenesisStd(true); - private static Schema getSchema(Class cls) { + private static final Objenesis OBJENESIS = new ObjenesisStd(true); + + private static Schema getSchema(final Class cls) { return (Schema) CACHED_SCHEMA.get(cls); } - - /** - * 序列化对象 - * - * @param obj 需要序更列化的对象 - * @return byte [] - * @throws TransactionException - */ @Override - public byte[] serialize(Object obj) throws TransactionException { + public byte[] serialize(final Object obj) throws TransactionException { Class cls = obj.getClass(); LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE); - try ( ByteArrayOutputStream outputStream = new ByteArrayOutputStream();){ + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { Schema schema = getSchema(cls); ProtostuffIOUtil.writeTo(outputStream, obj, schema, buffer); return outputStream.toByteArray(); - } catch (Exception e) { + } catch (IOException e) { throw new TransactionException(e.getMessage(), e); } finally { buffer.clear(); } } - /** - * 反序列化对象 - * - * @param param 需要反序列化的byte [] - * @param clazz - * @return 对象 - * @throws TransactionException - */ @Override - public T deSerialize(byte[] param, Class clazz) throws TransactionException { + public T deSerialize(final byte[] param, final Class clazz) throws TransactionException { T object; - try( ByteArrayInputStream inputStream = new ByteArrayInputStream(param)) { - Class cls = clazz; - object = OBJENESIS_STD.newInstance((Class) cls); - Schema schema = getSchema(cls); + try (ByteArrayInputStream inputStream = new ByteArrayInputStream(param)) { + object = OBJENESIS.newInstance(clazz); + Schema schema = getSchema((Class) clazz); ProtostuffIOUtil.mergeFrom(inputStream, object, schema); return object; - } catch (Exception e) { + } catch (IOException e) { throw new TransactionException(e.getMessage(), e); } } /** - * 设置scheme - * + * 设置scheme. * @return scheme 命名 */ @Override diff --git a/raincat-common/src/main/java/com/raincat/common/serializer/SchemaCache.java b/raincat-common/src/main/java/com/raincat/common/serializer/SchemaCache.java index c655d565..025c18a2 100644 --- a/raincat-common/src/main/java/com/raincat/common/serializer/SchemaCache.java +++ b/raincat-common/src/main/java/com/raincat/common/serializer/SchemaCache.java @@ -15,6 +15,7 @@ * along with this distribution; if not, see . * */ + package com.raincat.common.serializer; import com.dyuproject.protostuff.Schema; @@ -26,22 +27,19 @@ import java.util.concurrent.TimeUnit; /** + * SchemaCache. * @author xiaoyu */ public class SchemaCache { - private static class SchemaCacheHolder { - private static SchemaCache cache = new SchemaCache(); - } - public static SchemaCache getInstance() { + private Cache, Schema> cache = CacheBuilder.newBuilder() + .maximumSize(1024).expireAfterWrite(1, TimeUnit.HOURS).build(); + + protected static SchemaCache getInstance() { return SchemaCacheHolder.cache; } - private Cache, Schema> cache = CacheBuilder.newBuilder() - .maximumSize(1024).expireAfterWrite(1, TimeUnit.HOURS) - .build(); - - private Schema get(final Class cls, Cache, Schema> cache) { + private Schema get(final Class cls, final Cache, Schema> cache) { try { return cache.get(cls, () -> RuntimeSchema.createFrom(cls)); } catch (ExecutionException e) { @@ -49,8 +47,17 @@ private Schema get(final Class cls, Cache, Schema> cache) { } } - public Schema get(final Class cls) { - return get(cls, cache); + /** + * acquire Schema with class. + * @param clazz Class + * @return Schema + */ + public Schema get(final Class clazz) { + return get(clazz, cache); + } + + private static class SchemaCacheHolder { + private static SchemaCache cache = new SchemaCache(); } } diff --git a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/SerializeTest.java b/raincat-common/src/test/java/com/raincat/common/holder/httpclient/SerializeTest.java similarity index 98% rename from raincat-common/src/main/java/com/raincat/common/netty/serizlize/SerializeTest.java rename to raincat-common/src/test/java/com/raincat/common/holder/httpclient/SerializeTest.java index 24e0d6e5..b37149c0 100644 --- a/raincat-common/src/main/java/com/raincat/common/netty/serizlize/SerializeTest.java +++ b/raincat-common/src/test/java/com/raincat/common/holder/httpclient/SerializeTest.java @@ -15,7 +15,7 @@ * along with this distribution; if not, see . * */ -package com.raincat.common.netty.serizlize; +package com.raincat.common.holder.httpclient; import com.raincat.common.enums.NettyMessageActionEnum; import com.raincat.common.enums.TransactionStatusEnum; diff --git a/script/raincat_checks.xml b/script/raincat_checks.xml new file mode 100644 index 00000000..7b1f2e59 --- /dev/null +++ b/script/raincat_checks.xml @@ -0,0 +1,242 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +