diff --git a/center.manager/src/main/java/com/lyms/cm/controller/sys/SysRemoteController.java b/center.manager/src/main/java/com/lyms/cm/controller/sys/SysRemoteController.java index 5c7bf49..bfbbd35 100644 --- a/center.manager/src/main/java/com/lyms/cm/controller/sys/SysRemoteController.java +++ b/center.manager/src/main/java/com/lyms/cm/controller/sys/SysRemoteController.java @@ -4,31 +4,29 @@ import java.io.IOException; import javax.servlet.http.HttpServletRequest; +import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; -import com.lyms.cm.entity.sys.SysUsers; +import com.lyms.synch.ParamsHandler; +import com.lyms.synch.SycnHandler; import com.lyms.synch.SyncUtils; -import com.lyms.synch.entity.AckObj; -import com.lyms.synch.entity.SyncnModel; +import com.lyms.synch.entity.ChannelData; import com.lyms.web.controller.BaseController; @Controller @RequestMapping("/remote") +@Deprecated public class SysRemoteController extends BaseController { - @RequestMapping(value = "/push") + @RequestMapping(value = "/sycn", produces = { MediaType.APPLICATION_JSON_VALUE }) @ResponseBody - public String push(HttpServletRequest request) throws ClassNotFoundException, IOException { - SyncnModel model = SyncUtils.conver(request); - if (model.isAck()) { - AckObj ack = SyncUtils.converDataToAck(model); - System.out.println("回执信息: " + ack.getData()); - } else { - SysUsers user = SyncUtils.converData(model, SysUsers.class); - System.out.println("user: " + user.getName()); - } - return "OK"; + public Object push(HttpServletRequest request) throws ClassNotFoundException, IOException { + ChannelData model = SyncUtils.conver(request); + Object object = SycnHandler.handler(model); + model.setData(ParamsHandler.builder().push(object).toJsonString()); + model.setAck(true); + return model; } } diff --git a/center.manager/src/main/java/com/lyms/cm/dao/sys/SysRegionsMapper.xml b/center.manager/src/main/java/com/lyms/cm/dao/sys/SysRegionsMapper.xml index c949c49..bf1fa0a 100644 --- a/center.manager/src/main/java/com/lyms/cm/dao/sys/SysRegionsMapper.xml +++ b/center.manager/src/main/java/com/lyms/cm/dao/sys/SysRegionsMapper.xml @@ -30,5 +30,5 @@ re.PARENT_ID=#{id} - + diff --git a/center.manager/src/main/java/com/lyms/cm/job/SycnFixJob.java b/center.manager/src/main/java/com/lyms/cm/job/SycnFixJob.java new file mode 100644 index 0000000..d31c4cb --- /dev/null +++ b/center.manager/src/main/java/com/lyms/cm/job/SycnFixJob.java @@ -0,0 +1,75 @@ +package com.lyms.cm.job; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import com.lyms.synch.ParamsHandler; +import com.lyms.synch.SycnHandler; +import com.lyms.synch.SyncCallback; +import com.lyms.synch.SyncnCenter; +import com.lyms.synch.SyncnCenter.Work; +import com.lyms.synch.entity.ChannelData; +import com.lyms.util.HttpUtils; +import com.lyms.util.JsonUtils; + +/** + *
  • @ClassName: SycnJob + *
  • @Description: 同步任务执行器,依赖spring + *
  • @author maliang + *
  • @date 2017年3月14日 + *
  • + */ +public class SycnFixJob { + private Logger LOG = LoggerFactory.getLogger(getClass()); + + @Autowired + public SyncnCenter center; + + public void excute() { + // 拉取远端数据 + LOG.debug("执行拉取远程数据任务..."); + final Work work = center.buildWork(); + try { + work.pullFix(new SyncCallback() { + @Override + public void callBack(Object object) { + if (object instanceof ChannelData) { + ChannelData oldData = (ChannelData) object; + if (oldData != null && StringUtils.isNotBlank(oldData.getId())) { + // 任务发送执行 + System.out.println("拉取到本地任务: " + ToStringBuilder.reflectionToString(oldData)); + String result = HttpUtils.REMOTE.post(oldData); + System.out.println("返回结果: " + result); + if (StringUtils.isBlank(result)) + return; + ChannelData data = JsonUtils.jsonToBean(result, ChannelData.class); + // 处理回执消息 + if (data != null && data.getAck()) { + // 拉取到数据执行本地方法 + System.out.println("执行: " + ToStringBuilder.reflectionToString(data)); + Object handlResult = SycnHandler.handler(data); + // 要求处理成功都必须返回true | false; + Boolean tag = (Boolean) handlResult; + if (tag) { + data.setRemote(oldData.getRemote()); + data.setData(ParamsHandler.builder().push(data.getId()).toJsonString()); + data.setAck(true); + // 处理成功回执消息 + data.setRemoteClazz("com.lyms.hospital.service.sys.impl.SyncDataBasicServiceImpl"); + data.setRemoteMethod("updateBasic"); + work.ack(data); + } + } + } + } + } + }); + } catch (Exception e) { + LOG.error("同步数据错误 {}", e); + } + } + +} diff --git a/center.manager/src/main/java/com/lyms/cm/job/SycnTmpJob.java b/center.manager/src/main/java/com/lyms/cm/job/SycnTmpJob.java new file mode 100644 index 0000000..e36a577 --- /dev/null +++ b/center.manager/src/main/java/com/lyms/cm/job/SycnTmpJob.java @@ -0,0 +1,54 @@ +package com.lyms.cm.job; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import com.lyms.synch.SyncCallback; +import com.lyms.synch.SyncnCenter; +import com.lyms.synch.SyncnCenter.Work; +import com.lyms.synch.entity.ChannelData; +import com.lyms.util.HttpUtils; +import com.lyms.util.JsonUtils; + +/** + *
  • @ClassName: SycnJob + *
  • @Description: 同步任务执行器,依赖spring + *
  • @author maliang + *
  • @date 2017年3月14日 + *
  • + */ +public class SycnTmpJob { + + private Logger LOG = LoggerFactory.getLogger(getClass()); + + @Autowired + public SyncnCenter center; + + public void excute() { + // 拉取远端数据 + LOG.debug("执行推送远程数据任务..."); + final Work work = center.buildWork(); + try { + work.pullTmp(new SyncCallback() { + @Override + public void callBack(Object object) { + if (object instanceof ChannelData) { + ChannelData model = (ChannelData) object; + if (model != null) { + // 任务发送执行 + String result = HttpUtils.REMOTE.post(model); + model = JsonUtils.jsonToBean(result, ChannelData.class); + if (model != null && model.getAck()) { + work.backPressure(); + } + } + } + } + }); + } catch (Exception e) { + LOG.error("同步数据错误 {}", e); + work.backPressure(); + } + } +} diff --git a/center.manager/src/main/java/com/lyms/cm/job/package-info.java b/center.manager/src/main/java/com/lyms/cm/job/package-info.java new file mode 100644 index 0000000..8ca94e8 --- /dev/null +++ b/center.manager/src/main/java/com/lyms/cm/job/package-info.java @@ -0,0 +1,8 @@ +/** + *
  • @ClassName: package-info + *
  • @Description: TODO(类描述) + *
  • @author maliang + *
  • @date 2017年3月14日 + *
  • + */ +package com.lyms.cm.job; \ No newline at end of file diff --git a/center.manager/src/main/java/com/lyms/cm/service/sys/impl/SysUsersServiceImpl.java b/center.manager/src/main/java/com/lyms/cm/service/sys/impl/SysUsersServiceImpl.java index f8b8684..0216631 100644 --- a/center.manager/src/main/java/com/lyms/cm/service/sys/impl/SysUsersServiceImpl.java +++ b/center.manager/src/main/java/com/lyms/cm/service/sys/impl/SysUsersServiceImpl.java @@ -32,165 +32,165 @@ import com.lyms.util.StrUtils; @Service public class SysUsersServiceImpl extends ServiceImpl implements SysUsersService { - @Autowired - private SysUsersMapper userMapper; - - @Autowired - private SysUserRoleMapsService sysUserRoleMapsService; - - /** - * 系统默认密码 - */ - private static final String DEFAULT_PWD = "123456"; - - // 模块基础操作信息 - private boolean empty(SysUsers user) { - return user == null; - } - - /** - * 初始密码设置 - */ - private void initPwd(SysUsers user) { - if (empty(user)) - return; - String pwd = user.getPwd(); - if (StringUtils.isBlank(pwd)) { - pwd = DEFAULT_PWD; - } - String encode = MD5Utils.md5(pwd); - user.setPwd(encode); - } - - @Override - @Transactional - public boolean addUser(SysUsers user, List userRoleMapsList) throws SystemException { - if (empty(user)) - return false; - // 设置user ID - user.setIfdel(0); - if (null == user.getType()) {//没有勾选管理,就是用户 - user.setType(1); - } - if (null == user.getEnable()) { - user.setEnable(1); - } - // 设置用户密码 - this.initPwd(user); - - Integer tag = userMapper.insert(user); - if (!userRoleMapsList.isEmpty()) { - sysUserRoleMapsService.insertBatch(userRoleMapsList); - } - return tag != null && tag >= 1; - } - - @Override - @Transactional - public boolean updateUser(SysUsers user, List userRoleMapsList) throws SystemException { - if (empty(user)) - return false; - if (null == user.getType()) {//没有勾选管理,就是用户 - user.setType(1); - } - if (null == user.getEnable()) { - user.setEnable(1); - } - if (StrUtils.isNotEmpty(user.getPwd())) { - // 初始密码 - this.initPwd(user); - } - - Integer tag = userMapper.updateById(user); - EntityWrapper ew = new EntityWrapper(); - ew.where("user_id={0}", "'" + user.getId() + "'"); - sysUserRoleMapsService.delete(ew); - if (!userRoleMapsList.isEmpty()) { - sysUserRoleMapsService.insertBatch(userRoleMapsList); - } - return tag != null && tag >= 1; - } - - /* - * @Override public SysUsers getUserById(String userId) throws - * SystemException { if (StringUtils.isBlank(userId)) return null; return - * userMapper.selectById(userId); } - */ - - @Override - @Transactional - public boolean delete(String userId) throws SystemException { - - if (StringUtils.isBlank(userId)) - return false; - // TODO 通过sql 修改 - SysUsers user = userMapper.selectById(userId); - if (user != null) { - Integer ifDel = user.getIfdel(); - if (ifDel == null || ifDel == ValidityEnum.VALIDITY.getValidity()) { - ifDel = ValidityEnum.UNVALIDITY.getValidity(); - } else { - ifDel = ValidityEnum.VALIDITY.getValidity(); - } - user.setIfdel(ifDel); - Integer tag = userMapper.updateById(user); - return tag != null && tag >= 1; - } - return false; - } - - @Override - public Integer deleteLogicById(Serializable id) { - return baseMapper.deleteLogicById(id); - } - - @Override - public boolean isAllowUpdate(String account, String userid) { - boolean flag = true; - if (StrUtils.isNotEmpty(userid)) {//修改用户 - SysUsers oldDbUser = selectById(userid); - if (!oldDbUser.getAccount().equalsIgnoreCase(account)) {//登录账号改变 - flag = !isExistAccount(account); - } - } else {//新增 - flag = !isExistAccount(account); - } - return flag; - } - - /** - *
  • @Description:是否存在登录名 - *
  • @param account - *
  • @return - *
  • 创建人:方承 - *
  • 创建时间:2017年3月9日 - *
  • 修改人: - *
  • 修改时间: - */ - private boolean isExistAccount(String account) { - SysUsers entity = selectOne( - new EntityWrapper().where("account={0}", "'" + account + "'").and("ifDel=0")); - if (null == entity) { - return false; - } - return true; - } - - @Override - public SysUsers getUserByUsername(String name) { - SysUsers user = selectOne(new EntityWrapper().where("account={0}", name).and("ifDel=0")); - return user; - } - - @Override - public List getRoleIdListByUserid(String uid) { - List urList = sysUserRoleMapsService - .selectList(new EntityWrapper().where("user_id={0}", uid)); - List roleIdList = InstanceUtils.newArrayList(); - for (SysUserRoleMaps ur : urList) { - roleIdList.add(ur.getRoleId()); - } - return roleIdList; - } + @Autowired + private SysUsersMapper userMapper; + + @Autowired + private SysUserRoleMapsService sysUserRoleMapsService; + + /** + * 系统默认密码 + */ + private static final String DEFAULT_PWD = "123456"; + + // 模块基础操作信息 + private boolean empty(SysUsers user) { + return user == null; + } + + /** + * 初始密码设置 + */ + private void initPwd(SysUsers user) { + if (empty(user)) + return; + String pwd = user.getPwd(); + if (StringUtils.isBlank(pwd)) { + pwd = DEFAULT_PWD; + } + String encode = MD5Utils.md5(pwd); + user.setPwd(encode); + } + + @Override + @Transactional + public boolean addUser(SysUsers user, List userRoleMapsList) throws SystemException { + if (empty(user)) + return false; + // 设置user ID + user.setIfdel(0); + if (null == user.getType()) {// 没有勾选管理,就是用户 + user.setType(1); + } + if (null == user.getEnable()) { + user.setEnable(1); + } + // 设置用户密码 + this.initPwd(user); + + Integer tag = userMapper.insert(user); + if (userRoleMapsList != null && !userRoleMapsList.isEmpty()) { + sysUserRoleMapsService.insertBatch(userRoleMapsList); + } + return tag != null && tag >= 1; + } + + @Override + @Transactional + public boolean updateUser(SysUsers user, List userRoleMapsList) throws SystemException { + if (empty(user)) + return false; + if (null == user.getType()) {// 没有勾选管理,就是用户 + user.setType(1); + } + if (null == user.getEnable()) { + user.setEnable(1); + } + if (StrUtils.isNotEmpty(user.getPwd())) { + // 初始密码 + this.initPwd(user); + } + + Integer tag = userMapper.updateById(user); + EntityWrapper ew = new EntityWrapper(); + ew.where("user_id={0}", "'" + user.getId() + "'"); + sysUserRoleMapsService.delete(ew); + if (!userRoleMapsList.isEmpty()) { + sysUserRoleMapsService.insertBatch(userRoleMapsList); + } + return tag != null && tag >= 1; + } + + /* + * @Override public SysUsers getUserById(String userId) throws + * SystemException { if (StringUtils.isBlank(userId)) return null; return + * userMapper.selectById(userId); } + */ + + @Override + @Transactional + public boolean delete(String userId) throws SystemException { + + if (StringUtils.isBlank(userId)) + return false; + // TODO 通过sql 修改 + SysUsers user = userMapper.selectById(userId); + if (user != null) { + Integer ifDel = user.getIfdel(); + if (ifDel == null || ifDel == ValidityEnum.VALIDITY.getValidity()) { + ifDel = ValidityEnum.UNVALIDITY.getValidity(); + } else { + ifDel = ValidityEnum.VALIDITY.getValidity(); + } + user.setIfdel(ifDel); + Integer tag = userMapper.updateById(user); + return tag != null && tag >= 1; + } + return false; + } + + @Override + public Integer deleteLogicById(Serializable id) { + return baseMapper.deleteLogicById(id); + } + + @Override + public boolean isAllowUpdate(String account, String userid) { + boolean flag = true; + if (StrUtils.isNotEmpty(userid)) {// 修改用户 + SysUsers oldDbUser = selectById(userid); + if (!oldDbUser.getAccount().equalsIgnoreCase(account)) {// 登录账号改变 + flag = !isExistAccount(account); + } + } else {// 新增 + flag = !isExistAccount(account); + } + return flag; + } + + /** + *
  • @Description:是否存在登录名 + *
  • @param account + *
  • @return + *
  • 创建人:方承 + *
  • 创建时间:2017年3月9日 + *
  • 修改人: + *
  • 修改时间: + */ + private boolean isExistAccount(String account) { + SysUsers entity = selectOne( + new EntityWrapper().where("account={0}", "'" + account + "'").and("ifDel=0")); + if (null == entity) { + return false; + } + return true; + } + + @Override + public SysUsers getUserByUsername(String name) { + SysUsers user = selectOne(new EntityWrapper().where("account={0}", name).and("ifDel=0")); + return user; + } + + @Override + public List getRoleIdListByUserid(String uid) { + List urList = sysUserRoleMapsService + .selectList(new EntityWrapper().where("user_id={0}", uid)); + List roleIdList = InstanceUtils.newArrayList(); + for (SysUserRoleMaps ur : urList) { + roleIdList.add(ur.getRoleId()); + } + return roleIdList; + } } diff --git a/center.manager/src/main/resources/app-context.xml b/center.manager/src/main/resources/app-context.xml index 778ff2d..1c44a1b 100644 --- a/center.manager/src/main/resources/app-context.xml +++ b/center.manager/src/main/resources/app-context.xml @@ -17,6 +17,8 @@ + + diff --git a/center.manager/src/main/resources/xml/app-timer.xml b/center.manager/src/main/resources/xml/app-timer.xml new file mode 100644 index 0000000..8483291 --- /dev/null +++ b/center.manager/src/main/resources/xml/app-timer.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/center.manager/src/test/java/center/manager/test/user/WorkTest.java b/center.manager/src/test/java/center/manager/test/user/WorkTest.java index bee1e91..4848d84 100644 --- a/center.manager/src/test/java/center/manager/test/user/WorkTest.java +++ b/center.manager/src/test/java/center/manager/test/user/WorkTest.java @@ -1,15 +1,18 @@ package center.manager.test.user; +import org.apache.commons.lang3.builder.ToStringBuilder; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; -import com.lyms.cm.entity.sys.SysRoles; +import com.alibaba.fastjson.JSON; import com.lyms.cm.entity.sys.SysUsers; +import com.lyms.synch.ParamsHandler; import com.lyms.synch.SyncCallback; import com.lyms.synch.SyncnCenter; import com.lyms.synch.SyncnCenter.Work; -import com.lyms.synch.entity.ModelType; -import com.lyms.synch.entity.SyncnModel; +import com.lyms.synch.entity.ChannelData; +import com.lyms.util.HttpUtils; +import com.lyms.util.JsonUtils; import com.lyms.util.StrUtils; /** @@ -24,27 +27,18 @@ public class WorkTest extends BaseTest { @Autowired public SyncnCenter center; + @Test public void push() { - SyncnModel model = new SyncnModel(); - model.setId(StrUtils.uuid()); - model.setModel("user2"); - model.setMethod("post"); - model.setType(ModelType.ADD.name()); - // 推送数据远程地址 - model.setRemote("http://127.0.0.1:9090/center.manager/remote/push"); - // 对于远程获取数据,回调地址 - model.setCallBack("http://www.baidu.com"); - model.setTs(System.currentTimeMillis()); + String remote = "http://127.0.0.1:9090/hospital.web/remote/sycn"; + String remoteClazz = "com.lyms.hospital.service.sys.impl.SyncDataBasicServiceImpl"; + String remoteMethod = "selectOne"; + Object data = null;// new Object[] { user, null }; - SysUsers user = new SysUsers(); - user.setName("乱码测试"); - model.setData(user); + boolean loop = true; - SysRoles roles = new SysRoles(); - roles.setName("roles"); - user.setRoles(roles); + ChannelData push = new ChannelData(remote, remoteClazz, remoteMethod, null, loop); - center.buildWork().push(model, new SyncCallback() { + center.buildWork().push(push, new SyncCallback() { @Override public void callBack(Object object) { System.out.println("push callBack : " + object); @@ -62,19 +56,16 @@ public class WorkTest extends BaseTest { } }).start(); - new Thread(new Runnable() { - @Override - public void run() { - try { - fix(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - }).start(); + /* + * new Thread(new Runnable() { + * + * @Override public void run() { try { fix(); } catch + * (InterruptedException e) { e.printStackTrace(); } } }).start(); + */ + // while (true) { push(); - Thread.sleep(10000); + Thread.sleep(30000); } } @@ -82,21 +73,35 @@ public class WorkTest extends BaseTest { @Test public void tmp() { while (true) { - Work work = center.buildWork(); + final Work work = center.buildWork(); try { // final AckObj ack = new AckObj(); + work.pullTmp(new SyncCallback() { @Override public void callBack(Object object) { - SyncnModel model = (SyncnModel) object; - // String result = HttpUtils.REMOTE.post(model); - // ack.setData(result); - System.out.println("tmp ...."); + if (object == null) + return; + if (object instanceof ChannelData) { + ChannelData model = (ChannelData) object; + String result = HttpUtils.REMOTE.post(model); + System.out.println(result); + model = JsonUtils.jsonToBean(result, ChannelData.class); + System.out.println("回执: " + ToStringBuilder.reflectionToString(model)); + if (model != null) { + if (!model.getAck()) { + work.backPressure(); + } else { + System.out.println("远程数据处理成功"); + } + } + } } }); } catch (Exception e) { e.printStackTrace(); // 异常数据反压 + System.out.println("数据反压"); work.backPressure(); } } @@ -106,27 +111,56 @@ public class WorkTest extends BaseTest { public void fix() throws InterruptedException { // 获取固定任务队列任务 // 包含ack 回调方法 - while (true) { - Work work2 = center.buildWork(); - try { - // final AckObj ack = new AckObj(); - work2.pullFix(new SyncCallback() { - @Override - public void callBack(Object object) { + // while (true) { + Work work2 = center.buildWork(); + try { + // final AckObj ack = new AckObj(); + work2.pullFix(new SyncCallback() { + @Override + public void callBack(Object object) { + if (object != null && object instanceof ChannelData) { // remote - SyncnModel model = (SyncnModel) object; + ChannelData model = (ChannelData) object; // 处理实际业务 + System.out.println(ToStringBuilder.reflectionToString(model)); System.out.println(model.getRemote() + "====>fix"); - - // String result = HttpUtils.REMOTE.post(model); - // System.out.println(model.getModel()); + String result = HttpUtils.REMOTE.post(model); + System.out.println(result); // ack.setData(model.getData()); } - });// .ackGet(params);// .ackGet(null) - } catch (Exception e) { - e.printStackTrace(); - } - Thread.sleep(15000); + } + });// .ackGet(params);// .ackGet(null) + } catch (Exception e) { + e.printStackTrace(); } + // Thread.sleep(15000); + // } + } + + public static void buildParams() throws ClassNotFoundException { + String uid = StrUtils.uuid(); + + ChannelData data = ChannelData.emtpy(); + data.setId(uid); + data.setRemote(null); + data.setRemoteClazz("com.lyms.cm.service.sys.impl.SysUsersServiceImpl"); + data.setRemoteMethod("addUser"); + SysUsers user = new SysUsers(); + user.setId(uid); + user.setName("测试信息"); + // Object params = new Object[] { user, null }; + + // 设置参数 + ParamsHandler params = ParamsHandler.builder().push(user).push(null); + data.setData(params.toJsonString()); + + String str = JSON.toJSONString(data); + System.out.println(str); + } + + public static void main(String[] args) throws ClassNotFoundException { + buildParams(); + } + } diff --git a/core.sdk/src/main/java/com/lyms/spring/SpringContextHolder.java b/core.sdk/src/main/java/com/lyms/spring/SpringContextHolder.java index 23ecedb..edbae3e 100644 --- a/core.sdk/src/main/java/com/lyms/spring/SpringContextHolder.java +++ b/core.sdk/src/main/java/com/lyms/spring/SpringContextHolder.java @@ -8,14 +8,14 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Lazy; -import org.springframework.stereotype.Service; +import org.springframework.stereotype.Component; /** * * 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候取出ApplicaitonContext. * */ -@Service +@Component @Lazy(false) public class SpringContextHolder implements ApplicationContextAware, DisposableBean { @@ -92,7 +92,8 @@ public class SpringContextHolder implements ApplicationContextAware, DisposableB * */ private static void assertContextInjected() { - Validate.validState(applicationContext != null, "applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder."); + Validate.validState(applicationContext != null, + "applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder."); } /** diff --git a/core.sdk/src/main/java/com/lyms/synch/ParamsHandler.java b/core.sdk/src/main/java/com/lyms/synch/ParamsHandler.java new file mode 100644 index 0000000..2ca0804 --- /dev/null +++ b/core.sdk/src/main/java/com/lyms/synch/ParamsHandler.java @@ -0,0 +1,83 @@ +package com.lyms.synch; + +import java.io.Serializable; +import java.util.LinkedList; +import java.util.List; + +import com.lyms.util.JsonUtils; + +/** + *
  • @ClassName: ParamsHandler + *
  • @Description: 参数处理 + *
  • @author maliang + *
  • @date 2017年3月15日 + *
  • + */ +public class ParamsHandler implements Serializable { + + /** + */ + private static final long serialVersionUID = 7048461500310029490L; + private List params = new LinkedList<>(); + + public ParamsHandler() { + } + + public static ParamsHandler builder() { + return new ParamsHandler(); + } + + public String toJsonString() { + return JsonUtils.beanToJson(this); + } + + public ParamsHandler push(Object obj) { + if (obj == null) { + params.add(new Param(Object.class.getName(), "null")); + } else { + params.add(new Param(obj.getClass().getName(), obj)); + } + return this; + } + + public static class Param implements Serializable { + /** + */ + private static final long serialVersionUID = -1634342674830431814L; + private String className; + private Object obj; + + public Param() { + }; + + public Param(String className, Object obj) { + this.className = className; + this.obj = obj; + } + + public String getClassName() { + return className; + } + + public void setClassName(String className) { + this.className = className; + } + + public Object getObj() { + return obj; + } + + public void setObj(Object obj) { + this.obj = obj; + } + } + + public List getParams() { + return params; + } + + public void setParams(List params) { + this.params = params; + } + +} diff --git a/core.sdk/src/main/java/com/lyms/synch/SycnHandler.java b/core.sdk/src/main/java/com/lyms/synch/SycnHandler.java new file mode 100644 index 0000000..a6165d9 --- /dev/null +++ b/core.sdk/src/main/java/com/lyms/synch/SycnHandler.java @@ -0,0 +1,111 @@ +package com.lyms.synch; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.lyms.spring.SpringContextHolder; +import com.lyms.synch.ParamsHandler.Param; +import com.lyms.synch.entity.ChannelData; +import com.lyms.util.JsonUtils; + +/** + * + *
  • @ClassName: SyncHandler + *
  • @Description: 处理器 + *
  • @author maliang + *
  • @date 2017年3月15日 + *
  • + */ +public class SycnHandler { + + private static Logger LOG = LoggerFactory.getLogger(SycnHandler.class); + + public static Object handler(ChannelData data) { + try { + return invoke(data); + } catch (Exception e) { + LOG.error("执行方法错误: {}", e); + return false; + } + } + + private static Object invoke(ChannelData data) + throws ClassNotFoundException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + if (data == null) + return null; + + Class clazz = getClazz(data.getRemoteClazz()); + if (clazz == null) + return null; + Object tagetObject = getObject(clazz); + Method method = getMethod(clazz, data.getRemoteMethod()); + + return excute(tagetObject, method, data.getData()); + } + + private static Object excute(Object object, Method method, String params) + throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException { + if (method == null || object == null) + return null; + Object[] objs = null; + if (StringUtils.isNotBlank(params)) { + ParamsHandler handler = JsonUtils.jsonToBean(params, ParamsHandler.class); + if (handler != null) { + List ps = handler.getParams(); + objs = new Object[ps.size()]; + if (ps != null && !ps.isEmpty()) { + int i = 0; + for (Param p : ps) { + String clazz = p.getClassName(); + String value = p.getObj().toString(); + if (value.equalsIgnoreCase("null")) { + objs[i] = null; + } else { + // 做数据类型匹配,尽量多的排除基本类型 + // 针对业务出现的数据类型做处理 TODO + if (clazz.equals(String.class.getName()) || clazz.equals(Integer.class.getName()) + || clazz.equals(Long.class.getName()) || clazz.equals(Boolean.class.getName())) { + objs[i] = value; + } else { + Object tmp = JsonUtils.jsonToBean(value, getClazz(clazz)); + objs[i] = tmp; + } + + } + i++; + } + } + + } + } + // System.out.println(ToStringBuilder.reflectionToString(objs)); + return method.invoke(object, objs); + + } + + private static Class getClazz(String clazz) throws ClassNotFoundException { + if (StringUtils.isNotBlank(clazz)) { + return Class.forName(clazz); + } + return null; + } + + private static Object getObject(Class clazz) { + return SpringContextHolder.getBean(clazz); + } + + private static Method getMethod(Class clazz, String methodName) { + for (Method method : clazz.getDeclaredMethods()) { + if (method.getName().equalsIgnoreCase(methodName)) { + return method; + } + } + return null; + } + +} diff --git a/core.sdk/src/main/java/com/lyms/synch/SyncUtils.java b/core.sdk/src/main/java/com/lyms/synch/SyncUtils.java index 266842d..c0870ce 100644 --- a/core.sdk/src/main/java/com/lyms/synch/SyncUtils.java +++ b/core.sdk/src/main/java/com/lyms/synch/SyncUtils.java @@ -1,13 +1,11 @@ package com.lyms.synch; -import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import javax.servlet.http.HttpServletRequest; -import com.lyms.synch.entity.AckObj; -import com.lyms.synch.entity.SyncnModel; +import com.lyms.synch.entity.ChannelData; /** *
  • @ClassName: SyncUtils @@ -18,10 +16,15 @@ import com.lyms.synch.entity.SyncnModel; */ public class SyncUtils { - public static SyncnModel conver(HttpServletRequest request) throws IOException, ClassNotFoundException { - request.setCharacterEncoding("utf-8"); - ObjectInputStream dis = new ObjectInputStream(request.getInputStream()); - SyncnModel model = (SyncnModel) dis.readObject(); + public static ChannelData conver(HttpServletRequest request) { + ChannelData model = ChannelData.emtpy(); + try { + request.setCharacterEncoding("utf-8"); + ObjectInputStream dis = new ObjectInputStream(request.getInputStream()); + model = (ChannelData) dis.readObject(); + } catch (Exception e) { + e.printStackTrace(); + } return model; } @@ -35,7 +38,7 @@ public class SyncUtils { *
  • 修改时间: */ @SuppressWarnings("unchecked") - public static T converData(SyncnModel model, Class t) { + public static T converData(ChannelData model, Class t) { if (model == null || model.getData() == null) return null; if (!Serializable.class.isAssignableFrom(t)) { @@ -44,23 +47,4 @@ public class SyncUtils { return (T) model.getData(); } - /** - *
  • @Description:直接转化为ACK Object - *
  • @param model - *
  • @return - *
  • 创建人:maliang - *
  • 创建时间:2017年3月14日 - *
  • 修改人: - *
  • 修改时间: - */ - public static AckObj converDataToAck(SyncnModel model) { - if (model == null || model.getData() == null) - return null; - if (!(model.getData() instanceof AckObj)) { - return null; - } - return (AckObj) model.getData(); - // return converData(model, AckObj.class); - } - } diff --git a/core.sdk/src/main/java/com/lyms/synch/SyncnCenter.java b/core.sdk/src/main/java/com/lyms/synch/SyncnCenter.java index d8a2823..c722b7e 100644 --- a/core.sdk/src/main/java/com/lyms/synch/SyncnCenter.java +++ b/core.sdk/src/main/java/com/lyms/synch/SyncnCenter.java @@ -1,17 +1,11 @@ package com.lyms.synch; -import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; -import org.apache.commons.lang3.StringUtils; - -import com.lyms.synch.entity.AckObj; -import com.lyms.synch.entity.ModelType; -import com.lyms.synch.entity.SyncnModel; +import com.lyms.synch.entity.ChannelData; import com.lyms.synch.queue.SyncnQueue; import com.lyms.util.HttpUtils; -import com.lyms.util.StrUtils; /** *
  • @ClassName: SyncnCenter @@ -62,13 +56,13 @@ public class SyncnCenter { public class Work { - public SyncnModel model; + public ChannelData data; // public CenterCallback callBack; - public Work push(SyncnModel model, SyncCallback callBack) { - this.model = model; - Boolean tag = queue.push(model); + public Work push(ChannelData data, SyncCallback callBack) { + // this.model = model; + Boolean tag = queue.push(data); callBack.callBack(tag); return this; } @@ -85,9 +79,10 @@ public class SyncnCenter { *
  • 修改时间: */ public Work pullFix(SyncCallback callBack) { - SyncnModel model = queue.pull(ModelType.GET); - this.model = model; - callBack.callBack(model); + // SyncnModel model = queue.pull(ModelType.GET); + ChannelData data = queue.pull(true); + this.data = data; + callBack.callBack(data); return this; } @@ -103,9 +98,9 @@ public class SyncnCenter { *
  • 修改时间: */ public Work pullTmp(SyncCallback callBack) { - SyncnModel model = queue.pull(null); - this.model = model; - callBack.callBack(model); + ChannelData data = queue.pull(false); + this.data = data; + callBack.callBack(data); return this; } @@ -120,7 +115,9 @@ public class SyncnCenter { *
  • 修改时间: */ public void backPressure() { - this.push(model, new SyncCallback() { + if (data == null) + return; + this.push(data, new SyncCallback() { boolean tag = false; @Override @@ -137,68 +134,21 @@ public class SyncnCenter { /** *
  • @Description:回调方法,调用远端接口 *

    - * 跟 {@link #ackGet(Map)} {@link #ackPost(Map)} 的区别是,后两者需要自己设定callback - * 地址跟参数,可以指定任意地址 + * 该方法只有跟 {@link #pullFix(SyncCallback)} {@link #pullTmp(SyncCallback)} + * 才有意义 *

  • @return *
  • 创建人:maliang *
  • 创建时间:2017年3月14日 *
  • 修改人: *
  • 修改时间: */ - public String ack(AckObj ack) { - if (model != null && !model.isAck() && StringUtils.isNotBlank(model.getRemote())) { - model.setId(StrUtils.uuid()); - model.setTs(System.currentTimeMillis()); - model.setData(ack); - model.setType(ModelType.ACK.name()); - ack.setOldType(model.getType()); - return HttpUtils.REMOTE.post(model); - } - return null; - } - - /** - *
  • @Description:该方法为回执方法,将会调用目标接口,返回提示对应消息处理成功 - *

    - * 使用方式 pull(type,callBack).ackGet(); - *

    - * 目前该方法对PULL 的消息回执才有实际的意义 - *

  • @return - *
  • 创建人:maliang - *
  • 创建时间:2017年3月13日 - *
  • 修改人: - *
  • 修改时间: - */ - public String ackGet(Map params) { - if (model != null && StringUtils.isNotBlank(model.getCallBack())) { - return HttpUtils.REMOTE.get(model.getCallBack(), params); - } - return null; - } - - public String ackPost(Map params) { - if (model != null && StringUtils.isNotBlank(model.getCallBack())) { - return HttpUtils.REMOTE.post(model.getCallBack(), params); + public String ack(ChannelData ackData) { + if (ackData != null) { + HttpUtils.REMOTE.post(ackData); } return null; } - /** - *
  • @Description:该方法主要检测是否重复执行,对应数据 - *

    - * TODO - *

    - * 使用方式 push(model,callBack).validata(); - *

  • @return - *
  • 创建人:maliang - *
  • 创建时间:2017年3月13日 - *
  • 修改人: - *
  • 修改时间: - */ - public Work validata() { - return this; - } - } public SyncnQueue getQueue() { diff --git a/core.sdk/src/main/java/com/lyms/synch/entity/AckObj.java b/core.sdk/src/main/java/com/lyms/synch/entity/AckObj.java deleted file mode 100644 index c6eb330..0000000 --- a/core.sdk/src/main/java/com/lyms/synch/entity/AckObj.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.lyms.synch.entity; - -import java.io.Serializable; - -/** - *
  • @ClassName: AckObj - *
  • @Description: 回调实体,用于封装获取到的数据信息 - *
  • @author maliang - *
  • @date 2017年3月14日 - *
  • - */ -public class AckObj implements Serializable { - - /** - */ - private static final long serialVersionUID = -3939046868818014917L; - - /** - * {@link ModelType} 获取数据 - */ - private String oldType; - - /** - * remote、获取的数据信息,该参数需要自行封装 - */ - private Object data; - - public String getOldType() { - return oldType; - } - - public void setOldType(String oldType) { - this.oldType = oldType; - } - - public Object getData() { - return data; - } - - public void setData(Object data) { - this.data = data; - } -} diff --git a/core.sdk/src/main/java/com/lyms/synch/entity/ChannelData.java b/core.sdk/src/main/java/com/lyms/synch/entity/ChannelData.java new file mode 100644 index 0000000..f9b2197 --- /dev/null +++ b/core.sdk/src/main/java/com/lyms/synch/entity/ChannelData.java @@ -0,0 +1,143 @@ +package com.lyms.synch.entity; + +import java.io.Serializable; + +import com.lyms.util.JsonUtils; +import com.lyms.util.StrUtils; + +/** + *
  • @ClassName: ChannelData + *
  • @Description: 通道实体 + *
  • @author maliang + *
  • @date 2017年3月15日 + *
  • + */ +public class ChannelData implements Serializable { + + /** + */ + private static final long serialVersionUID = -4448732709523865922L; + + public ChannelData() { + }; + + public static ChannelData emtpy() { + return new ChannelData(); + } + + /** + * 数据传输ID + */ + private String id; + + /** + * remote address + */ + private String remote; + + /** + * remote class name + */ + private String remoteClazz; + + /** + * remote method name + */ + private String remoteMethod; + + /** + * remote body json + */ + private String data; + + private Boolean loop = Boolean.FALSE; + + /** + * 是否回执信息 + */ + private Boolean ack = Boolean.FALSE; + + /** + * 创建时间 + */ + private Long ts; + + public ChannelData(String remote, String remoteClazz, String remoteMethod, String data, boolean loop) { + this.id = StrUtils.uuid(); + this.remote = remote; + this.remoteClazz = remoteClazz; + this.remoteMethod = remoteMethod; + this.data = data; + this.ts = System.currentTimeMillis(); + this.loop = loop; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getRemote() { + return remote; + } + + public void setRemote(String remote) { + this.remote = remote; + } + + public String getRemoteClazz() { + return remoteClazz; + } + + public void setRemoteClazz(String remoteClazz) { + this.remoteClazz = remoteClazz; + } + + public String getRemoteMethod() { + return remoteMethod; + } + + public void setRemoteMethod(String remoteMethod) { + this.remoteMethod = remoteMethod; + } + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } + + public Long getTs() { + return ts; + } + + public void setTs(Long ts) { + this.ts = ts; + } + + public Boolean getLoop() { + return loop; + } + + public void setLoop(Boolean loop) { + this.loop = loop; + } + + public Boolean getAck() { + return ack; + } + + public void setAck(Boolean ack) { + this.ack = ack; + } + + public String toJsonString() { + return JsonUtils.beanToJson(this); + } + +} diff --git a/core.sdk/src/main/java/com/lyms/synch/entity/Model.java b/core.sdk/src/main/java/com/lyms/synch/entity/Model.java deleted file mode 100644 index 8513bb0..0000000 --- a/core.sdk/src/main/java/com/lyms/synch/entity/Model.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.lyms.synch.entity; - -/** - *
  • @ClassName: Model - *
  • @Description: 模块信息 - *
  • @author maliang - *
  • @date 2017年3月13日 - *
  • - */ -public enum Model { - USER("用户信息"); - - private String des; - - private Model(String des) { - this.des = des; - } - - public String getDes() { - return this.des; - } -} diff --git a/core.sdk/src/main/java/com/lyms/synch/entity/ModelType.java b/core.sdk/src/main/java/com/lyms/synch/entity/ModelType.java deleted file mode 100644 index 9065e9f..0000000 --- a/core.sdk/src/main/java/com/lyms/synch/entity/ModelType.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.lyms.synch.entity; - -import java.util.EnumSet; - -/** - *
  • @ClassName: ModelType - *
  • @Description: 数据模型类型 - *
  • @author maliang - *
  • @date 2017年3月13日 - *
  • - */ -public enum ModelType { - - ADD, DEL, UPDATE, GET, ACK; - - public static ModelType exitsType(String typeName) { - for (ModelType modelType : EnumSet.allOf(ModelType.class)) { - if (modelType.name().equalsIgnoreCase(typeName)) { - return modelType; - } - } - return null; - } - - public static boolean isAdd(String type) { - return ADD.equals(exitsType(type)); - } - - public static boolean isACK(String type) { - return ACK.equals(exitsType(type)); - } - - public static boolean isDel(String type) { - return DEL.equals(exitsType(type)); - } - - public static boolean isUpdate(String type) { - return UPDATE.equals(exitsType(type)); - } - - public static boolean isGet(String type) { - return GET.equals(exitsType(type)); - } - - public static boolean isGet(ModelType type) { - return GET.equals(type); - } - - public static void main(String[] args) { - System.out.println(ModelType.isAdd("add")); - } - -} diff --git a/core.sdk/src/main/java/com/lyms/synch/entity/SyncnModel.java b/core.sdk/src/main/java/com/lyms/synch/entity/SyncnModel.java deleted file mode 100644 index 9068d9b..0000000 --- a/core.sdk/src/main/java/com/lyms/synch/entity/SyncnModel.java +++ /dev/null @@ -1,132 +0,0 @@ -package com.lyms.synch.entity; - -import java.io.Serializable; - -import com.lyms.util.JsonUtils; - -/** - *
  • @ClassName: SynceModel - *
  • @Description: 数据模型 - *
  • @author maliang - *
  • @date 2017年3月13日 - *
  • - */ -public class SyncnModel implements Serializable { - - /** - */ - private static final long serialVersionUID = -5121448640215880284L; - - /** - * 消息模型ID - */ - private String id; - - /** - * 远程地址,远程访问的服务地址 - */ - private String remote; - - /** - * 回调地址,获取数据处理的时候该参数才有实际意义 - */ - private String callBack; - - /** - * get | post - */ - private String method; - - /** - * 操作类型 - */ - private String type; - - /** - * 模块 - */ - private String model; - - /** - * 数据信息 - */ - private Object data; - - /** - * 操作时间 - */ - private Long ts; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getModel() { - return model; - } - - public void setModel(String model) { - this.model = model; - } - - public Object getData() { - return data; - } - - public void setData(Object data) { - this.data = data; - } - - public Long getTs() { - return ts; - } - - public void setTs(Long ts) { - this.ts = ts; - } - - public String getRemote() { - return remote; - } - - public void setRemote(String remote) { - this.remote = remote; - } - - public String getCallBack() { - return callBack; - } - - public void setCallBack(String callBack) { - this.callBack = callBack; - } - - public String getMethod() { - return method; - } - - public void setMethod(String method) { - this.method = method; - } - - public static SyncnModel conver(String body) { - return JsonUtils.jsonToBean(body, SyncnModel.class); - } - - public boolean isAck() { - return ModelType.isACK(getType()); - } - -} diff --git a/core.sdk/src/main/java/com/lyms/synch/queue/SyncnQueue.java b/core.sdk/src/main/java/com/lyms/synch/queue/SyncnQueue.java index 3634487..77ed320 100644 --- a/core.sdk/src/main/java/com/lyms/synch/queue/SyncnQueue.java +++ b/core.sdk/src/main/java/com/lyms/synch/queue/SyncnQueue.java @@ -5,8 +5,7 @@ import java.io.Serializable; import org.springframework.data.redis.core.RedisTemplate; import com.lyms.spring.redis.operation.RedisLock; -import com.lyms.synch.entity.ModelType; -import com.lyms.synch.entity.SyncnModel; +import com.lyms.synch.entity.ChannelData; /** *
  • @ClassName: SyncnQueue @@ -73,25 +72,24 @@ public class SyncnQueue { *
  • 修改人: *
  • 修改时间: */ - private Boolean pushFixationWork(SyncnModel model) { - Long tag = template.opsForList().leftPush(FIXATION_WORK, model); + private Boolean pushFixationWork(ChannelData data) { + Long tag = template.opsForList().leftPush(FIXATION_WORK, data); return tag >= 1; } - private SyncnModel pullFixationModel() { + private ChannelData pullFixationData() { // 添加锁 try { - if (Tmp_Lock.acquireLock(LOCK_FIXATION_NAME, WAIT_LOCK_TIME)) { - SyncnModel obj = (SyncnModel) template.opsForList().rightPopAndLeftPush(FIXATION_WORK, FIXATION_WORK); - // this.pushFixationWork(obj); + if (Fix_Lock.acquireLock(LOCK_FIXATION_NAME, WAIT_LOCK_TIME)) { + ChannelData obj = (ChannelData) template.opsForList().rightPopAndLeftPush(FIXATION_WORK, FIXATION_WORK); return obj; } } catch (Exception e) { e.printStackTrace(); } finally { try { - if (Tmp_Lock != null) { - Tmp_Lock.releaseLock(); + if (Fix_Lock != null) { + Fix_Lock.releaseLock(); } } catch (Exception e) { e.printStackTrace(); @@ -112,8 +110,8 @@ public class SyncnQueue { *
  • 修改人: *
  • 修改时间: */ - private boolean pushTempWork(SyncnModel model) { - Long tag = template.opsForList().leftPush(TMP_WORK, model); + private boolean pushTempWork(ChannelData data) { + Long tag = template.opsForList().leftPush(TMP_WORK, data); return tag >= 1; } @@ -125,12 +123,12 @@ public class SyncnQueue { *
  • 修改人: *
  • 修改时间: */ - private SyncnModel pullTempModel() { + private ChannelData pullTempData() { try { if (Tmp_Lock.acquireLock(LOCK_TMP_NAME, WAIT_LOCK_TIME)) { Serializable object = template.opsForList().rightPop(TMP_WORK); - return object != null ? (SyncnModel) object : null; + return object != null ? (ChannelData) object : null; } } catch (Exception e) { e.printStackTrace(); @@ -156,23 +154,23 @@ public class SyncnQueue { *
  • 修改人: *
  • 修改时间: */ - public Boolean push(SyncnModel model) { - if (template == null || model == null) + public Boolean push(ChannelData data) { + if (template == null || data == null) return Boolean.FALSE; // 设置任务添加时间 - model.setTs(System.currentTimeMillis()); - String modelType = model.getType(); - if (ModelType.isGet(modelType)) { - return this.pushFixationWork(model); - } else { - return this.pushTempWork(model); - } + /* + * model.setTs(System.currentTimeMillis()); String modelType = + * model.getType(); if (ModelType.isGet(modelType)) { return + * this.pushFixationWork(model); } else { return + * this.pushTempWork(model); } + */ + boolean loop = data.getLoop(); + return loop ? this.pushFixationWork(data) : this.pushTempWork(data); } /** *
  • @Description:获取队列中的数据 *

    - * {@link ModelType#GET} 该参数将会获取固定任务列表中的数据{@link ModelType} 其他参数将会获取临时列表中数据 *

  • @param type *
  • @return *
  • 创建人:maliang @@ -180,12 +178,13 @@ public class SyncnQueue { *
  • 修改人: *
  • 修改时间: */ - public SyncnModel pull(ModelType type) { - if (ModelType.isGet(type)) { - return this.pullFixationModel(); - } else { - return this.pullTempModel(); - } + public ChannelData pull(boolean loop) { + // boolean loop = data != null && data.getLoop(); + return loop ? this.pullFixationData() : this.pullTempData(); + /* + * if (ModelType.isGet(type)) { return this.pullFixationModel(); } else + * { return this.pullTempModel(); } + */ } public RedisTemplate getTemplate() { diff --git a/core.sdk/src/main/java/com/lyms/util/StrUtils.java b/core.sdk/src/main/java/com/lyms/util/StrUtils.java index 05e179e..7c28259 100644 --- a/core.sdk/src/main/java/com/lyms/util/StrUtils.java +++ b/core.sdk/src/main/java/com/lyms/util/StrUtils.java @@ -8,13 +8,14 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; -import java.util.UUID; import java.util.Map.Entry; -/** - *
  • ClassName:StrUtils
    +import java.util.UUID; + +/** + *
  • ClassName:StrUtils
    *
  • @Description: TODO(类描述) - *
  • @Date: 2016年9月22日
    - *
  • @author 方承 + *
  • @Date: 2016年9月22日
    + *
  • @author 方承 */ public class StrUtils { @@ -36,27 +37,29 @@ public class StrUtils { public static final String EMPTY_JSON = "{}"; - // ------------------------------------------------------------------------ Blank - - /** + // ------------------------------------------------------------------------ + // Blank + + /** *
  • @Description: 生成32位全大写uuid *
  • @return *
  • 创建人:方承 *
  • 创建时间:2016年1月5日 *
  • 修改人: *
  • 修改时间: - */ + */ public static String uuid() { return UUID.randomUUID().toString().replace("-", "").toUpperCase(); } - + /** * 字符串是否为空白 空白的定义如下:
    * 1、为null
    * 2、为不可见字符(如空格)
    * 3、""
    * - * @param str 被检测的字符串 + * @param str + * 被检测的字符串 * @return 是否为空 */ public static boolean isBlank(String str) { @@ -82,7 +85,8 @@ public class StrUtils { * 2、不为不可见字符(如空格)
    * 3、不为""
    * - * @param str 被检测的字符串 + * @param str + * 被检测的字符串 * @return 是否为非空 */ public static boolean isNotBlank(String str) { @@ -92,7 +96,8 @@ public class StrUtils { /** * 是否包含空字符串 * - * @param strs 字符串列表 + * @param strs + * 字符串列表 * @return 是否包含空字符串 */ public static boolean hasBlank(String... strs) { @@ -111,7 +116,8 @@ public class StrUtils { /** * 给定所有字符串是否为空白 * - * @param strs 字符串 + * @param strs + * 字符串 * @return 所有字符串是否为空白 */ public static boolean isAllBlank(String... strs) { @@ -127,12 +133,14 @@ public class StrUtils { return true; } - // ------------------------------------------------------------------------ Empty + // ------------------------------------------------------------------------ + // Empty /** * 字符串是否为空,空的定义如下 1、为null
    * 2、为""
    * - * @param str 被检测的字符串 + * @param str + * 被检测的字符串 * @return 是否为空 */ public static boolean isEmpty(String str) { @@ -144,7 +152,8 @@ public class StrUtils { * 1、不为null
    * 2、不为""
    * - * @param str 被检测的字符串 + * @param str + * 被检测的字符串 * @return 是否为非空 */ public static boolean isNotEmpty(String str) { @@ -154,7 +163,8 @@ public class StrUtils { /** * 当给定字符串为null时,转换为Empty * - * @param str 被转换的字符串 + * @param str + * 被转换的字符串 * @return 转换后的字符串 */ public static String nullToEmpty(String str) { @@ -171,8 +181,10 @@ public class StrUtils { * nullToDefault("bat", "default") = "bat" * * - * @param str 要转换的字符串 - * @param defaultStr 默认字符串 + * @param str + * 要转换的字符串 + * @param defaultStr + * 默认字符串 * * @return 字符串本身或指定的默认字符串 */ @@ -183,7 +195,8 @@ public class StrUtils { /** * 当给定字符串为空字符串时,转换为null * - * @param str 被转换的字符串 + * @param str + * 被转换的字符串 * @return 转换后的字符串 */ public static String emptyToNull(String str) { @@ -193,7 +206,8 @@ public class StrUtils { /** * 是否包含空字符串 * - * @param strs 字符串列表 + * @param strs + * 字符串列表 * @return 是否包含空字符串 */ public static boolean hasEmpty(String... strs) { @@ -212,7 +226,8 @@ public class StrUtils { /** * 是否全部为空字符串 * - * @param strs 字符串列表 + * @param strs + * 字符串列表 * @return 是否全部为空字符串 */ public static boolean isAllEmpty(String... strs) { @@ -228,12 +243,14 @@ public class StrUtils { return true; } - // ------------------------------------------------------------------------ Trim + // ------------------------------------------------------------------------ + // Trim /** * 除去字符串头尾部的空白,如果字符串是null,依然返回null。 * *

    - * 注意,和String.trim不同,此方法使用Character.isWhitespace 来判定空白, 因而可以除去英文字符集之外的其它空白,如中文空格。 + * 注意,和String.trim不同,此方法使用Character.isWhitespace + * 来判定空白, 因而可以除去英文字符集之外的其它空白,如中文空格。 * *

     	 * trim(null)          = null
    @@ -245,7 +262,8 @@ public class StrUtils {
     	 * 
     	 * 

    * - * @param str 要处理的字符串 + * @param str + * 要处理的字符串 * * @return 除去空白的字符串,如果原字串为null,则返回null */ @@ -256,7 +274,8 @@ public class StrUtils { /** * 给定字符串数组全部做去首尾空格 * - * @param strs 字符串数组 + * @param strs + * 字符串数组 */ public static void trim(String[] strs) { if (null == strs) { @@ -275,7 +294,8 @@ public class StrUtils { * 除去字符串头部的空白,如果字符串是null,则返回null。 * *

    - * 注意,和String.trim不同,此方法使用Character.isWhitespace 来判定空白, 因而可以除去英文字符集之外的其它空白,如中文空格。 + * 注意,和String.trim不同,此方法使用Character.isWhitespace + * 来判定空白, 因而可以除去英文字符集之外的其它空白,如中文空格。 * *

     	 * trimStart(null)         = null
    @@ -288,9 +308,11 @@ public class StrUtils {
     	 * 
     	 * 

    * - * @param str 要处理的字符串 + * @param str + * 要处理的字符串 * - * @return 除去空白的字符串,如果原字串为null或结果字符串为"",则返回 null + * @return 除去空白的字符串,如果原字串为null或结果字符串为"",则返回 + * null */ public static String trimStart(String str) { return trim(str, -1); @@ -300,7 +322,8 @@ public class StrUtils { * 除去字符串尾部的空白,如果字符串是null,则返回null。 * *

    - * 注意,和String.trim不同,此方法使用Character.isWhitespace 来判定空白, 因而可以除去英文字符集之外的其它空白,如中文空格。 + * 注意,和String.trim不同,此方法使用Character.isWhitespace + * 来判定空白, 因而可以除去英文字符集之外的其它空白,如中文空格。 * *

     	 * trimEnd(null)       = null
    @@ -313,9 +336,11 @@ public class StrUtils {
     	 * 
     	 * 

    * - * @param str 要处理的字符串 + * @param str + * 要处理的字符串 * - * @return 除去空白的字符串,如果原字串为null或结果字符串为"",则返回 null + * @return 除去空白的字符串,如果原字串为null或结果字符串为"",则返回 + * null */ public static String trimEnd(String str) { return trim(str, 1); @@ -324,8 +349,11 @@ public class StrUtils { /** * 除去字符串头尾部的空白符,如果字符串是null,依然返回null。 * - * @param str 要处理的字符串 - * @param mode -1表示trimStart,0表示trim全部, 1表示trimEnd + * @param str + * 要处理的字符串 + * @param mode + * -1表示trimStart,0表示trim全部, + * 1表示trimEnd * * @return 除去指定字符后的的字符串,如果原字串为null,则返回null */ @@ -358,46 +386,57 @@ public class StrUtils { return str; } - + /** * 是否以指定字符串开头 - * @param str 被监测字符串 - * @param prefix 开头字符串 - * @param isIgnoreCase 是否忽略大小写 + * + * @param str + * 被监测字符串 + * @param prefix + * 开头字符串 + * @param isIgnoreCase + * 是否忽略大小写 * @return 是否以指定字符串开头 */ - public static boolean startWith(String str, String prefix, boolean isIgnoreCase){ - if(isIgnoreCase){ + public static boolean startWith(String str, String prefix, boolean isIgnoreCase) { + if (isIgnoreCase) { return str.toLowerCase().startsWith(prefix.toLowerCase()); - }else{ + } else { return str.startsWith(prefix); } } - + /** * 是否以指定字符串结尾 - * @param str 被监测字符串 - * @param suffix 结尾字符串 - * @param isIgnoreCase 是否忽略大小写 + * + * @param str + * 被监测字符串 + * @param suffix + * 结尾字符串 + * @param isIgnoreCase + * 是否忽略大小写 * @return 是否以指定字符串结尾 */ - public static boolean endWith(String str, String suffix, boolean isIgnoreCase){ - if(isIgnoreCase){ + public static boolean endWith(String str, String suffix, boolean isIgnoreCase) { + if (isIgnoreCase) { return str.toLowerCase().endsWith(suffix.toLowerCase()); - }else{ + } else { return str.endsWith(suffix); } } - + /** * 是否包含特定字符,忽略大小写,如果给定两个参数都为null,返回true - * @param str 被检测字符串 - * @param testStr 被测试是否包含的字符串 + * + * @param str + * 被检测字符串 + * @param testStr + * 被测试是否包含的字符串 * @return 是否包含 */ - public static boolean containsIgnoreCase(String str, String testStr){ - if(null == str){ - //如果被监测字符串和 + public static boolean containsIgnoreCase(String str, String testStr) { + if (null == str) { + // 如果被监测字符串和 return null == testStr; } return str.toLowerCase().contains(testStr.toLowerCase()); @@ -421,7 +460,8 @@ public class StrUtils { * 生成set方法名
    * 例如:name 返回 setName * - * @param fieldName 属性名 + * @param fieldName + * 属性名 * @return setXxx */ public static String genSetter(String fieldName) { @@ -431,7 +471,8 @@ public class StrUtils { /** * 生成get方法名 * - * @param fieldName 属性名 + * @param fieldName + * 属性名 * @return getXxx */ public static String genGetter(String fieldName) { @@ -442,8 +483,10 @@ public class StrUtils { * 去掉首部指定长度的字符串并将剩余字符串首字母小写
    * 例如:str=setName, preLength=3 -> return name * - * @param str 被处理的字符串 - * @param preLength 去掉的长度 + * @param str + * 被处理的字符串 + * @param preLength + * 去掉的长度 * @return 处理后的字符串,不符合规范返回null */ public static String cutPreAndLowerFirst(String str, int preLength) { @@ -463,8 +506,10 @@ public class StrUtils { /** * 原字符串首字母大写并在其首部添加指定字符串 例如:str=name, preString=get -> return getName * - * @param str 被处理的字符串 - * @param preString 添加的首部 + * @param str + * 被处理的字符串 + * @param preString + * 添加的首部 * @return 处理后的字符串 */ public static String upperFirstAndAddPre(String str, String preString) { @@ -478,7 +523,8 @@ public class StrUtils { * 大写首字母
    * 例如:str = name, return Name * - * @param str 字符串 + * @param str + * 字符串 * @return 字符串 */ public static String upperFirst(String str) { @@ -489,11 +535,12 @@ public class StrUtils { * 小写首字母
    * 例如:str = Name, return name * - * @param str 字符串 + * @param str + * 字符串 * @return 字符串 */ public static String lowerFirst(String str) { - if(isBlank(str)){ + if (isBlank(str)) { return str; } return Character.toLowerCase(str.charAt(0)) + str.substring(1); @@ -502,15 +549,17 @@ public class StrUtils { /** * 去掉指定前缀 * - * @param str 字符串 - * @param prefix 前缀 + * @param str + * 字符串 + * @param prefix + * 前缀 * @return 切掉后的字符串,若前缀不是 preffix, 返回原字符串 */ public static String removePrefix(String str, String prefix) { - if(isEmpty(str) || isEmpty(prefix)){ + if (isEmpty(str) || isEmpty(prefix)) { return str; } - + if (str.startsWith(prefix)) { return str.substring(prefix.length()); } @@ -520,15 +569,17 @@ public class StrUtils { /** * 忽略大小写去掉指定前缀 * - * @param str 字符串 - * @param prefix 前缀 + * @param str + * 字符串 + * @param prefix + * 前缀 * @return 切掉后的字符串,若前缀不是 prefix, 返回原字符串 */ public static String removePrefixIgnoreCase(String str, String prefix) { - if(isEmpty(str) || isEmpty(prefix)){ + if (isEmpty(str) || isEmpty(prefix)) { return str; } - + if (str.toLowerCase().startsWith(prefix.toLowerCase())) { return str.substring(prefix.length()); } @@ -538,15 +589,17 @@ public class StrUtils { /** * 去掉指定后缀 * - * @param str 字符串 - * @param suffix 后缀 + * @param str + * 字符串 + * @param suffix + * 后缀 * @return 切掉后的字符串,若后缀不是 suffix, 返回原字符串 */ public static String removeSuffix(String str, String suffix) { - if(isEmpty(str) || isEmpty(suffix)){ + if (isEmpty(str) || isEmpty(suffix)) { return str; } - + if (str.endsWith(suffix)) { return str.substring(0, str.length() - suffix.length()); } @@ -556,48 +609,56 @@ public class StrUtils { /** * 忽略大小写去掉指定后缀 * - * @param str 字符串 - * @param suffix 后缀 + * @param str + * 字符串 + * @param suffix + * 后缀 * @return 切掉后的字符串,若后缀不是 suffix, 返回原字符串 */ public static String removeSuffixIgnoreCase(String str, String suffix) { - if(isEmpty(str) || isEmpty(suffix)){ + if (isEmpty(str) || isEmpty(suffix)) { return str; } - + if (str.toLowerCase().endsWith(suffix.toLowerCase())) { return str.substring(0, str.length() - suffix.length()); } return str; } - + /** * 如果给定字符串不是以prefix开头的,在开头补充 prefix - * @param str 字符串 - * @param prefix 前缀 + * + * @param str + * 字符串 + * @param prefix + * 前缀 * @return 补充后的字符串 */ - public static String addPrefixIfNot(String str, String prefix){ - if(isEmpty(str) || isEmpty(prefix)){ + public static String addPrefixIfNot(String str, String prefix) { + if (isEmpty(str) || isEmpty(prefix)) { return str; } - if(false == str.startsWith(prefix)){ + if (false == str.startsWith(prefix)) { str = prefix + str; } return str; } - + /** * 如果给定字符串不是以suffix结尾的,在尾部补充 suffix - * @param str 字符串 - * @param suffix 后缀 + * + * @param str + * 字符串 + * @param suffix + * 后缀 * @return 补充后的字符串 */ - public static String addSuffixIfNot(String str, String suffix){ - if(isEmpty(str) || isEmpty(suffix)){ + public static String addSuffixIfNot(String str, String suffix) { + if (isEmpty(str) || isEmpty(suffix)) { return str; } - if(false == str.endsWith(suffix)){ + if (false == str.endsWith(suffix)) { str += suffix; } return str; @@ -606,7 +667,8 @@ public class StrUtils { /** * 清理空白字符 * - * @param str 被清理的字符串 + * @param str + * 被清理的字符串 * @return 清理后的字符串 */ public static String cleanBlank(String str) { @@ -622,8 +684,10 @@ public class StrUtils { * a#b#c -> [a,b,c]
    * a##b#c -> [a,"",b,c] * - * @param str 被切分的字符串 - * @param separator 分隔符字符 + * @param str + * 被切分的字符串 + * @param separator + * 分隔符字符 * @return 切分后的集合 */ public static List split(String str, char separator) { @@ -633,9 +697,12 @@ public class StrUtils { /** * 切分字符串 * - * @param str 被切分的字符串 - * @param separator 分隔符字符 - * @param limit 限制分片数 + * @param str + * 被切分的字符串 + * @param separator + * 分隔符字符 + * @param limit + * 限制分片数 * @return 切分后的集合 */ public static List split(String str, char separator, int limit) { @@ -674,8 +741,10 @@ public class StrUtils { * 切分字符串
    * from jodd * - * @param str 被切分的字符串 - * @param delimiter 分隔符 + * @param str + * 被切分的字符串 + * @param delimiter + * 分隔符 * @return 字符串 */ public static String[] split(String str, String delimiter) { @@ -714,9 +783,12 @@ public class StrUtils { * index从0开始计算,最后一个字符为-1
    * 如果from和to位置一样,返回 "" example: abcdefgh 2 3 -> c abcdefgh 2 -3 -> cde * - * @param string String - * @param fromIndex 开始的index(包括) - * @param toIndex 结束的index(不包括) + * @param string + * String + * @param fromIndex + * 开始的index(包括) + * @param toIndex + * 结束的index(不包括) * @return 字串 */ public static String sub(String string, int fromIndex, int toIndex) { @@ -752,8 +824,10 @@ public class StrUtils { /** * 切割前部分 * - * @param string 字符串 - * @param toIndex 切割到的位置(不包括) + * @param string + * 字符串 + * @param toIndex + * 切割到的位置(不包括) * @return 切割后的字符串 */ public static String subPre(String string, int toIndex) { @@ -763,8 +837,10 @@ public class StrUtils { /** * 切割后部分 * - * @param string 字符串 - * @param fromIndex 切割开始的位置(包括) + * @param string + * 字符串 + * @param fromIndex + * 切割开始的位置(包括) * @return 切割后的字符串 */ public static String subSuf(String string, int fromIndex) { @@ -777,9 +853,12 @@ public class StrUtils { /** * 给定字符串是否被字符包围 * - * @param str 字符串 - * @param prefix 前缀 - * @param suffix 后缀 + * @param str + * 字符串 + * @param prefix + * 前缀 + * @param suffix + * 后缀 * @return 是否包围,空串不包围 */ public static boolean isSurround(String str, String prefix, String suffix) { @@ -796,9 +875,12 @@ public class StrUtils { /** * 给定字符串是否被字符包围 * - * @param str 字符串 - * @param prefix 前缀 - * @param suffix 后缀 + * @param str + * 字符串 + * @param prefix + * 前缀 + * @param suffix + * 后缀 * @return 是否包围,空串不包围 */ public static boolean isSurround(String str, char prefix, char suffix) { @@ -815,8 +897,10 @@ public class StrUtils { /** * 重复某个字符 * - * @param c 被重复的字符 - * @param count 重复的数目 + * @param c + * 被重复的字符 + * @param count + * 重复的数目 * @return 重复字符字符串 */ public static String repeat(char c, int count) { @@ -830,8 +914,10 @@ public class StrUtils { /** * 重复某个字符串 * - * @param str 被重复的字符 - * @param count 重复的数目 + * @param str + * 被重复的字符 + * @param count + * 重复的数目 * @return 重复字符字符串 */ public static String repeat(String str, int count) { @@ -865,8 +951,10 @@ public class StrUtils { * equals("abc", "ABC") = false *
    * - * @param str1 要比较的字符串1 - * @param str2 要比较的字符串2 + * @param str1 + * 要比较的字符串1 + * @param str2 + * 要比较的字符串2 * * @return 如果两个字符串相同,或者都是null,则返回true */ @@ -889,8 +977,10 @@ public class StrUtils { * equalsIgnoreCase("abc", "ABC") = true *
    * - * @param str1 要比较的字符串1 - * @param str2 要比较的字符串2 + * @param str1 + * 要比较的字符串1 + * @param str2 + * 要比较的字符串2 * * @return 如果两个字符串相同,或者都是null,则返回true */ @@ -904,10 +994,12 @@ public class StrUtils { /** * 格式化文本, {} 表示占位符
    - * 例如:format("aaa {} ccc", "bbb") ----> aaa bbb ccc + * 例如:format("aaa {} ccc", "bbb") ----> aaa bbb ccc * - * @param template 文本模板,被替换的部分用 {} 表示 - * @param values 参数值 + * @param template + * 文本模板,被替换的部分用 {} 表示 + * @param values + * 参数值 * @return 格式化后的文本 */ public static String format(String template, Object... values) { @@ -945,11 +1037,13 @@ public class StrUtils { /** * 格式化文本,使用 {varName} 占位
    - * map = {a: "aValue", b: "bValue"} - * format("{a} and {b}", map) ----> aValue and bValue + * map = {a: "aValue", b: "bValue"} format("{a} and {b}", map) ----> aValue + * and bValue * - * @param template 文本模板,被替换的部分用 {key} 表示 - * @param map 参数值对 + * @param template + * 文本模板,被替换的部分用 {key} 表示 + * @param map + * 参数值对 * @return 格式化后的文本 */ public static String format(String template, Map map) { @@ -962,12 +1056,14 @@ public class StrUtils { } return template; } - + /** * 编码字符串 * - * @param str 字符串 - * @param charset 字符集,如果此字段为空,则解码的结果取决于平台 + * @param str + * 字符串 + * @param charset + * 字符集,如果此字段为空,则解码的结果取决于平台 * @return 编码后的字节码 */ public static byte[] bytes(String str, String charset) { @@ -977,8 +1073,10 @@ public class StrUtils { /** * 编码字符串 * - * @param str 字符串 - * @param charset 字符集,如果此字段为空,则解码的结果取决于平台 + * @param str + * 字符串 + * @param charset + * 字符集,如果此字段为空,则解码的结果取决于平台 * @return 编码后的字节码 */ public static byte[] bytes(String str, Charset charset) { @@ -991,64 +1089,68 @@ public class StrUtils { } return str.getBytes(charset); } - + /** * 将对象转为字符串
    - * 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 - * 2、对象数组会调用Arrays.toString方法 + * 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法 * - * @param obj 对象 + * @param obj + * 对象 * @return 字符串 */ - public static String utf8Str(Object obj){ + public static String utf8Str(Object obj) { return str(obj, CharsetUtils.CHARSET_UTF_8); } - + /** * 将对象转为字符串
    - * 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 - * 2、对象数组会调用Arrays.toString方法 + * 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法 * - * @param obj 对象 - * @param charsetName 字符集 + * @param obj + * 对象 + * @param charsetName + * 字符集 * @return 字符串 */ - public static String str(Object obj, String charsetName){ + public static String str(Object obj, String charsetName) { return str(obj, Charset.forName(charsetName)); } - + /** * 将对象转为字符串
    - * 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 - * 2、对象数组会调用Arrays.toString方法 + * 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法 * - * @param obj 对象 - * @param charset 字符集 + * @param obj + * 对象 + * @param charset + * 字符集 * @return 字符串 */ - public static String str(Object obj, Charset charset){ - if(null == obj){ + public static String str(Object obj, Charset charset) { + if (null == obj) { return null; } - - if(obj instanceof String) { - return (String)obj; - }else if(obj instanceof byte[] || obj instanceof Byte[]){ - return str((Byte[])obj, charset); - }else if(obj instanceof ByteBuffer){ - return str((ByteBuffer)obj, charset); - }else if(CollectionUtils.isArray(obj)){ + + if (obj instanceof String) { + return (String) obj; + } else if (obj instanceof byte[] || obj instanceof Byte[]) { + return str((Byte[]) obj, charset); + } else if (obj instanceof ByteBuffer) { + return str((ByteBuffer) obj, charset); + } else if (CollectionUtils.isArray(obj)) { return CollectionUtils.toString(obj); } - + return obj.toString(); } - + /** * 将byte数组转为字符串 * - * @param bytes byte数组 - * @param charset 字符集 + * @param bytes + * byte数组 + * @param charset + * 字符集 * @return 字符串 */ public static String str(byte[] bytes, String charset) { @@ -1058,8 +1160,10 @@ public class StrUtils { /** * 解码字节码 * - * @param data 字符串 - * @param charset 字符集,如果此字段为空,则解码的结果取决于平台 + * @param data + * 字符串 + * @param charset + * 字符集,如果此字段为空,则解码的结果取决于平台 * @return 解码后的字符串 */ public static String str(byte[] data, Charset charset) { @@ -1072,38 +1176,47 @@ public class StrUtils { } return new String(data, charset); } - + /** * 将编码的byteBuffer数据转换为字符串 - * @param data 数据 - * @param charset 字符集,如果为空使用当前系统字符集 + * + * @param data + * 数据 + * @param charset + * 字符集,如果为空使用当前系统字符集 * @return 字符串 */ - public static String str(ByteBuffer data, String charset){ - if(data == null) { + public static String str(ByteBuffer data, String charset) { + if (data == null) { return null; } - + return str(data, Charset.forName(charset)); } - + /** * 将编码的byteBuffer数据转换为字符串 - * @param data 数据 - * @param charset 字符集,如果为空使用当前系统字符集 + * + * @param data + * 数据 + * @param charset + * 字符集,如果为空使用当前系统字符集 * @return 字符串 */ - public static String str(ByteBuffer data, Charset charset){ - if(null == charset) { + public static String str(ByteBuffer data, Charset charset) { + if (null == charset) { charset = Charset.defaultCharset(); } return charset.decode(data).toString(); } - + /** * 字符串转换为byteBuffer - * @param str 字符串 - * @param charset 编码 + * + * @param str + * 字符串 + * @param charset + * 编码 * @return byteBuffer */ public static ByteBuffer byteBuffer(String str, String charset) { @@ -1113,8 +1226,10 @@ public class StrUtils { /** * 以 conjunction 为分隔符将多个对象转换为字符串 * - * @param conjunction 分隔符 - * @param objs 数组 + * @param conjunction + * 分隔符 + * @param objs + * 数组 * @return 连接后的字符串 */ public static String join(String conjunction, Object... objs) { @@ -1130,12 +1245,13 @@ public class StrUtils { } return sb.toString(); } - + /** * 将驼峰式命名的字符串转换为下划线方式。如果转换前的驼峰式命名的字符串为空,则返回空字符串。
    * 例如:HelloWorld->hello_world * - * @param camelCaseStr 转换前的驼峰式命名的字符串 + * @param camelCaseStr + * 转换前的驼峰式命名的字符串 * @return 转换后下划线大写方式命名的字符串 */ public static String toUnderlineCase(String camelCaseStr) { @@ -1155,7 +1271,8 @@ public class StrUtils { } if (Character.isUpperCase(c)) { if (!isPreUpperCase || !isNextUpperCase) { - if (i > 0) sb.append(UNDERLINE); + if (i > 0) + sb.append(UNDERLINE); } isPreUpperCase = true; } else { @@ -1170,7 +1287,8 @@ public class StrUtils { * 将下划线方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。
    * 例如:hello_world->HelloWorld * - * @param name 转换前的下划线大写方式命名的字符串 + * @param name + * 转换前的下划线大写方式命名的字符串 * @return 转换后的驼峰式命名的字符串 */ public static String toCamelCase(String name) { @@ -1202,9 +1320,12 @@ public class StrUtils { /** * 包装指定字符串 * - * @param str 被包装的字符串 - * @param prefix 前缀 - * @param suffix 后缀 + * @param str + * 被包装的字符串 + * @param prefix + * 前缀 + * @param suffix + * 后缀 * @return 包装后的字符串 */ public static String wrap(String str, String prefix, String suffix) { @@ -1214,9 +1335,12 @@ public class StrUtils { /** * 指定字符串是否被包装 * - * @param str 字符串 - * @param prefix 前缀 - * @param suffix 后缀 + * @param str + * 字符串 + * @param prefix + * 前缀 + * @param suffix + * 后缀 * @return 是否被包装 */ public static boolean isWrap(String str, String prefix, String suffix) { @@ -1226,8 +1350,10 @@ public class StrUtils { /** * 指定字符串是否被同一字符包装(前后都有这些字符串) * - * @param str 字符串 - * @param wrapper 包装字符串 + * @param str + * 字符串 + * @param wrapper + * 包装字符串 * @return 是否被包装 */ public static boolean isWrap(String str, String wrapper) { @@ -1237,8 +1363,10 @@ public class StrUtils { /** * 指定字符串是否被同一字符包装(前后都有这些字符串) * - * @param str 字符串 - * @param wrapper 包装字符 + * @param str + * 字符串 + * @param wrapper + * 包装字符 * @return 是否被包装 */ public static boolean isWrap(String str, char wrapper) { @@ -1248,9 +1376,12 @@ public class StrUtils { /** * 指定字符串是否被包装 * - * @param str 字符串 - * @param prefixChar 前缀 - * @param suffixChar 后缀 + * @param str + * 字符串 + * @param prefixChar + * 前缀 + * @param suffixChar + * 后缀 * @return 是否被包装 */ public static boolean isWrap(String str, char prefixChar, char suffixChar) { @@ -1260,9 +1391,12 @@ public class StrUtils { /** * 补充字符串以满足最小长度 StrUtil.padPre("1", 3, '0');//"001" * - * @param str 字符串 - * @param minLength 最小长度 - * @param padChar 补充的字符 + * @param str + * 字符串 + * @param minLength + * 最小长度 + * @param padChar + * 补充的字符 * @return 补充后的字符串 */ public static String padPre(String str, int minLength, char padChar) { @@ -1280,9 +1414,12 @@ public class StrUtils { /** * 补充字符串以满足最小长度 StrUtil.padEnd("1", 3, '0');//"100" * - * @param str 字符串 - * @param minLength 最小长度 - * @param padChar 补充的字符 + * @param str + * 字符串 + * @param minLength + * 最小长度 + * @param padChar + * 补充的字符 * @return 补充后的字符串 */ public static String padEnd(String str, int minLength, char padChar) { @@ -1331,7 +1468,8 @@ public class StrUtils { /** * 获得StringReader * - * @param str 字符串 + * @param str + * 字符串 * @return StringReader */ public static StringReader getReader(String str) { @@ -1348,4 +1486,3 @@ public class StrUtils { } } - diff --git a/core.sdk/src/main/java/com/lyms/util/remote/HttpRemote.java b/core.sdk/src/main/java/com/lyms/util/remote/HttpRemote.java index 582462b..00e9571 100644 --- a/core.sdk/src/main/java/com/lyms/util/remote/HttpRemote.java +++ b/core.sdk/src/main/java/com/lyms/util/remote/HttpRemote.java @@ -11,7 +11,7 @@ import org.apache.http.client.methods.HttpPost; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.entity.SerializableEntity; -import com.lyms.synch.entity.SyncnModel; +import com.lyms.synch.entity.ChannelData; /** * http,https 远程调用 @@ -28,35 +28,25 @@ public class HttpRemote extends AbsRemote { return new HttpRemote(); } - public String post(SyncnModel model) { - if (model == null) + public String post(ChannelData data) { + if (data == null) return null; - String url = model.getRemote(); + String url = data.getRemote(); HttpClientContext httpContext = HttpClientContext.create(); HttpPost post = new HttpPost(url); HttpEntity entity = null; CloseableHttpResponse response = null; try { - - // ContentType content = - // ContentType.create(MimeTypeUtils.TEXT_PLAIN_VALUE, - // CharsetUtils.UTF_8); - - // entity = new StringEntity(JsonUtils.beanToJson(model), content); - - entity = new SerializableEntity(model); - // post.setHeader("Content-Type", "text/plain; charset=utf-8"); + entity = new SerializableEntity(data); post.setEntity(entity); response = httpclient.execute(post, httpContext); entity = response.getEntity(); httpContext.getCookieStore().clear(); return responseUTF8(entity); - } catch (ClientProtocolException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); + } catch (Exception e) { + LOG.error("连接错误: " + e); } finally { try { if (response != null) { diff --git a/hospital.web/src/main/java/com/lyms/hospital/controller/LoginController.java b/hospital.web/src/main/java/com/lyms/hospital/controller/LoginController.java index 5f9ceb2..eb97a5d 100644 --- a/hospital.web/src/main/java/com/lyms/hospital/controller/LoginController.java +++ b/hospital.web/src/main/java/com/lyms/hospital/controller/LoginController.java @@ -5,7 +5,6 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.lyms.web.controller.BaseController; -import com.mysql.fabric.xmlrpc.base.Data; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; @@ -13,18 +12,16 @@ import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; @RestController -@RequestMapping(value="/login",method=RequestMethod.POST) +@RequestMapping(value = "/login") @Api(value = "/api", description = "登录的相关操作") public class LoginController extends BaseController { - @ApiOperation(value = "测试登录", notes = "测试登录说明") - @ApiImplicitParams({ - @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long"), - @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User") - }) - @RequestMapping(value="/testLogin",method=RequestMethod.GET) - public String testLogin(){ - request.getSession().setAttribute("abc", "123"); + @ApiOperation(value = "测试登录", notes = "测试登录说明") + @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long"), + @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User") }) + @RequestMapping(value = "/testLogin", method = RequestMethod.GET) + public String testLogin() { + // request.getSession().setAttribute("abc", "123"); return "abc"; } } diff --git a/hospital.web/src/main/java/com/lyms/hospital/controller/RouterController.java b/hospital.web/src/main/java/com/lyms/hospital/controller/RouterController.java new file mode 100644 index 0000000..16155f0 --- /dev/null +++ b/hospital.web/src/main/java/com/lyms/hospital/controller/RouterController.java @@ -0,0 +1,43 @@ +package com.lyms.hospital.controller; + +import java.io.IOException; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.lyms.synch.ParamsHandler; +import com.lyms.synch.SycnHandler; +import com.lyms.synch.SyncUtils; +import com.lyms.synch.entity.ChannelData; +import com.lyms.web.controller.BaseController; + +/** + *
  • @ClassName: RouterController + *
  • @Description: 远程接口调用数据处理分发 + *
  • @author maliang + *
  • @date 2017年3月14日 + *
  • + */ +@RestController +@RequestMapping("/remote") +public class RouterController extends BaseController { + + @RequestMapping(value = "/sycn", produces = { MediaType.APPLICATION_JSON_VALUE }) + public Object remote(HttpServletRequest request) throws ClassNotFoundException, IOException { + ChannelData data = SyncUtils.conver(request); + System.out.println("接受到数据: " + ToStringBuilder.reflectionToString(data)); + Object handResult = SycnHandler.handler(data); + if (data.getLoop()) { + data = (ChannelData) handResult; + } else { + data.setData(ParamsHandler.builder().push(handResult).toJsonString()); + } + data.setAck(true); + return data; + } + +} diff --git a/hospital.web/src/main/java/com/lyms/hospital/dao/sys/SyncDataBasicMapper.java b/hospital.web/src/main/java/com/lyms/hospital/dao/sys/SyncDataBasicMapper.java new file mode 100644 index 0000000..970e354 --- /dev/null +++ b/hospital.web/src/main/java/com/lyms/hospital/dao/sys/SyncDataBasicMapper.java @@ -0,0 +1,35 @@ +package com.lyms.hospital.dao.sys; + +import java.io.Serializable; +import java.util.List; + +import org.springframework.stereotype.Repository; + +import com.baomidou.mybatisplus.mapper.BaseMapper; +import com.lyms.hospital.entity.sys.SyncDataBasic; + +/** + *

    + * Mapper接口 + *

    + * + * @author maliang + * @since 2017-03-15 + */ +@Repository +public interface SyncDataBasicMapper extends BaseMapper { + + public Integer deleteLogicById(Serializable id); + + /** + *
  • @Description: 批量更新 + *
  • @param ids + *
  • @return + *
  • 创建人:maliang + *
  • 创建时间:2017年3月15日 + *
  • 修改人: + *
  • 修改时间: + */ + public Integer updateBatchByIds(List ids); + +} \ No newline at end of file diff --git a/hospital.web/src/main/java/com/lyms/hospital/dao/sys/SyncDataBasicMapper.xml b/hospital.web/src/main/java/com/lyms/hospital/dao/sys/SyncDataBasicMapper.xml new file mode 100644 index 0000000..afc5da5 --- /dev/null +++ b/hospital.web/src/main/java/com/lyms/hospital/dao/sys/SyncDataBasicMapper.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + ID AS id, DATA AS data, CREATE_TIME AS createTime, IFSUC AS ifsuc + + + + SYNC_DATA_BASIC + + + + + update from as sb set sb.ifsuc=1 + where sb.id in + + #{item} + + + + diff --git a/hospital.web/src/main/java/com/lyms/hospital/entity/sys/SyncDataBasic.java b/hospital.web/src/main/java/com/lyms/hospital/entity/sys/SyncDataBasic.java new file mode 100644 index 0000000..c2a8183 --- /dev/null +++ b/hospital.web/src/main/java/com/lyms/hospital/entity/sys/SyncDataBasic.java @@ -0,0 +1,78 @@ +package com.lyms.hospital.entity.sys; + +import java.io.Serializable; +import java.util.Date; + +import com.baomidou.mybatisplus.annotations.TableField; +import com.baomidou.mybatisplus.annotations.TableId; +import com.baomidou.mybatisplus.annotations.TableName; +import com.lyms.synch.entity.ChannelData; + +/** + * + *

    + * 用户、角色、权限、医院、部门等基础数据同步 + *

    + * + * @author maliang + * @since 2017-03-15 + */ +@TableName("SYNC_DATA_BASIC") +public class SyncDataBasic implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 该ID 一定要与data 中的ID一致 + */ + @TableId(value = "ID") + private String id; + /** + * 数据对象 {@link ChannelData} json 数据格式 + */ + @TableField(value = "DATA") + private String data; + /** + * 创建时间 + */ + @TableField(value = "CREATE_TIME") + private Date createTime; + /** + * 数据上传是否成功 + */ + @TableField(value = "IFSUC") + private Integer ifsuc; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } + + public Date getCreateTime() { + return createTime; + } + + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + public Integer getIfsuc() { + return ifsuc; + } + + public void setIfsuc(Integer ifsuc) { + this.ifsuc = ifsuc; + } + +} diff --git a/hospital.web/src/main/java/com/lyms/hospital/service/sys/SyncDataBasicService.java b/hospital.web/src/main/java/com/lyms/hospital/service/sys/SyncDataBasicService.java new file mode 100644 index 0000000..3766427 --- /dev/null +++ b/hospital.web/src/main/java/com/lyms/hospital/service/sys/SyncDataBasicService.java @@ -0,0 +1,50 @@ +package com.lyms.hospital.service.sys; + +import java.io.Serializable; +import java.util.List; + +import com.lyms.hospital.entity.sys.SyncDataBasic; +import com.lyms.synch.entity.ChannelData; +import com.lyms.web.service.BaseService; + +/** + *

    + * 数据同步模块 + *

    + * + * @author maliang + * @since 2017-03-15 + */ +public interface SyncDataBasicService extends BaseService { + + /** + *
  • @Description:逻辑删除,ifDel = 1 为删除,否则为没有删除 + *
  • @param id 删除主键id + *
  • @return 大于0修改成功,否则为失败 + */ + public Integer deleteLogicById(Serializable id); + + /** + *
  • @Description:更新同步成功的数据 + *
  • @param ids + *
  • @return + *
  • 创建人:maliang + *
  • 创建时间:2017年3月15日 + *
  • 修改人: + *
  • 修改时间: + */ + public Boolean updateBasic(List ids); + + /** + * 获取一条数据 + *
  • @Description:TODO(方法描述) + *
  • @return + *
  • 创建人:maliang + *
  • 创建时间:2017年3月15日 + *
  • 修改人: + *
  • 修改时间: + */ + public ChannelData selectOne(); + + public Boolean updateBasic(Serializable id); +} diff --git a/hospital.web/src/main/java/com/lyms/hospital/service/sys/impl/SyncDataBasicServiceImpl.java b/hospital.web/src/main/java/com/lyms/hospital/service/sys/impl/SyncDataBasicServiceImpl.java new file mode 100644 index 0000000..05344bb --- /dev/null +++ b/hospital.web/src/main/java/com/lyms/hospital/service/sys/impl/SyncDataBasicServiceImpl.java @@ -0,0 +1,67 @@ +package com.lyms.hospital.service.sys.impl; + +import java.io.Serializable; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.baomidou.mybatisplus.mapper.EntityWrapper; +import com.baomidou.mybatisplus.service.impl.ServiceImpl; +import com.lyms.hospital.dao.sys.SyncDataBasicMapper; +import com.lyms.hospital.entity.sys.SyncDataBasic; +import com.lyms.hospital.service.sys.SyncDataBasicService; +import com.lyms.synch.entity.ChannelData; +import com.lyms.util.JsonUtils; + +/** + *

    + * 用户、角色、权限、医院、部门等基础数据同步 服务实现类 + *

    + * + * @author maliang + * @since 2017-03-15 + */ +@Service +public class SyncDataBasicServiceImpl extends ServiceImpl + implements SyncDataBasicService { + + @Autowired + private SyncDataBasicMapper basicMapper; + + public Integer deleteLogicById(Serializable id) { + return baseMapper.deleteLogicById(id); + } + + @Override + @Transactional + public Boolean updateBasic(List ids) { + Integer tag = basicMapper.updateBatchByIds(ids); + return tag >= 1 ? Boolean.TRUE : Boolean.FALSE; + } + + @Override + public Boolean updateBasic(Serializable id) { + SyncDataBasic dataBasic = baseMapper.selectById(id); + dataBasic.setIfsuc(1); + Integer tag = baseMapper.updateById(dataBasic); + return tag >= 1; + } + + @Override + public ChannelData selectOne() { + EntityWrapper ew = new EntityWrapper(); + ew.where("ifsuc=0"); + List datas = baseMapper.selectList(ew); + + // 单条同步,避免过于复杂的消息回执 + SyncDataBasic basic = datas != null && datas.size() > 0 ? datas.get(0) : null; + if (basic != null) { + ChannelData data = JsonUtils.jsonToBean(basic.getData(), ChannelData.class); + return data; + } + return ChannelData.emtpy(); + } + +} diff --git a/hospital.web/src/main/resources/app-context.xml b/hospital.web/src/main/resources/app-context.xml index d102a45..43624fa 100644 --- a/hospital.web/src/main/resources/app-context.xml +++ b/hospital.web/src/main/resources/app-context.xml @@ -23,7 +23,7 @@ - + diff --git a/mybatis-plus/src/test/java/com/baomidou/mybatisplus/test/generator/MysqlGenerator.java b/mybatis-plus/src/test/java/com/baomidou/mybatisplus/test/generator/MysqlGenerator.java index 8f47441..6a02179 100644 --- a/mybatis-plus/src/test/java/com/baomidou/mybatisplus/test/generator/MysqlGenerator.java +++ b/mybatis-plus/src/test/java/com/baomidou/mybatisplus/test/generator/MysqlGenerator.java @@ -45,7 +45,7 @@ public class MysqlGenerator { gc.setAuthor("maliang"); // strategy.setInclude(new String[] { // "SYS_USERS","SYS_USER_ROLE_MAPS","SYS_ROLES" }); // 需要生成的表 - strategy.setInclude(new String[] { "SYS_ORGAN_GROUP" }); // 需要生成的表 + strategy.setInclude(new String[] { "SYNC_DATA_BASIC" }); // 需要生成的表 // pc.setParent("com.lyms.hospital"); pc.setParent("com.lyms.cm"); @@ -100,9 +100,9 @@ public class MysqlGenerator { DataSourceConfig dsc = new DataSourceConfig(); dsc.setDbType(DbType.MYSQL); dsc.setDriverName("com.mysql.jdbc.Driver"); - dsc.setUsername("center"); + dsc.setUsername("hospital"); dsc.setPassword("lyms2015"); - dsc.setUrl("jdbc:mysql://119.90.57.26:3306/center?characterEncoding=utf8"); + dsc.setUrl("jdbc:mysql://119.90.57.26:3306/hospital?characterEncoding=utf8"); mpg.setDataSource(dsc); // 策略配置