first commit

This commit is contained in:
=
2025-03-14 10:29:20 +08:00
commit ac92981557
3616 changed files with 907328 additions and 0 deletions
+991
View File
@@ -0,0 +1,991 @@
package io.v.nutz;
import io.v.nutz.sys.models.*;
import io.v.nutz.zhgh.proposal.models.ProposalUndertake;
import io.v.nutz.sys.services.SysTaskService;
import io.v.nutz.task.services.TaskPlatformService;
import io.v.nutz.web.commons.base.Globals;
import io.v.nutz.web.commons.ext.pubsub.WebPubSub;
import io.v.nutz.web.commons.filter.CsrfFilter;
import io.v.nutz.web.commons.filter.SsrfFilter;
import org.apache.commons.net.ftp.FTPClient;
import org.beetl.core.GroupTemplate;
import org.nutz.boot.NbApp;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.impl.FileSqlManager;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.util.Daos;
import org.nutz.integration.jedis.JedisAgent;
import org.nutz.integration.shiro.ShiroSessionProvider;
import org.nutz.ioc.Ioc;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Mirror;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.annotation.*;
import org.quartz.Scheduler;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.servlet.ServletContext;
import java.lang.management.ManagementFactory;
import java.sql.Driver;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.stream.Collectors;
import static org.nutz.boot.starter.ftp.FtpStarter.*;
/**
* @author wizzer@qq.com
*/
@IocBean(create = "init", depose = "depose")
@Localization(value = "locales/", defaultLocalizationKey = "zh_CN")
@Encoding(input = "UTF-8", output = "UTF-8")
@ChainBy(args = "chain/mvc-chain.json")
@SessionBy(ShiroSessionProvider.class)
@IocBy(args = {
"*io.v.nutz.base.aop.ViReturnAopLoader",
})
@Filters(value = {@By(type = CsrfFilter.class), @By(type = SsrfFilter.class)})
public class MainLauncher {
private static final Log log = Logs.get();
@Inject("refer:$ioc")
private Ioc ioc;
@Inject
private PropertiesProxy conf;
@Inject
private JedisAgent jedisAgent;
@Inject
private WebPubSub webPubSub;//注入一下为了初始化
@Inject
private GroupTemplate groupTemplate;
@Inject
private TaskPlatformService taskPlatformService;
@Inject
private SysTaskService sysTaskService;
@Inject
private Dao dao;
public static void main(String[] args) throws Exception {
NbApp nb = new NbApp().setArgs(args).setPrintProcDoc(true);
nb.getAppContext().setMainPackage("io.v");
nb.run();
}
public static NbApp warMain(ServletContext sc) {
NbApp nb = new NbApp().setPrintProcDoc(true);
nb.getAppContext().setMainPackage("io.v");
return nb;
}
public void init() {
Mvcs.DISABLE_X_POWERED_BY = true;
Globals.AppBase = Mvcs.getServletContext().getContextPath();
Globals.AppRoot = Mvcs.getServletContext().getRealPath("/");
init_sys();
init_task();
init_proposal_undertake();
ioc.get(Globals.class);
}
/**
* 初始化承办单位表
*/
private void init_proposal_undertake() {
int count = dao.count(ProposalUndertake.class, Cnd.NEW());
if (count == 0) {
List<Sys_unit> units = dao.query(Sys_unit.class, Cnd.where("unitlevel", "=", 2).and("parentId", "IS NOT", null));
List<ProposalUndertake> proposalUnderTakes = units.stream().map(v -> {
ProposalUndertake proposalUndertake = new ProposalUndertake();
proposalUndertake.setUnitCode(v.getUnitcode());
proposalUndertake.setUnitName(v.getName());
proposalUndertake.setIsEnable(true);
return proposalUndertake;
}).collect(Collectors.toList());
dao.insert(proposalUnderTakes);
}
}
private void init_task() {
if (!dao.exists("sys_qrtz_triggers")) {
//执行Quartz SQL脚本
String dbType = dao.getJdbcExpert().getDatabaseType();
log.debug("dbType:::" + dbType);
FileSqlManager fmq = new FileSqlManager("quartz/" + dbType.toLowerCase() + ".sql");
List<Sql> sqlListq = fmq.createCombo(fmq.keys());
Sql[] sqlsq = sqlListq.toArray(new Sql[sqlListq.size()]);
for (Sql sql : sqlsq) {
dao.execute(sql);
}
}
if (0 == sysTaskService.count()) {
//定时任务示例
Sys_task task = new Sys_task();
task.setDisabled(true);
task.setName("测试任务");
task.setJobClass("io.v.nutz.task.job.TestJob");
task.setCron("*/5 * * * * ?");
task.setData("{\"hi\":\"Wechat:wizzer | send red packets of support,thank u\"}");
task.setNote("微信号:wizzer | 欢迎发送红包以示支持,多谢。。");
sysTaskService.insert(task);
}
}
private void init_sys() {
//通过POJO类创建表结构
try {
Daos.createTablesInPackage(dao, "io.v", false);
//通过POJO类修改表结构
Daos.migration(dao, "io.v", true, false);
} catch (Exception e) {
e.printStackTrace();
}
// 若必要的数据表不存在,则初始化数据库
if (0 == dao.count(Sys_user.class)) {
//初始化配置表
Sys_config conf = new Sys_config();
conf.setConfigKey("AppName");
conf.setConfigValue("BudWk-V5 mini");
conf.setNote("系统名称");
dao.insert(conf);
conf = new Sys_config();
conf.setConfigKey("AppShrotName");
conf.setConfigValue("budwk");
conf.setNote("系统短名称");
dao.insert(conf);
conf = new Sys_config();
conf.setConfigKey("AppDomain");
conf.setConfigValue("http://127.0.0.1:8080");
conf.setNote("系统域名");
dao.insert(conf);
conf = new Sys_config();
conf.setConfigKey("AppFileDomain");
conf.setConfigValue("");
conf.setNote("文件访问域名");
dao.insert(conf);
conf = new Sys_config();
conf.setConfigKey("AppUploadBase");
conf.setConfigValue("/upload");
conf.setNote("文件访问路径");
dao.insert(conf);
conf = new Sys_config();
conf.setConfigKey("SessionOnlyOne");
conf.setConfigValue("true");
conf.setNote("用户登录只允许一个Session实例(为true时退出登录会更新sys_user表在线状态)");
dao.insert(conf);
conf = new Sys_config();
conf.setConfigKey("WebNotification");
conf.setConfigValue("false");
conf.setNote("启用浏览器通知");
dao.insert(conf);
//初始化单位
Sys_unit unit = new Sys_unit();
unit.setPath("0001");
unit.setName("系统管理");
unit.setAliasName("System");
unit.setUnitcode("system");
unit.setLocation(0);
unit.setAddress("银河-太阳系-地球");
unit.setEmail("wizzer@qq.com");
unit.setTelephone("");
unit.setHasChildren(false);
unit.setParentId("");
unit.setWebsite("https://budwk.com");
Sys_unit dbunit = dao.insert(unit);
//初始化菜单
List<Sys_menu> menuList = new ArrayList<Sys_menu>();
Sys_menu menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001");
menu.setName("系统");
menu.setNote("系统");
menu.setAliasName("System");
menu.setIcon("ti-settings");
menu.setLocation(0);
menu.setHref("");
menu.setTarget("");
menu.setShowit(true);
menu.setHasChildren(true);
menu.setParentId("");
menu.setType("menu");
menu.setPermission("sys");
Sys_menu m0 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("00010001");
menu.setName("系统管理");
menu.setNote("系统管理");
menu.setAliasName("Manager");
menu.setIcon("ti-settings");
menu.setLocation(1);
menu.setHref("");
menu.setTarget("");
menu.setShowit(true);
menu.setHasChildren(true);
menu.setParentId(m0.getId());
menu.setType("menu");
menu.setPermission("sys.manager");
Sys_menu m1 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("000100010001");
menu.setName("单位管理");
menu.setAliasName("Unit");
menu.setLocation(0);
menu.setHref("/platform/sys/unit");
menu.setTarget("data-pjax");
menu.setShowit(true);
menu.setPermission("sys.manager.unit");
menu.setParentId(m1.getId());
menu.setType("menu");
Sys_menu m2 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000100010001");
menu.setName("添加单位");
menu.setAliasName("Add");
menu.setLocation(0);
menu.setShowit(false);
menu.setPermission("sys.manager.unit.add");
menu.setParentId(m2.getId());
menu.setType("data");
Sys_menu m21 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000100010002");
menu.setName("修改单位");
menu.setAliasName("Edit");
menu.setLocation(0);
menu.setShowit(false);
menu.setPermission("sys.manager.unit.edit");
menu.setParentId(m2.getId());
menu.setType("data");
Sys_menu m22 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000100010003");
menu.setName("删除单位");
menu.setAliasName("Delete");
menu.setLocation(0);
menu.setShowit(false);
menu.setPermission("sys.manager.unit.delete");
menu.setParentId(m2.getId());
menu.setType("data");
Sys_menu m23 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("000100010002");
menu.setName("用户管理");
menu.setAliasName("User");
menu.setLocation(0);
menu.setHref("/platform/sys/user");
menu.setTarget("data-pjax");
menu.setShowit(true);
menu.setPermission("sys.manager.user");
menu.setHasChildren(false);
menu.setParentId(m1.getId());
menu.setType("menu");
Sys_menu m3 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000100020001");
menu.setName("添加用户");
menu.setAliasName("Add");
menu.setLocation(0);
menu.setShowit(false);
menu.setPermission("sys.manager.user.add");
menu.setParentId(m3.getId());
menu.setType("data");
Sys_menu m31 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000100020002");
menu.setName("修改用户");
menu.setAliasName("Edit");
menu.setLocation(1);
menu.setShowit(false);
menu.setPermission("sys.manager.user.edit");
menu.setParentId(m3.getId());
menu.setType("data");
Sys_menu m32 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000100020003");
menu.setName("删除用户");
menu.setAliasName("Delete");
menu.setLocation(2);
menu.setShowit(false);
menu.setPermission("sys.manager.user.delete");
menu.setParentId(m3.getId());
menu.setType("data");
Sys_menu m33 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("000100010003");
menu.setName("角色管理");
menu.setAliasName("Role");
menu.setLocation(0);
menu.setHref("/platform/sys/role");
menu.setShowit(true);
menu.setPermission("sys.manager.role");
menu.setTarget("data-pjax");
menu.setParentId(m1.getId());
menu.setType("menu");
Sys_menu m4 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000100030001");
menu.setName("添加角色");
menu.setAliasName("Add");
menu.setLocation(1);
menu.setShowit(false);
menu.setPermission("sys.manager.role.add");
menu.setParentId(m4.getId());
menu.setType("data");
Sys_menu m41 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000100030002");
menu.setName("修改角色");
menu.setAliasName("Edit");
menu.setLocation(2);
menu.setShowit(false);
menu.setPermission("sys.manager.role.edit");
menu.setParentId(m4.getId());
menu.setType("data");
Sys_menu m42 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000100030003");
menu.setName("删除角色");
menu.setAliasName("Delete");
menu.setLocation(3);
menu.setShowit(false);
menu.setPermission("sys.manager.role.delete");
menu.setParentId(m4.getId());
menu.setType("data");
Sys_menu m43 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000100030004");
menu.setName("分配菜单");
menu.setAliasName("SetMenu");
menu.setLocation(4);
menu.setShowit(false);
menu.setPermission("sys.manager.role.menu");
menu.setParentId(m4.getId());
menu.setType("data");
Sys_menu m44 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000100030005");
menu.setName("分配用户");
menu.setAliasName("SetUser");
menu.setLocation(5);
menu.setShowit(false);
menu.setPermission("sys.manager.role.user");
menu.setParentId(m4.getId());
menu.setType("data");
Sys_menu m45 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("000100010004");
menu.setName("菜单管理");
menu.setAliasName("Menu");
menu.setLocation(0);
menu.setHref("/platform/sys/menu");
menu.setTarget("data-pjax");
menu.setShowit(true);
menu.setPermission("sys.manager.menu");
menu.setParentId(m1.getId());
menu.setType("menu");
Sys_menu m5 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000100040001");
menu.setName("添加菜单");
menu.setAliasName("Add");
menu.setLocation(1);
menu.setShowit(false);
menu.setPermission("sys.manager.menu.add");
menu.setParentId(m5.getId());
menu.setType("data");
Sys_menu m51 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000100040002");
menu.setName("修改菜单");
menu.setAliasName("Edit");
menu.setLocation(2);
menu.setShowit(false);
menu.setPermission("sys.manager.menu.edit");
menu.setParentId(m5.getId());
menu.setType("data");
Sys_menu m52 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000100040003");
menu.setName("删除菜单");
menu.setAliasName("Delete");
menu.setLocation(3);
menu.setShowit(false);
menu.setPermission("sys.manager.menu.delete");
menu.setParentId(m5.getId());
menu.setType("data");
Sys_menu m53 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("000100010005");
menu.setName("系统参数");
menu.setAliasName("Param");
menu.setLocation(0);
menu.setHref("/platform/sys/conf");
menu.setTarget("data-pjax");
menu.setShowit(true);
menu.setPermission("sys.manager.conf");
menu.setParentId(m1.getId());
menu.setType("menu");
Sys_menu m6 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000100050001");
menu.setName("添加参数");
menu.setAliasName("Add");
menu.setLocation(1);
menu.setShowit(false);
menu.setPermission("sys.manager.conf.add");
menu.setParentId(m6.getId());
menu.setType("data");
Sys_menu m61 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000100050002");
menu.setName("修改参数");
menu.setAliasName("Edit");
menu.setLocation(2);
menu.setShowit(false);
menu.setPermission("sys.manager.conf.edit");
menu.setParentId(m6.getId());
menu.setType("data");
Sys_menu m62 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000100050003");
menu.setName("删除参数");
menu.setAliasName("Delete");
menu.setLocation(3);
menu.setShowit(false);
menu.setPermission("sys.manager.conf.delete");
menu.setParentId(m6.getId());
menu.setType("data");
Sys_menu m63 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("000100010006");
menu.setName("日志管理");
menu.setAliasName("Log");
menu.setLocation(0);
menu.setHref("/platform/sys/log");
menu.setTarget("data-pjax");
menu.setShowit(true);
menu.setPermission("sys.manager.log");
menu.setParentId(m1.getId());
menu.setType("menu");
Sys_menu m7 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000100060001");
menu.setName("清除日志");
menu.setAliasName("Delete");
menu.setLocation(1);
menu.setShowit(false);
menu.setPermission("sys.manager.log.delete");
menu.setParentId(m7.getId());
menu.setType("data");
Sys_menu m71 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("000100010007");
menu.setName("定时任务");
menu.setAliasName("Task");
menu.setLocation(0);
menu.setHref("/platform/sys/task");
menu.setTarget("data-pjax");
menu.setShowit(true);
menu.setPermission("sys.manager.task");
menu.setParentId(m1.getId());
menu.setType("menu");
Sys_menu m8 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000100070001");
menu.setName("添加任务");
menu.setAliasName("Add");
menu.setLocation(1);
menu.setShowit(false);
menu.setPermission("sys.manager.task.add");
menu.setParentId(m8.getId());
menu.setType("data");
Sys_menu m81 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000100070002");
menu.setName("修改任务");
menu.setAliasName("Edit");
menu.setLocation(2);
menu.setShowit(false);
menu.setPermission("sys.manager.task.edit");
menu.setParentId(m8.getId());
menu.setType("data");
Sys_menu m82 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000100070003");
menu.setName("删除任务");
menu.setAliasName("Delete");
menu.setLocation(3);
menu.setShowit(false);
menu.setPermission("sys.manager.task.delete");
menu.setParentId(m8.getId());
menu.setType("data");
Sys_menu m83 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("000100010008");
menu.setName("自定义路由");
menu.setAliasName("Route");
menu.setLocation(0);
menu.setHref("/platform/sys/route");
menu.setTarget("data-pjax");
menu.setShowit(true);
menu.setPermission("sys.manager.route");
menu.setParentId(m1.getId());
menu.setType("menu");
Sys_menu m9 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000100080001");
menu.setName("添加路由");
menu.setAliasName("Add");
menu.setLocation(1);
menu.setShowit(false);
menu.setPermission("sys.manager.route.add");
menu.setParentId(m9.getId());
menu.setType("data");
Sys_menu m91 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000100080002");
menu.setName("修改路由");
menu.setAliasName("Edit");
menu.setLocation(2);
menu.setShowit(false);
menu.setPermission("sys.manager.route.edit");
menu.setParentId(m9.getId());
menu.setType("data");
Sys_menu m92 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000100080003");
menu.setName("删除路由");
menu.setAliasName("Delete");
menu.setLocation(3);
menu.setShowit(false);
menu.setPermission("sys.manager.route.delete");
menu.setParentId(m9.getId());
menu.setType("data");
Sys_menu m93 = dao.insert(menu);
menu = new Sys_menu();
menu.setParentId(m0.getId());
menu.setDisabled(false);
menu.setPath("00010002");
menu.setName("系统配置");
menu.setAliasName("Config");
menu.setType("menu");
menu.setLocation(2);
menu.setIcon("ti-pencil-alt");
menu.setShowit(true);
menu.setPermission("sys.config");
menu.setHasChildren(true);
Sys_menu pp1 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("000100020001");
menu.setName("数据字典");
menu.setAliasName("Dict");
menu.setLocation(0);
menu.setHref("/platform/sys/dict");
menu.setTarget("data-pjax");
menu.setShowit(true);
menu.setPermission("sys.manager.dict");
menu.setParentId(pp1.getId());
menu.setType("menu");
Sys_menu d = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000200010001");
menu.setName("添加字典");
menu.setAliasName("Add");
menu.setLocation(1);
menu.setShowit(false);
menu.setPermission("sys.manager.dict.add");
menu.setParentId(d.getId());
menu.setType("data");
Sys_menu d1 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000200010002");
menu.setName("修改字典");
menu.setAliasName("Edit");
menu.setLocation(2);
menu.setShowit(false);
menu.setPermission("sys.manager.dict.edit");
menu.setParentId(d.getId());
menu.setType("data");
Sys_menu d2 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000200010003");
menu.setName("删除字典");
menu.setAliasName("Delete");
menu.setLocation(3);
menu.setShowit(false);
menu.setPermission("sys.manager.dict.delete");
menu.setParentId(d.getId());
menu.setType("data");
Sys_menu d3 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("000100020002");
menu.setName("密钥管理");
menu.setAliasName("Api");
menu.setLocation(0);
menu.setHref("/platform/sys/api");
menu.setTarget("data-pjax");
menu.setShowit(true);
menu.setPermission("sys.manager.api");
menu.setParentId(pp1.getId());
menu.setType("menu");
Sys_menu appManger = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000200020001");
menu.setName("添加密钥");
menu.setAliasName("Add");
menu.setLocation(0);
menu.setShowit(false);
menu.setPermission("sys.manager.api.add");
menu.setParentId(appManger.getId());
menu.setType("data");
dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000200020002");
menu.setName("修改密钥");
menu.setAliasName("Edit");
menu.setLocation(1);
menu.setShowit(false);
menu.setPermission("sys.manager.api.edit");
menu.setParentId(appManger.getId());
menu.setType("data");
dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000200020003");
menu.setName("删除密钥");
menu.setAliasName("Delete");
menu.setLocation(2);
menu.setShowit(false);
menu.setPermission("sys.manager.api.delete");
menu.setParentId(appManger.getId());
menu.setType("data");
dao.insert(menu);
//消息中心及消息管理
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("00010003");
menu.setName("消息中心");
menu.setNote("消息中心");
menu.setAliasName("InnerMsg");
menu.setIcon("ti-bell");
menu.setLocation(0);
menu.setHref("");
menu.setTarget("");
menu.setShowit(true);
menu.setHasChildren(true);
menu.setParentId(m0.getId());
menu.setType("menu");
menu.setPermission("sys.msg");
Sys_menu msg0 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("000100030001");
menu.setName("全部消息");
menu.setAliasName("All");
menu.setLocation(0);
menu.setHref("/platform/sys/msg/user/all");
menu.setTarget("data-pjax");
menu.setShowit(true);
menu.setPermission("sys.msg.all");
menu.setParentId(msg0.getId());
menu.setType("menu");
dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("000100030002");
menu.setName("未读消息");
menu.setAliasName("Unread");
menu.setLocation(1);
menu.setHref("/platform/sys/msg/user/unread");
menu.setTarget("data-pjax");
menu.setShowit(true);
menu.setPermission("sys.msg.unread");
menu.setParentId(msg0.getId());
menu.setType("menu");
dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("000100030003");
menu.setName("已读消息");
menu.setAliasName("Read");
menu.setLocation(2);
menu.setHref("/platform/sys/msg/user/read");
menu.setTarget("data-pjax");
menu.setShowit(true);
menu.setPermission("sys.msg.read");
menu.setParentId(msg0.getId());
menu.setType("menu");
dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("000100010009");
menu.setName("消息管理");
menu.setAliasName("Msg");
menu.setLocation(0);
menu.setHref("/platform/sys/msg");
menu.setTarget("data-pjax");
menu.setShowit(true);
menu.setPermission("sys.manager.msg");
menu.setParentId(m1.getId());
menu.setType("menu");
Sys_menu msgManger = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000100090001");
menu.setName("添加消息");
menu.setAliasName("Add");
menu.setLocation(0);
menu.setShowit(false);
menu.setPermission("sys.manager.msg.add");
menu.setParentId(msgManger.getId());
menu.setType("data");
dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000100090002");
menu.setName("修改消息");
menu.setAliasName("Edit");
menu.setLocation(1);
menu.setShowit(false);
menu.setPermission("sys.manager.msg.edit");
menu.setParentId(msgManger.getId());
menu.setType("data");
dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000100090003");
menu.setName("删除消息");
menu.setAliasName("Delete");
menu.setLocation(2);
menu.setShowit(false);
menu.setPermission("sys.manager.msg.delete");
menu.setParentId(msgManger.getId());
menu.setType("data");
dao.insert(menu);
//运维中心
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("00010004");
menu.setName("运维中心");
menu.setNote("运维中心");
menu.setAliasName("Operation");
menu.setIcon("ti-shield");
menu.setLocation(0);
menu.setHref("");
menu.setTarget("");
menu.setShowit(true);
menu.setHasChildren(true);
menu.setParentId(m0.getId());
menu.setType("menu");
menu.setPermission("sys.operation");
Sys_menu op0 = dao.insert(menu);
//应用管理
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("000100040002");
menu.setName("应用管理");
menu.setAliasName("App");
menu.setLocation(0);
menu.setHref("/platform/sys/app");
menu.setTarget("data-pjax");
menu.setShowit(true);
menu.setPermission("sys.operation.app");
menu.setParentId(op0.getId());
menu.setType("menu");
Sys_menu op02 = dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000400020001");
menu.setName("配置文件管理");
menu.setAliasName("AppConfig");
menu.setLocation(1);
menu.setShowit(false);
menu.setPermission("sys.operation.app.conf");
menu.setParentId(op02.getId());
menu.setType("data");
dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000400020002");
menu.setName("Jar包管理");
menu.setAliasName("AppJar");
menu.setLocation(2);
menu.setShowit(false);
menu.setPermission("sys.operation.app.jar");
menu.setParentId(op02.getId());
menu.setType("data");
dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000400020003");
menu.setName("实例管理");
menu.setAliasName("AppInstance");
menu.setLocation(3);
menu.setShowit(false);
menu.setPermission("sys.operation.app.instance");
menu.setParentId(op02.getId());
menu.setType("data");
dao.insert(menu);
menu = new Sys_menu();
menu.setDisabled(false);
menu.setPath("0001000400020004");
menu.setName("修改日志等级");
menu.setAliasName("Loglevel");
menu.setLocation(4);
menu.setShowit(false);
menu.setPermission("sys.operation.app.loglevel");
menu.setParentId(op02.getId());
menu.setType("data");
dao.insert(menu);
//初始化角色
Sys_role role = new Sys_role();
role.setName("公共角色");
role.setCode("public");
role.setAliasName("Public");
role.setNote("All user has role");
role.setUnitid("");
role.setDisabled(false);
dao.insert(role);
role = new Sys_role();
role.setName("系统管理员");
role.setCode("sysadmin");
role.setAliasName("Sysadmin");
role.setNote("System Admin");
role.setUnitid("");
role.setMenus(menuList);
role.setDisabled(false);
Sys_role dbrole = dao.insert(role);
//初始化用户
Sys_user user = new Sys_user();
user.setId("43d2c4a34fc64f88acf2d95d2908d8ed");
user.setLoginname("superadmin");
user.setUsername("超级管理员");
user.setCreateAt(System.currentTimeMillis());
//String slat=R.UU32();
//new Sha256Hash("1",ByteSource.Util.bytes(s), 1024).toHex();
user.setSalt("r5tdr01s7uglfokpsdmtu15602");
user.setPassword("1bba9287ebc50b766bff84273d11ccefaa7a8da95d078960f05f116e9d970fb0");
user.setLoginIp("127.0.0.1");
user.setLoginAt(0L);
user.setLoginCount(0);
user.setEmail("wizzer@qq.com");
user.setLoginTheme("palette.3.css");
user.setLoginBoxed(false);
user.setLoginScroll(true);
user.setLoginSidebar(false);
user.setLoginPjax(true);
user.setUnitid(dbunit.getId());
Sys_user dbuser = dao.insert(user);
//不同的插入数据方式(安全)
dao.insert("sys_user_unit", org.nutz.dao.Chain.make("userId", dbuser.getId()).add("unitId", dbunit.getId()));
dao.insert("sys_user_role", Chain.make("userId", dbuser.getId()).add("roleId", dbrole.getId()));
//执行SQL脚本
FileSqlManager fm = new FileSqlManager("db/");
List<Sql> sqlList = fm.createCombo(fm.keys());
Sql[] sqls = sqlList.toArray(new Sql[sqlList.size()]);
for (Sql sql : sqls) {
dao.execute(sql);
}
//菜单关联到角色
dao.execute(Sqls.create("INSERT INTO sys_role_menu(roleId,menuId) SELECT @roleId,id FROM sys_menu").setParam("roleId", dbrole.getId()));
//消息中心放第一个位置
dao.execute(Sqls.create("update sys_menu set location=0 where path='00010003'"));
//初始化自定义路由
Sys_route route = new Sys_route();
route.setDisabled(false);
route.setUrl("/sysadmin");
route.setToUrl("/platform/login");
route.setType("hide");
dao.insert(route);
}
}
public void depose() {
// 非mysql数据库,或多webapp共享mysql驱动的话,以下语句删掉
try {
Mirror.me(Class.forName("com.mysql.jdbc.AbandonedConnectionCleanupThread")).invoke(null, "shutdown");
} catch (Throwable e) {
}
// 解决quartz有时候无法停止的问题
try {
ioc.get(Scheduler.class).shutdown(true);
} catch (Exception e) {
}
// 解决com.alibaba.druid.proxy.DruidDriver和com.mysql.jdbc.Driver在reload时报warning的问题
// 多webapp共享mysql驱动的话,以下语句删掉
Enumeration<Driver> en = DriverManager.getDrivers();
while (en.hasMoreElements()) {
try {
Driver driver = en.nextElement();
String className = driver.getClass().getName();
log.debug("deregisterDriver: " + className);
DriverManager.deregisterDriver(driver);
} catch (Exception e) {
}
}
try {
MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
ObjectName objectName = new ObjectName("com.alibaba.druid:type=MockDriver");
if (mbeanServer.isRegistered(objectName))
mbeanServer.unregisterMBean(objectName);
objectName = new ObjectName("com.alibaba.druid:type=DruidDriver");
if (mbeanServer.isRegistered(objectName))
mbeanServer.unregisterMBean(objectName);
} catch (Exception ex) {
}
}
}
@@ -0,0 +1,14 @@
package io.v.nutz.base.annontation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
public @interface SelectEnum{
String[] fields() default {};
}
@@ -0,0 +1,4 @@
package io.v.nutz.base.annontation;
public @interface Valid {
}
@@ -0,0 +1,9 @@
package io.v.nutz.base.annontation;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER})
@Documented
public @interface ViRequired {
}
@@ -0,0 +1,12 @@
package io.v.nutz.base.annontation;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Documented
public @interface ViReturn {
String successMsg() default "操作成功";
String errorMsg() default "操作失败";
}
@@ -0,0 +1,21 @@
package io.v.nutz.base.aop;
import io.v.nutz.base.annontation.ViReturn;
import io.v.nutz.base.interceptor.ViReturnInterceptor;
import org.nutz.aop.MethodInterceptor;
import org.nutz.ioc.Ioc;
import org.nutz.ioc.aop.SimpleAopMaker;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
public class ViReturnAopLoader extends SimpleAopMaker<ViReturn> {
public ViReturnAopLoader() {
}
public List<? extends MethodInterceptor> makeIt(ViReturn tryCatch, Method method, Ioc ioc) {
return Arrays.asList(new ViReturnInterceptor());
}
}
@@ -0,0 +1,125 @@
package io.v.nutz.base.config;
import lombok.extern.slf4j.Slf4j;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Lang;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;
/**
* @version 1.0
* @Author zzr
* @nameThreadPoolConfig
* @Date 2024/12/6 14:35
* @注释
*/
@Slf4j
@IocBean
public class ThreadPoolConfig {
@Inject
private Dao dao;
/**
* 核心线程数(默认线程数)
*/
private static final int CORE_POOL_SIZE = 2 * Runtime.getRuntime().availableProcessors() + 1;
/**
* 最大线程数
*/
private static final int MAX_POOL_SIZE = 128;
/**
* 允许线程空闲时间(单位:默认为秒)
*/
private static final int KEEP_ALIVE_TIME = 5;
/**
* 任务的等待时间
*/
private static final int AWAIT_TERMINATION_TIME = 30;
/**
* 缓冲队列数
*/
private static final int QUEUE_CAPACITY = 1200;
/**
* 线程池名前缀
*/
private static final String THREAD_NAME_PREFIX = "dd3s-thread-pool";
/**
* bean的名称,默认为首字母小写的方法名
* spring管理的线程池,顶级父类也是Executor
*/
@IocBean(name = "executorService")
public ThreadPoolTaskExecutor executorService() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(CORE_POOL_SIZE);
executor.setMaxPoolSize(MAX_POOL_SIZE);
executor.setQueueCapacity(QUEUE_CAPACITY);
executor.setKeepAliveSeconds(KEEP_ALIVE_TIME);
executor.setThreadNamePrefix(THREAD_NAME_PREFIX);
executor.setAwaitTerminationSeconds(AWAIT_TERMINATION_TIME);
executor.setWaitForTasksToCompleteOnShutdown(true);
// 线程池对拒绝任务的处理策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
/**
* 异步执行
*
* @param list 泛型list,任意实体类集合
* @param batchSize 期望单次操作的数量,默认200
* @param mode insert插入 update更新 insertOrUpdate插入或更新
* @param isFastInsertOrUpdateIgnoreNull mode为新增此值为true代表fastInsertmode为修改时此值为true代表updateIgnoreNull
* @param <T>
*/
public <T> void asyncExecute(List<T> list, Integer batchSize, String mode, boolean isFastInsertOrUpdateIgnoreNull) {
if (Lang.isEmpty(list)) {
return;
}
if (batchSize == null || batchSize <= 0) {
batchSize = 200;
}
for (int i = 0; i < list.size(); i += batchSize) {
final int end = Math.min(i + batchSize, list.size());
List<T> batch = list.subList(i, end);
executorService().execute(() -> {
try {
switch(mode) {
case "insert" -> {
if (isFastInsertOrUpdateIgnoreNull) {
dao.fastInsert(batch);
} else {
dao.insert(batch);
}
}
case "update" -> {
if (isFastInsertOrUpdateIgnoreNull) {
dao.updateIgnoreNull(batch);
} else {
dao.update(batch);
}
}
case "insertOrUpdate" -> dao.insertOrUpdate(batch);
}
} catch (Exception e) {
// 日志记录异常信息
System.err.println("Error occurred while inserting batch: " + e.getMessage());
e.printStackTrace();
}
});
}
}
}
@@ -0,0 +1,25 @@
package io.v.nutz.base.constant;
/**
* @author wizzer@qq.com
*/
public class RedisConstant {
public final static String PLATFORM_REDIS_PREFIX = "budwk5mini:";
public final static String PLATFORM_REDIS_WKCACHE_PREFIX = PLATFORM_REDIS_PREFIX + "wkcache:";
public final static String REDIS_KEY_WSROOM = PLATFORM_REDIS_PREFIX + "wsroom:";
public final static String REDIS_KEY_LOGIN_ADMIN_CAPTCHA = PLATFORM_REDIS_PREFIX + "admin:login:captcha:";
public final static String REDIS_KEY_ADMIN_PUBSUB = PLATFORM_REDIS_PREFIX + "admin:pubsub:";
public final static String REDIS_KEY_WX_TOKEN = PLATFORM_REDIS_PREFIX + "wx:token:";
public final static String REDIS_CAPTCHA_KEY = PLATFORM_REDIS_PREFIX + "platfrom:captcha:";
public final static String REDIS_SMSCODE_KEY = PLATFORM_REDIS_PREFIX + "platfrom:smscode:";
public final static String REDIS_KEY_API_SIGN_DEPLOY_NONCE = PLATFORM_REDIS_PREFIX + "api:sign:deploy:nonce:";
public final static String REDIS_KEY_API_SIGN_OPEN_NONCE = PLATFORM_REDIS_PREFIX + "api:sign:open:nonce:";
//企业微信TOKEN
public final static String REDIS_KEY_QIYE_WECHAT_ACCESS_TOKEN = "qiyewx:token:";
//健步走小程序TOKEN
public final static String REDIS_KEY_WE_APP_ACCESS_TOKEN = "weapp:token:";
}
@@ -0,0 +1,42 @@
package io.v.nutz.base.dao;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import io.v.nutz.base.query.PageForm;
import org.nutz.dao.Cnd;
import org.nutz.lang.Lang;
import org.nutz.lang.util.NutMap;
import java.util.Map;
public class CndPlus extends Cnd {
private static final NutMap map = NutMap.NEW().addv("ascending", "asc").addv("descending", "desc");
public CndPlus() {
}
public static String getOrder(String key) {
return map.getString(key);
}
public static CndPlus create() {
return new CndPlus();
}
public CndPlus and(PageForm pageForm) {
if (StrUtil.isAllNotBlank(pageForm.getSearchName(), pageForm.getSearchKeyword())) {
this.where().andLike(pageForm.getSearchName(), pageForm.getSearchKeyword());
}
if (StrUtil.isAllNotBlank(pageForm.getPageOrderName(), pageForm.getPageOrderBy())) {
this.orderBy(pageForm.getPageOrderName(), getOrder(pageForm.getPageOrderBy()));
}
return this;
}
public CndPlus andEx(String name, String op, Object value) {
if (StrUtil.isNotBlank(name) && !Lang.isEmpty(value)) {
this.and(name, op, value);
}
return this;
}
}
@@ -0,0 +1,27 @@
package io.v.nutz.base.enums;
import io.v.nutz.base.annontation.SelectEnum;
@SelectEnum
public enum AuditTypeEnum {
AUDIT(0, "审核"),
REJECT(1, "拒绝"),
NODE_PASS(2, "节点通过"),
PROCESS_PASS(3, "流程通过");
public Integer value;
public String desc;
public Integer getValue() {
return this.value;
}
public String getDesc() {
return this.desc;
}
private AuditTypeEnum(Integer value, String desc) {
this.value = value;
this.desc = desc;
}
}
@@ -0,0 +1,9 @@
package io.v.nutz.base.enums;
public enum Env {
dev,
prod;
private Env() {
}
}
@@ -0,0 +1,4 @@
package io.v.nutz.base.expression;
public interface Exp {
}
@@ -0,0 +1,6 @@
package io.v.nutz.base.expression;
@FunctionalInterface
public interface Exp1 extends Exp {
void run();
}
@@ -0,0 +1,6 @@
package io.v.nutz.base.expression;
@FunctionalInterface
public interface Exp2<T> extends Exp {
void run(T var1);
}
@@ -0,0 +1,6 @@
package io.v.nutz.base.expression;
@FunctionalInterface
public interface Exp3 extends Exp {
<E> void run(E... var1);
}
@@ -0,0 +1,5 @@
package io.v.nutz.base.expression;
public interface Exp4<T> extends Exp {
Object run(T var1);
}
@@ -0,0 +1,60 @@
package io.v.nutz.base.interceptor;
import io.v.nutz.base.annontation.ViReturn;
import io.v.nutz.base.result.Result;
import org.nutz.aop.InterceptorChain;
import org.nutz.aop.MethodInterceptor;
import org.nutz.lang.Lang;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.Param;
import java.lang.reflect.Parameter;
public class ViReturnInterceptor implements MethodInterceptor {
private static final Log log = Logs.get();
@Override
public void filter(InterceptorChain chain) throws Throwable {
Object[] args = chain.getArgs();
Parameter[] parameters = chain.getCallingMethod().getParameters();
try {
for (int i = 0; i < parameters.length; i++) {
Object param = args[i];
Parameter parameter = parameters[i];
Param paramAnnotation = parameter.getDeclaredAnnotation(Param.class);
if ((paramAnnotation == null || paramAnnotation.required()) && Lang.isEmpty(param)) {
chain.setReturnValue(Result.error().addMsg(parameter.getName() + " is required!"));
// throw new MissingParameterException(parameter.getName() + " must not null !");
}
}
//执行方法
InterceptorChain doChain = chain.doChain();
Object chainReturn = doChain.getReturn();
if (chainReturn instanceof Result) {
chain.setReturnValue(chainReturn);
}else if(chainReturn instanceof cn.wizzer.framework.base.Result){
chain.setReturnValue(chainReturn);
} else {
Result success = Result.success();
if (!chain.getCallingMethod().getReturnType().equals(Void.TYPE)) {
success.addData(doChain.getReturn());
}
success.addMsg(chain.getCallingMethod().getAnnotation(ViReturn.class).successMsg());
chain.setReturnValue(success);
}
} catch (Exception e) {
//如果之前没有设返回值就在这里设
if (chain.getReturn() == null) {
// chain.setReturnValue(Result.error().addMsg(chain.getCallingMethod().getAnnotation(ViReturn.class).errorMsg()));
chain.setReturnValue(Result.error().addMsg(e.getMessage()));
}
log.error(e);
}
}
}
@@ -0,0 +1,77 @@
package io.v.nutz.base.lang;
import cn.hutool.core.util.ReflectUtil;
import org.nutz.lang.util.NutMap;
import org.springframework.util.Assert;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
public class Enum {
public Enum() {
}
public static <E, C> E instance(Class<E> enumClass, C code) {
Assert.isTrue(enumClass.isEnum(), String.format("%s not a enum", enumClass.getSimpleName()));
Object[] enumConstants = enumClass.getEnumConstants();
Field[] fields = ReflectUtil.getFields(enumClass);
Object[] var4 = enumConstants;
int var5 = enumConstants.length;
for(int var6 = 0; var6 < var5; ++var6) {
Object object = var4[var6];
Field[] var8 = fields;
int var9 = fields.length;
for(int var10 = 0; var10 < var9; ++var10) {
Field field = var8[var10];
field.setAccessible(true);
try {
if (code.equals(field.get(object))) {
return (E) object;
}
} catch (IllegalAccessException var13) {
}
}
}
return null;
}
public static <E> List<NutMap> transToList(Class<E> enumClass) {
return transToList(enumClass, (List)null);
}
public static <E> List<NutMap> transToList(Class<E> enumClass, List<String> fieldNames) {
Assert.isTrue(enumClass.isEnum(), String.format("%s not a enum", enumClass.getSimpleName()));
List<NutMap> result = new ArrayList();
Object[] enumConstants = enumClass.getEnumConstants();
Field[] fields = ReflectUtil.getFields(enumClass);
Object[] var5 = enumConstants;
int var6 = enumConstants.length;
for(int var7 = 0; var7 < var6; ++var7) {
Object enumConstant = var5[var7];
NutMap map = NutMap.NEW();
Field[] var10 = fields;
int var11 = fields.length;
for(int var12 = 0; var12 < var11; ++var12) {
Field field = var10[var12];
if (fieldNames == null || fieldNames.contains(field.getName())) {
try {
field.setAccessible(true);
map.setv(field.getName(), field.get(enumConstant));
} catch (IllegalAccessException var15) {
}
}
}
result.add(map);
}
return result;
}
}
@@ -0,0 +1,63 @@
package io.v.nutz.base.lang;
import org.nutz.lang.Strings;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
public class Lang {
public Lang() {
}
public static boolean match(Object obj, boolean isNull) {
if (obj instanceof String) {
String s = (String)obj;
return isNull ? Strings.isBlank(s) : Strings.isNotBlank(s);
} else {
return isNull == (obj == null);
}
}
public static String sqlAlias(String alias) {
return Strings.isBlank(alias) ? "" : alias + ".";
}
public static boolean isNull(Object... objects) {
return Arrays.stream(objects).allMatch((v) -> {
return match(v, true);
});
}
public static boolean notNull(Object... objects) {
return Arrays.stream(objects).allMatch((v) -> {
return match(v, false);
});
}
public static boolean anyNull(Object... objects) {
return Arrays.stream(objects).anyMatch((v) -> {
return match(v, true);
});
}
public static boolean anyNotNull(Object... objects) {
return Arrays.stream(objects).anyMatch((v) -> {
return match(v, false);
});
}
public static int eleSize(Object obj) {
if (null == obj) {
return 0;
} else if (obj.getClass().isArray()) {
return Array.getLength(obj);
} else if (obj instanceof Collection) {
Collection o = (Collection)obj;
return o.size();
} else {
return obj instanceof Map ? ((Map)obj).size() : 1;
}
}
}
@@ -0,0 +1,360 @@
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package io.v.nutz.base.model;
import cn.hutool.json.JSONObject;
import cn.wizzer.framework.base.model.BaseModel;
import io.v.nutz.web.commons.utils.ShiroUtil;
import java.util.Date;
import org.nutz.dao.entity.annotation.ColDefine;
import org.nutz.dao.entity.annotation.ColType;
import org.nutz.dao.entity.annotation.Column;
import org.nutz.dao.entity.annotation.Comment;
import org.nutz.dao.entity.annotation.EL;
import org.nutz.dao.entity.annotation.Name;
import org.nutz.dao.entity.annotation.Prev;
import org.nutz.dao.entity.annotation.Table;
import org.nutz.dao.interceptor.annotation.PrevInsert;
@Table("audit")
public class Audit extends BaseModel {
@Column
@Name
@Comment("ID")
@ColDefine(
type = ColType.VARCHAR,
width = 32
)
@PrevInsert(
uu32 = true
)
private String id;
@Column
@Comment("审核人")
@ColDefine(
type = ColType.VARCHAR,
width = 32
)
@PrevInsert(
els = {@EL("$me.uid()")}
)
private String auditor;
@Column
@Comment("是否通过")
@ColDefine(
type = ColType.BOOLEAN
)
private Boolean auditPass;
@Column
@Comment("审核时间")
@Prev(
els = {@EL("$me.nowDate()")}
)
private Date auditTime;
@Column
@Comment("审核意见")
@ColDefine(
type = ColType.VARCHAR,
width = 500
)
private String auditOpinion;
@Column
@Comment("签字")
@ColDefine(
type = ColType.TEXT
)
private String auditSign;
@Column
@Comment("审核人姓名")
@ColDefine(
type = ColType.VARCHAR,
width = 50
)
@PrevInsert(
els = {@EL("$me.userName()")}
)
private String username;
@Column
@Comment("审核人工号")
@ColDefine(
type = ColType.VARCHAR,
width = 50
)
@PrevInsert(
els = {@EL("$me.loginName()")}
)
private String loginname;
@Column
@Comment("审核类型(1.通过 2.拒绝 3.退回)")
@ColDefine(
type = ColType.INT
)
private Integer auditType;
public JSONObject getExt() {
return ext;
}
public void setExt(JSONObject ext) {
this.ext = ext;
}
@Column
@Comment("扩展信息")
@ColDefine(type = ColType.MYSQL_JSON)
private JSONObject ext;
public Date nowDate() {
return new Date();
}
public String userName() {
return ShiroUtil.getPrincipalProperty("username").toString();
}
public String loginName() {
return ShiroUtil.getPrincipalProperty("loginname").toString();
}
public Audit() {
}
public String getId() {
return this.id;
}
public String getAuditor() {
return this.auditor;
}
public Boolean getAuditPass() {
return this.auditPass;
}
public Date getAuditTime() {
return this.auditTime;
}
public String getAuditOpinion() {
return this.auditOpinion;
}
public String getAuditSign() {
return this.auditSign;
}
public String getUsername() {
return this.username;
}
public String getLoginname() {
return this.loginname;
}
public Integer getAuditType() {
return this.auditType;
}
public Audit setId(String id) {
this.id = id;
return this;
}
public Audit setAuditor(String auditor) {
this.auditor = auditor;
return this;
}
public Audit setAuditPass(Boolean auditPass) {
this.auditPass = auditPass;
return this;
}
public Audit setAuditTime(Date auditTime) {
this.auditTime = auditTime;
return this;
}
public Audit setAuditOpinion(String auditOpinion) {
this.auditOpinion = auditOpinion;
return this;
}
public Audit setAuditSign(String auditSign) {
this.auditSign = auditSign;
return this;
}
public Audit setUsername(String username) {
this.username = username;
return this;
}
public Audit setLoginname(String loginname) {
this.loginname = loginname;
return this;
}
public Audit setAuditType(Integer auditType) {
this.auditType = auditType;
return this;
}
public String toString() {
String var10000 = this.getId();
return "Audit(id=" + var10000 + ", auditor=" + this.getAuditor() + ", auditPass=" + this.getAuditPass() + ", auditTime=" + this.getAuditTime() + ", auditOpinion=" + this.getAuditOpinion() + ", auditSign=" + this.getAuditSign() + ", username=" + this.getUsername() + ", loginname=" + this.getLoginname() + ", auditType=" + this.getAuditType() + ")";
}
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (!(o instanceof Audit)) {
return false;
} else {
Audit other = (Audit)o;
if (!other.canEqual(this)) {
return false;
} else if (!super.equals(o)) {
return false;
} else {
label121: {
Object this$id = this.getId();
Object other$id = other.getId();
if (this$id == null) {
if (other$id == null) {
break label121;
}
} else if (this$id.equals(other$id)) {
break label121;
}
return false;
}
Object this$auditor = this.getAuditor();
Object other$auditor = other.getAuditor();
if (this$auditor == null) {
if (other$auditor != null) {
return false;
}
} else if (!this$auditor.equals(other$auditor)) {
return false;
}
label107: {
Object this$auditPass = this.getAuditPass();
Object other$auditPass = other.getAuditPass();
if (this$auditPass == null) {
if (other$auditPass == null) {
break label107;
}
} else if (this$auditPass.equals(other$auditPass)) {
break label107;
}
return false;
}
Object this$auditTime = this.getAuditTime();
Object other$auditTime = other.getAuditTime();
if (this$auditTime == null) {
if (other$auditTime != null) {
return false;
}
} else if (!this$auditTime.equals(other$auditTime)) {
return false;
}
Object this$auditOpinion = this.getAuditOpinion();
Object other$auditOpinion = other.getAuditOpinion();
if (this$auditOpinion == null) {
if (other$auditOpinion != null) {
return false;
}
} else if (!this$auditOpinion.equals(other$auditOpinion)) {
return false;
}
label86: {
Object this$auditSign = this.getAuditSign();
Object other$auditSign = other.getAuditSign();
if (this$auditSign == null) {
if (other$auditSign == null) {
break label86;
}
} else if (this$auditSign.equals(other$auditSign)) {
break label86;
}
return false;
}
label79: {
Object this$username = this.getUsername();
Object other$username = other.getUsername();
if (this$username == null) {
if (other$username == null) {
break label79;
}
} else if (this$username.equals(other$username)) {
break label79;
}
return false;
}
Object this$loginname = this.getLoginname();
Object other$loginname = other.getLoginname();
if (this$loginname == null) {
if (other$loginname != null) {
return false;
}
} else if (!this$loginname.equals(other$loginname)) {
return false;
}
Object this$auditType = this.getAuditType();
Object other$auditType = other.getAuditType();
if (this$auditType == null) {
if (other$auditType != null) {
return false;
}
} else if (!this$auditType.equals(other$auditType)) {
return false;
}
return true;
}
}
}
protected boolean canEqual(Object other) {
return other instanceof Audit;
}
public static enum auditType {
PASS(1, "通过"),
REFUSE(2, "拒绝"),
BACK(3, "退回");
private final Integer code;
private final String desc;
public Integer getCode() {
return this.code;
}
public String getDesc() {
return this.desc;
}
private auditType(Integer code, String desc) {
this.code = code;
this.desc = desc;
}
}
}
@@ -0,0 +1,210 @@
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package io.v.nutz.base.model;
import java.util.List;
import org.nutz.dao.entity.annotation.ColDefine;
import org.nutz.dao.entity.annotation.ColType;
import org.nutz.dao.entity.annotation.Column;
import org.nutz.dao.entity.annotation.Comment;
import org.nutz.dao.entity.annotation.Id;
import org.nutz.dao.entity.annotation.Many;
import org.nutz.dao.entity.annotation.Table;
@Table("audit_state")
public class AuditState {
@Column
@Id(
auto = false
)
@Comment("ID")
@ColDefine(
type = ColType.INT,
width = 8
)
private Integer stateId;
@Column
@Comment("状态名")
@ColDefine(
type = ColType.VARCHAR,
width = 50
)
private String stateName;
@Column
@Comment("强调色")
@ColDefine(
type = ColType.VARCHAR,
width = 20
)
private String stateColor;
@Column
@Comment("隶属(***模块)")
@ColDefine(
type = ColType.VARCHAR,
width = 50
)
private String module;
@Column
@Comment("下个审核节点代码")
@ColDefine(
type = ColType.INT,
width = 8
)
private Integer afterStateId;
@Column
@Comment("通过下个审核节点代码")
@ColDefine(
type = ColType.INT,
width = 8
)
private Integer afterPassStateId;
@Column
@Comment("拒绝后下个节点代码")
@ColDefine(
type = ColType.INT,
width = 8
)
private Integer afterRejectStateId;
@Column
@Comment("会议类型id 属于那个会议类型的流程")
@ColDefine(
type = ColType.INT
)
private Integer meetingTypeId;
@Column
@Comment("会议审核类型")
@ColDefine(
type = ColType.INT
)
private String auditAfterType;
@Column
@Comment("审核节点类型")
@ColDefine(
type = ColType.INT
)
private Integer stateAuditType;
@Column
@Comment("审核人员匹配条件")
@ColDefine(
type = ColType.VARCHAR
)
private String matchCnd;
@Many(
field = "stateId"
)
private List<AuditStateUser> auditStateUserList;
public AuditState() {
}
public Integer getStateId() {
return this.stateId;
}
public String getStateName() {
return this.stateName;
}
public String getStateColor() {
return this.stateColor;
}
public String getModule() {
return this.module;
}
public Integer getAfterStateId() {
return this.afterStateId;
}
public Integer getAfterPassStateId() {
return this.afterPassStateId;
}
public Integer getAfterRejectStateId() {
return this.afterRejectStateId;
}
public Integer getMeetingTypeId() {
return this.meetingTypeId;
}
public String getAuditAfterType() {
return this.auditAfterType;
}
public Integer getStateAuditType() {
return this.stateAuditType;
}
public String getMatchCnd() {
return this.matchCnd;
}
public List<AuditStateUser> getAuditStateUserList() {
return this.auditStateUserList;
}
public AuditState setStateId(Integer stateId) {
this.stateId = stateId;
return this;
}
public AuditState setStateName(String stateName) {
this.stateName = stateName;
return this;
}
public AuditState setStateColor(String stateColor) {
this.stateColor = stateColor;
return this;
}
public AuditState setModule(String module) {
this.module = module;
return this;
}
public AuditState setAfterStateId(Integer afterStateId) {
this.afterStateId = afterStateId;
return this;
}
public AuditState setAfterPassStateId(Integer afterPassStateId) {
this.afterPassStateId = afterPassStateId;
return this;
}
public AuditState setAfterRejectStateId(Integer afterRejectStateId) {
this.afterRejectStateId = afterRejectStateId;
return this;
}
public AuditState setMeetingTypeId(Integer meetingTypeId) {
this.meetingTypeId = meetingTypeId;
return this;
}
public AuditState setAuditAfterType(String auditAfterType) {
this.auditAfterType = auditAfterType;
return this;
}
public AuditState setStateAuditType(Integer stateAuditType) {
this.stateAuditType = stateAuditType;
return this;
}
public AuditState setMatchCnd(String matchCnd) {
this.matchCnd = matchCnd;
return this;
}
public AuditState setAuditStateUserList(List<AuditStateUser> auditStateUserList) {
this.auditStateUserList = auditStateUserList;
return this;
}
}
@@ -0,0 +1,73 @@
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package io.v.nutz.base.model;
import org.nutz.dao.entity.annotation.ColDefine;
import org.nutz.dao.entity.annotation.ColType;
import org.nutz.dao.entity.annotation.Column;
import org.nutz.dao.entity.annotation.Comment;
import org.nutz.dao.entity.annotation.Name;
import org.nutz.dao.entity.annotation.Table;
import org.nutz.dao.interceptor.annotation.PrevInsert;
@Table
public class AuditStateUser {
@Name
@Comment("ID")
@ColDefine(
type = ColType.VARCHAR,
width = 32
)
@PrevInsert(
uu32 = true
)
private String id;
@Column
@ColDefine(
type = ColType.INT,
width = 8
)
@Comment("审核状态id")
private Integer stateId;
@Column
@ColDefine(
type = ColType.VARCHAR,
width = 32
)
@Comment("由谁来审核该状态(指定到某个用户)")
private String userId;
public AuditStateUser() {
}
public String getId() {
return this.id;
}
public Integer getStateId() {
return this.stateId;
}
public String getUserId() {
return this.userId;
}
public AuditStateUser setId(String id) {
this.id = id;
return this;
}
public AuditStateUser setStateId(Integer stateId) {
this.stateId = stateId;
return this;
}
public AuditStateUser setUserId(String userId) {
this.userId = userId;
return this;
}
}
@@ -0,0 +1,108 @@
package io.v.nutz.base.model;
import lombok.Data;
import org.nutz.dao.entity.annotation.*;
import org.nutz.dao.interceptor.annotation.PrevInsert;
import org.nutz.dao.interceptor.annotation.PrevUpdate;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.nutz.lang.Strings;
import org.nutz.mvc.Mvcs;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
/**
* Created by wizzer on 2016/6/21.
*/
@Data
public abstract class BaseModel implements Serializable {
private static final long serialVersionUID = 1L;
@Column
@Comment("创建人")
@PrevInsert(els = @EL("$me.createdByUid()"))
@ColDefine(type = ColType.VARCHAR, width = 32)
private String createdBy;
/**
* Long不要用ColDefine定义,兼容oracle/mysql,支持2038年以后的时间戳
* 13位时间戳哦,不再是11位
*/
@Column
@Comment("创建时间")
@PrevInsert(now = true)
private Long createdAt;
@Column
@Comment("修改人")
@PrevInsert(els = @EL("$me.updatedByUid()"))
@PrevUpdate(els = @EL("$me.updatedByUid()"))
@ColDefine(type = ColType.VARCHAR, width = 32)
private String updatedBy;
/**
* Long不要用ColDefine定义,兼容oracle/mysql,支持2038年以后的时间戳
* 13位时间戳哦,不再是11位
*/
@Column
@Comment("修改时间")
@PrevInsert(now = true)
@PrevUpdate(now = true)
private Long updatedAt;
@Column
@Comment("删除标记")
@PrevInsert(els = @EL("$me.flag()"))
@ColDefine(type = ColType.BOOLEAN)
private Boolean delFlag;
@Column
@Comment("opBy")
@ColDefine(type = ColType.VARCHAR)
private String opBy;
@Column
@Comment("opAt")
@ColDefine(type = ColType.VARCHAR)
private String opAt;
public String toJsonString() {
return Json.toJson(this, JsonFormat.compact());
}
public Boolean flag() {
return false;
}
public String createdByUid() {
String uid = getCreatedBy();
if (Strings.isNotBlank(uid)) {
return uid;
}
try {
HttpServletRequest request = Mvcs.getReq();
if (request != null) {
return Strings.sNull(request.getSession(true).getAttribute("platform_uid"));
}
} catch (Exception e) {
}
return "";
}
public String updatedByUid() {
String uid = getUpdatedBy();
if (Strings.isNotBlank(uid)) {
return uid;
}
try {
HttpServletRequest request = Mvcs.getReq();
if (request != null) {
return Strings.sNull(request.getSession(true).getAttribute("platform_uid"));
}
} catch (Exception e) {
}
return "";
}
}
@@ -0,0 +1,55 @@
package io.v.nutz.base.model;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.nutz.dao.entity.annotation.*;
import org.nutz.dao.interceptor.annotation.PrevInsert;
/**
* @author zhf
* @date 2020/12/6 16:45
* @description
*/
@EqualsAndHashCode(callSuper = true)
@Data
@Table("Goods")
public class Goods extends BaseModel {
@Column
@Name
@Comment("ID")
@ColDefine(type = ColType.VARCHAR, width = 32)
@PrevInsert(uu32 = true)
private String id;
@Column
@Comment("关联表id")
@ColDefine(type = ColType.VARCHAR, width = 32)
private String reid;
@Column
@Comment("物品名称")
@ColDefine(type = ColType.VARCHAR, width = 100)
private String name;
@Column
@Comment("物品价格")
@ColDefine(type = ColType.FLOAT, width = 30)
private Double price;
@Column
@Comment("实际物品价格")
@ColDefine(type = ColType.FLOAT, width = 30)
private Double actualPrice;
@Column
@Comment("说明")
@ColDefine(type = ColType.TEXT)
private String notes;
@Column
@Comment("活动编号")
@ColDefine(type = ColType.VARCHAR, width = 50)
private String activityCode;
}
@@ -0,0 +1,69 @@
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package io.v.nutz.base.model;
import cn.wizzer.framework.base.model.BaseModel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.nutz.dao.entity.annotation.ColDefine;
import org.nutz.dao.entity.annotation.ColType;
import org.nutz.dao.entity.annotation.Column;
import org.nutz.dao.entity.annotation.Comment;
import org.nutz.dao.entity.annotation.Name;
import org.nutz.dao.entity.annotation.Table;
import org.nutz.dao.interceptor.annotation.PrevInsert;
@EqualsAndHashCode(callSuper = true)
@Table("Review")
@Deprecated
@Data
public class Review extends BaseModel {
@Column
@Name
@Comment("ID")
@ColDefine(
type = ColType.VARCHAR,
width = 32
)
@PrevInsert(
uu32 = true
)
private String id;
@Column
@Comment("审核人姓名")
@ColDefine(
type = ColType.VARCHAR,
width = 50
)
private String username;
@Column
@Comment("审核人工号")
@ColDefine(
type = ColType.VARCHAR,
width = 50
)
private String loginname;
@Column
@Comment("审核时间")
@ColDefine(
type = ColType.VARCHAR,
width = 30
)
private String time;
@Column
@Comment("审核意见")
@ColDefine(
type = ColType.VARCHAR,
width = 500
)
private String opinion;
@Column
@Comment("签字")
@ColDefine(
type = ColType.TEXT
)
private String sign;
}
@@ -0,0 +1,49 @@
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package io.v.nutz.base.model;
import lombok.Data;
import org.nutz.dao.entity.annotation.ColDefine;
import org.nutz.dao.entity.annotation.ColType;
import org.nutz.dao.entity.annotation.Column;
import org.nutz.dao.entity.annotation.Comment;
import org.nutz.dao.entity.annotation.Name;
import org.nutz.dao.entity.annotation.Table;
@Table("State")
@Deprecated
@Data
public class State {
@Column
@Name
@Comment("ID")
@ColDefine(
type = ColType.INT,
width = 8
)
private String state_id;
@Column
@Comment("状态名")
@ColDefine(
type = ColType.VARCHAR,
width = 50
)
private String state_name;
@Column
@Comment("强调色")
@ColDefine(
type = ColType.VARCHAR,
width = 50
)
private String state_color;
@Column
@Comment("隶属(***模块)")
@ColDefine(
type = ColType.VARCHAR,
width = 50
)
private String belong;
}
@@ -0,0 +1,98 @@
package io.v.nutz.base.model;
import java.io.Serial;
import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.nutz.dao.entity.annotation.ColDefine;
import org.nutz.dao.entity.annotation.ColType;
import org.nutz.dao.entity.annotation.Column;
import org.nutz.dao.entity.annotation.Comment;
import org.nutz.dao.entity.annotation.EL;
import org.nutz.dao.interceptor.annotation.PrevInsert;
import org.nutz.dao.interceptor.annotation.PrevUpdate;
import org.nutz.lang.Strings;
import org.nutz.mvc.Mvcs;
public abstract class ViBaseModel implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
@Column
@Comment("创建人")
@PrevInsert(
els = {@EL("$me.uid()")}
)
@ColDefine(
type = ColType.VARCHAR,
width = 32
)
private String createdBy;
@Column
@Comment("创建时间")
@PrevInsert(
els = {@EL("$me.now()")}
)
private Date createdAt;
@Column
@Comment("修改人")
@PrevInsert(
els = {@EL("$me.uid()")}
)
@PrevUpdate(
els = {@EL("$me.uid()")}
)
@ColDefine(
type = ColType.VARCHAR,
width = 32
)
private String updatedBy;
@Column
@Comment("修改时间")
@PrevInsert(
els = {@EL("$me.now()")}
)
private Date updatedAt;
@Column
@Comment("删除标记")
@PrevInsert(
els = {@EL("$me.flag()")}
)
@ColDefine(
type = ColType.BOOLEAN
)
private Boolean delFlag;
public String uid() {
String uid = this.getCreatedBy();
if (Strings.isNotBlank(uid)) {
return uid;
} else {
try {
HttpServletRequest request = Mvcs.getReq();
if (request != null) {
return Strings.sNull(request.getSession(true).getAttribute("platform_uid"));
}
} catch (Exception var3) {
}
return "";
}
}
public Date now() {
return new Date();
}
public int nowYear() {
return Calendar.getInstance().get(1);
}
public String getCreatedBy() {
return this.createdBy;
}
public boolean flag(){
return false;
}
}
@@ -0,0 +1,46 @@
package io.v.nutz.base.page;
import org.nutz.dao.pager.Pager;
import java.io.Serializable;
/**
* 指定偏移量及大小的Pager, 这样就不会受限于原生Pager的offset=(pageNumber-1)*pageSize
*
* @author wendal
*/
public class OffsetPager extends Pager implements Serializable {
private static final long serialVersionUID = -1385308131663113162L;
protected int offset = -1;
protected OffsetPager() {
}
/**
* 构建一个指定偏移量及大小的Pager
*
* @param offset 偏移量
* @param size 数据大小
*/
public OffsetPager(int offset, int size) {
super();
this.offset = offset;
setPageSize(size);
}
/**
* 覆盖超类的计算得到的offset
*/
public int getOffset() {
if (offset > -1)
return offset;
return super.getOffset();
}
public void setOffset(int offset) {
this.offset = offset;
}
}
@@ -0,0 +1,57 @@
package io.v.nutz.base.page;
public interface Paginable {
/**
* 总记录数
*
* @return
*/
public int getTotalCount();
/**
* 总页数
*
* @return
*/
public int getTotalPage();
/**
* 每页记录数
*
* @return
*/
public int getPageSize();
/**
* 当前页号
*
* @return
*/
public int getPageNo();
/**
* 是否第一页
*
* @return
*/
public boolean isFirstPage();
/**
* 是否最后一页
*
* @return
*/
public boolean isLastPage();
/**
* 返回下页的页号
*/
public int getNextPage();
/**
* 返回上页的页号
*/
public int getPrePage();
}
@@ -0,0 +1,78 @@
package io.v.nutz.base.page;
import org.nutz.lang.Lang;
import java.util.List;
public class Pagination extends SimplePage implements java.io.Serializable {
private static final long serialVersionUID = 1L;
public Pagination() {
}
/**
* 构造器
*
* @param pageNo 页码
* @param pageSize 每页几条数据
* @param totalCount 总共几条数据
*/
public Pagination(int pageNo, int pageSize, int totalCount) {
super(pageNo, pageSize, totalCount);
}
/**
* 构造器
*
* @param pageNo 页码
* @param pageSize 每页几条数据
* @param totalCount 总共几条数据
* @param list 分页内容
*/
public Pagination(int pageNo, int pageSize, int totalCount, List list) {
super(pageNo, pageSize, totalCount);
this.list = list;
}
/**
* 第一条数据位置
*
* @return
*/
public int getFirstResult() {
return (pageNo - 1) * pageSize;
}
/**
* 当前页的数据
*/
private List list;
/**
* 获得分页内容
*
* @return
*/
public <T> List<T> getList() {
return list;
}
/**
* @param classOfT 列表容器內的元素类型
* @param <T> 列表容器內的元素类型
* @return
*/
public <T> List<T> getList(Class<T> classOfT) {
return Lang.collection2list(list, classOfT);
}
/**
* 设置分页内容
*
* @param list
*/
public void setList(List list) {
this.list = list;
}
}
@@ -0,0 +1,175 @@
package io.v.nutz.base.page;
import java.util.ArrayList;
import java.util.List;
public class SimplePage implements java.io.Serializable, Paginable {
private static final long serialVersionUID = 1L;
public static final int DEF_COUNT = 10;
private List<Integer> localArrayList = new ArrayList<Integer>();
public List<Integer> getSegment() {
return localArrayList;
}
/**
* 检查页码 checkPageNo
*
* @param pageNo
* @return if pageNo==null or pageNo 小于 1 then return 1 else return pageNo
*/
public static int cpn(Integer pageNo) {
return (pageNo == null || pageNo < 1) ? 1 : pageNo;
}
public SimplePage() {
}
/**
* 构造器
*
* @param pageNo 页码
* @param pageSize 每页几条数据
* @param totalCount 总共几条数据
*/
public SimplePage(int pageNo, int pageSize, int totalCount) {
setTotalCount(totalCount);
setPageSize(pageSize);
setPageNo(pageNo);
adjustPageNo();
int totalPages = getTotalPage();
minPage = minPage < 1 ? 1 : minPage;
maxPage = maxPage > totalPages ? totalPages : maxPage;
for (int i = minPage; i <= maxPage; i++) {
localArrayList.add(i);
}
}
/**
* 调整页码,使不超过最大页数
*/
public void adjustPageNo() {
if (pageNo == 1) {
return;
}
int tp = getTotalPage();
if (pageNo > tp) {
pageNo = tp;
}
}
/**
* 获得页码
*/
public int getPageNo() {
return pageNo;
}
/**
* 每页几条数据
*/
public int getPageSize() {
return pageSize;
}
/**
* 总共几条数据
*/
public int getTotalCount() {
return totalCount;
}
/**
* 总共几页
*/
public int getTotalPage() {
int totalPage = totalCount / pageSize;
if (totalPage == 0 || totalCount % pageSize != 0) {
totalPage++;
}
return totalPage;
}
/**
* 是否第一页
*/
public boolean isFirstPage() {
return pageNo <= 1;
}
/**
* 是否最后一页
*/
public boolean isLastPage() {
return pageNo >= getTotalPage();
}
/**
* 下一页页码
*/
public int getNextPage() {
if (isLastPage()) {
return pageNo;
} else {
return pageNo + 1;
}
}
/**
* 上一页页码
*/
public int getPrePage() {
if (isFirstPage()) {
return pageNo;
} else {
return pageNo - 1;
}
}
protected int totalCount = 0;
protected int pageSize = 20;
protected int pageNo = 1;
/**
* if totalCount 小于 0 then totalCount=0
*
* @param totalCount
*/
public void setTotalCount(int totalCount) {
if (totalCount < 0) {
this.totalCount = 0;
} else {
this.totalCount = totalCount;
}
}
/**
* if pageSize 小于 1 then pageSize=DEF_COUNT
*
* @param pageSize
*/
public void setPageSize(int pageSize) {
if (pageSize < 1) {
this.pageSize = DEF_COUNT;
} else {
this.pageSize = pageSize;
}
}
/**
* if pageNo 小于 1 then pageNo=1
*
* @param pageNo
*/
public void setPageNo(int pageNo) {
if (pageNo < 1) {
this.pageNo = 1;
} else {
this.pageNo = pageNo;
}
}
int minPage = pageNo - (int) Math.floor((pageSize - 1) / 2.0D);
int maxPage = pageNo + (int) Math.ceil((pageSize - 1) / 2.0D);
int totalPage = getTotalPage();
}
@@ -0,0 +1,47 @@
package io.v.nutz.base.page.datatable;
import java.io.Serializable;
/**
* Created by wizzer on 2016/6/27.
*/
public class DataTableColumn implements Serializable {
private static final long serialVersionUID = 1L;
protected String data;
protected String name;
protected boolean searchable;
protected boolean orderable;
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isSearchable() {
return searchable;
}
public void setSearchable(boolean searchable) {
this.searchable = searchable;
}
public boolean isOrderable() {
return orderable;
}
public void setOrderable(boolean orderable) {
this.orderable = orderable;
}
}
@@ -0,0 +1,29 @@
package io.v.nutz.base.page.datatable;
import java.io.Serializable;
/**
* Created by wizzer on 2016/6/27.
*/
public class DataTableOrder implements Serializable {
private static final long serialVersionUID = 1L;
protected int column;
protected String dir;
public int getColumn() {
return column;
}
public void setColumn(int column) {
this.column = column;
}
public String getDir() {
return dir;
}
public void setDir(String dir) {
this.dir = dir;
}
}
@@ -0,0 +1,79 @@
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package io.v.nutz.base.query;
public class PageForm {
private String searchName;
private String searchKeyword;
private Integer pageNumber;
private Integer pageSize;
private String pageOrderName;
private String pageOrderBy;
public PageForm defaultSort(String column, String order) {
this.setPageOrderName(column);
this.setPageOrderBy(order);
return this;
}
public PageForm defaultSortAsc(String column) {
return this.defaultSort(column, "ascending");
}
public PageForm defaultSortDesc(String column) {
return this.defaultSort(column, "descending");
}
public PageForm() {
}
public String getSearchName() {
return this.searchName;
}
public String getSearchKeyword() {
return this.searchKeyword;
}
public Integer getPageNumber() {
return this.pageNumber;
}
public Integer getPageSize() {
return this.pageSize;
}
public String getPageOrderName() {
return this.pageOrderName;
}
public String getPageOrderBy() {
return this.pageOrderBy;
}
public void setSearchName(String searchName) {
this.searchName = searchName;
}
public void setSearchKeyword(String searchKeyword) {
this.searchKeyword = searchKeyword;
}
public void setPageNumber(Integer pageNumber) {
this.pageNumber = pageNumber;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public void setPageOrderName(String pageOrderName) {
this.pageOrderName = pageOrderName;
}
public void setPageOrderBy(String pageOrderBy) {
this.pageOrderBy = pageOrderBy;
}
}
@@ -0,0 +1,109 @@
package io.v.nutz.base.result;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.nutz.lang.Strings;
import org.nutz.mvc.Mvcs;
import java.io.Serializable;
/**
* Created by wizzer on 2016/12/21.
*/
public class Result implements Serializable {
private static final long serialVersionUID = 1L;
private int code;
private String msg;
private Object data;
private long time;
public Result() {
this.time = System.currentTimeMillis();
}
public static Result NEW() {
return new Result();
}
public Result addCode(int code) {
this.code = code;
return this;
}
public Result addMsg(String msg) {
if (Strings.isBlank(msg) || Mvcs.getActionContext() == null || Mvcs.getActionContext().getRequest() == null || Mvcs.getMessage(Mvcs.getActionContext().getRequest(), msg) == null) {
this.msg = Strings.sNull(msg);
} else {
this.msg = Mvcs.getMessage(Mvcs.getActionContext().getRequest(), msg);
}
return this;
}
public Result addData(Object data) {
this.data = data;
return this;
}
public Result(int code, String msg, Object data) {
this.code = code;
if (Strings.isBlank(msg) || Mvcs.getActionContext() == null || Mvcs.getActionContext().getRequest() == null || Mvcs.getMessage(Mvcs.getActionContext().getRequest(), msg) == null) {
this.msg = Strings.sNull(msg);
} else {
this.msg = Mvcs.getMessage(Mvcs.getActionContext().getRequest(), msg);
}
this.data = data;
this.time = System.currentTimeMillis();
}
public static Result success(String content) {
return new Result(0, content, null);
}
public static Result success(String content, Object data) {
return new Result(0, content, data);
}
public static Result success(Object data) {
return new Result(0, "system.success", data);
}
public static Result error(int code, String content) {
return new Result(code, content, null);
}
public static Result error(String content) {
return new Result(1, content, null);
}
public static Result success() {
return new Result(0, "system.success", null);
}
public static Result error() {
return new Result(1, "system.error", null);
}
public int getCode() {
return code;
}
public String getMsg() {
return msg;
}
public Object getData() {
return data;
}
public static Result condition(boolean flag) {
return flag ? success("system.error") : error("system.error");
}
public String toJsonString() {
return Json.toJson(this, JsonFormat.compact());
}
}
@@ -0,0 +1,111 @@
package io.v.nutz.base.service;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import io.v.nutz.base.expression.Exp;
import io.v.nutz.base.expression.Exp1;
import io.v.nutz.base.expression.Exp2;
import org.nutz.aop.interceptor.async.Async;
import org.nutz.ioc.loader.annotation.IocBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.AsyncResult;
@IocBean
public class AsyncService {
private static final Logger log = LoggerFactory.getLogger(AsyncService.class);
public AsyncService() {
}
public void exe2(Iterable iterable, Exp1 e) {
this.listExe(iterable, e);
}
public <E> void exe2(Iterable<E> iterable, Exp2<E> e) {
this.listExe(iterable, e);
}
public void exe(Iterable iterable, Exp1 e) {
this.listExe2(iterable, e);
}
public <E> void exe(Iterable<E> iterable, Exp2<E> e) {
this.listExe2(iterable, e);
}
private void listExe(Iterable iterable, Exp exp) {
List<Future> futures = new ArrayList();
Iterator var4 = iterable.iterator();
while(var4.hasNext()) {
Object o = var4.next();
if (exp instanceof Exp1) {
Exp1 exp1 = (Exp1)exp;
futures.add(this._run(exp1));
} else if (exp instanceof Exp2) {
Exp2 exp2 = (Exp2)exp;
futures.add(this._run(o, exp2));
}
}
var4 = futures.iterator();
while(var4.hasNext()) {
Future future = (Future)var4.next();
try {
future.get();
} catch (InterruptedException var7) {
var7.printStackTrace();
} catch (ExecutionException var8) {
var8.printStackTrace();
}
}
}
private void listExe2(Iterable par, Exp exp) {
Iterator var3 = par.iterator();
while(var3.hasNext()) {
Object o = var3.next();
if (exp instanceof Exp1) {
Exp1 exp1 = (Exp1)exp;
this._run2(exp1);
} else if (exp instanceof Exp2) {
Exp2 exp2 = (Exp2)exp;
this._run2(o, exp2);
}
}
}
@Async
public Future _run(Exp1 e) {
e.run();
return new AsyncResult((Object)null);
}
@Async
public Future _run(Object o, Exp2 e) {
e.run(o);
return new AsyncResult((Object)null);
}
@Async
public void _run2(Exp1 e) {
e.run();
}
@Async
public void _run2(Object o, Exp2 e) {
e.run(o);
}
}
@@ -0,0 +1,6 @@
package io.v.nutz.base.service;
import io.v.nutz.base.model.Audit;
public interface AuditService extends ViService<Audit> {
}
@@ -0,0 +1,914 @@
package io.v.nutz.base.service;
import io.v.nutz.base.page.Pagination;
import io.v.nutz.base.page.datatable.DataTableColumn;
import io.v.nutz.base.page.datatable.DataTableOrder;
import org.nutz.dao.*;
import org.nutz.dao.entity.Entity;
import org.nutz.dao.entity.Record;
import org.nutz.dao.pager.Pager;
import org.nutz.dao.sql.Sql;
import org.nutz.lang.util.NutMap;
import java.util.List;
import java.util.Map;
/**
* Created by wizzer on 2016/12/22.
*/
public interface BaseService<T> {
Dao dao();
/**
* 获取实体的Entity
*
* @return 实体的Entity
*/
Entity<T> getEntity();
/**
* 获取实体类型
*
* @return 实体类型
*/
Class<T> getEntityClass();
/**
* 统计符合条件的对象表条数
*
* @param cnd
* @return
*/
int count(Condition cnd);
/**
* 统计对象表条数
*
* @return
*/
int count();
/**
* 统计符合条件的记录条数
*
* @param tableName
* @param cnd
* @return
*/
int count(String tableName, Condition cnd);
/**
* 统计表记录条数
*
* @param tableName
* @return
*/
int count(String tableName);
/**
* 自定义SQL统计
*
* @param sql
* @return
*/
int count(Sql sql);
/**
* 通过数字型主键查询对象
*
* @param id
* @return
*/
T fetch(long id);
/**
* 通过字符型主键查询对象
*
* @param id
* @return
*/
T fetch(String id);
/**
* 查询关联表
*
* @param obj 数据对象,可以是普通对象或集合,但不是类
* @param regex 为null查询全部,支持通配符 ^(a|b)$
* @return
*/
<T> T fetchLinks(T obj, String regex);
/**
* 查询关联表
*
* @param obj 数据对象,可以是普通对象或集合,但不是类
* @param regex 为null查询全部,支持通配符 ^(a|b)$
* @param cnd 关联字段的过滤(排序,条件语句,分页等)
* @return
*/
<T> T fetchLinks(T obj, String regex, Condition cnd);
/**
* 查出符合条件的第一条记录
*
* @param cnd 查询条件
* @return 实体, 如不存在则为null
*/
T fetch(Condition cnd);
/**
* 复合主键专用
*
* @param pks 键值
* @return 对象 T
*/
T fetchx(Object... pks);
/**
* 复合主键专用
*
* @param pks 键值
* @return 对象 T
*/
boolean exists(Object... pks);
/**
* 将一个对象插入到一个数据库
*
* @param obj 要被插入的对象
* 它可以是:
* 普通 POJO
* 集合
* 数组
* Map
* 注意:如果是集合,数组或者 Map,所有的对象必须类型相同,否则可能会出错
* @return 插入后的对象
*/
<T> T insert(T obj);
/**
* 将一个对象按FieldFilter过滤后,插入到一个数据源。
* <p>
* <code>dao.insert(pet, FieldFilter.create(Pet.class, FieldMatcher.create(false)));</code>
*
* @param obj 要被插入的对象
* @param filter 字段过滤器, 其中FieldMatcher.isIgnoreId生效
* @return 插入后的对象
* @see Dao#insert(Object)
*/
<T> T insert(T obj, FieldFilter filter);
/**
* 根据对象的主键(@Id/@Name/@Pk)先查询, 如果存在就更新, 不存在就插入
*
* @param obj 对象
* @return 原对象
*/
<T> T insertOrUpdate(T obj);
/**
* 根据对象的主键(@Id/@Name/@Pk)先查询, 如果存在就更新, 不存在就插入
*
* @param obj 对象
* @param insertFieldFilter 插入时的字段过滤, 可以是null
* @param updateFieldFilter 更新时的字段过滤,可以是null
* @return 原对象
*/
<T> T insertOrUpdate(T obj, FieldFilter insertFieldFilter, FieldFilter updateFieldFilter);
/**
* 自由的向一个数据表插入一条数据
*
* @param tableName 表名
* @param chain 数据名值链
*/
void insert(String tableName, Chain chain);
/**
* 快速插入一个对象,对象的 '@Prev' 以及 '@Next' 在这个函数里不起作用
*
* @param obj
* @return
*/
<T> T fastInsert(T obj);
/**
* 将对象插入数据库同时,也将符合一个正则表达式的所有关联字段关联的对象统统插入相应的数据库
* <p>
* 关于关联字段更多信息,请参看 '@One' | '@Many' | '@ManyMany' 更多的描述
*
* @param obj 数据对象
* @param regex 正则表达式,描述了什么样的关联字段将被关注。如果为 null,则表示全部的关联字段都会被插入
* @return 数据对象本身
* @see org.nutz.dao.entity.annotation.One
* @see org.nutz.dao.entity.annotation.Many
* @see org.nutz.dao.entity.annotation.ManyMany
*/
<T> T insertWith(T obj, String regex);
/**
* 根据一个正则表达式,仅将对象所有的关联字段插入到数据库中,并不包括对象本身
*
* @param obj 数据对象
* @param regex 正则表达式,描述了什么样的关联字段将被关注。如果为 null,则表示全部的关联字段都会被插入
* @return 数据对象本身
* @see org.nutz.dao.entity.annotation.One
* @see org.nutz.dao.entity.annotation.Many
* @see org.nutz.dao.entity.annotation.ManyMany
*/
<T> T insertLinks(T obj, String regex);
/**
* 将对象的一个或者多个,多对多的关联信息,插入数据表
*
* @param obj 对象
* @param regex 正则表达式,描述了那种多对多关联字段将被执行该操作
* @return 对象自身
* @see org.nutz.dao.entity.annotation.ManyMany
*/
<T> T insertRelation(T obj, String regex);
/**
* 更新数据
*
* @param obj
* @return
*/
int update(Object obj);
/**
* 更新数据忽略值为null的字段
*
* @param obj
* @return
*/
int updateIgnoreNull(Object obj);
/**
* 部分更新实体表
*
* @param chain
* @param cnd
* @return
*/
int update(Chain chain, Condition cnd);
/**
* 部分更新表
*
* @param tableName
* @param chain
* @param cnd
* @return
*/
int update(String tableName, Chain chain, Condition cnd);
/**
* 将对象更新的同时,也将符合一个正则表达式的所有关联字段关联的对象统统更新
* <p>
* 关于关联字段更多信息,请参看 '@One' | '@Many' | '@ManyMany' 更多的描述
*
* @param obj 数据对象
* @param regex 正则表达式,描述了什么样的关联字段将被关注。如果为 null,则表示全部的关联字段都会被更新
* @return 数据对象本身
* @see org.nutz.dao.entity.annotation.One
* @see org.nutz.dao.entity.annotation.Many
* @see org.nutz.dao.entity.annotation.ManyMany
*/
<T> T updateWith(T obj, String regex);
/**
* 根据一个正则表达式,仅更新对象所有的关联字段,并不包括对象本身
*
* @param obj 数据对象
* @param regex 正则表达式,描述了什么样的关联字段将被关注。如果为 null,则表示全部的关联字段都会被更新
* @return 数据对象本身
* @see org.nutz.dao.entity.annotation.One
* @see org.nutz.dao.entity.annotation.Many
* @see org.nutz.dao.entity.annotation.ManyMany
*/
<T> T updateLinks(T obj, String regex);
/**
* 多对多关联是通过一个中间表将两条数据表记录关联起来。
* <p>
* 而这个中间表可能还有其他的字段,比如描述关联的权重等
* <p>
* 这个操作可以让你一次更新某一个对象中多个多对多关联的数据
*
* @param classOfT 对象类型
* @param regex 正则表达式,描述了那种多对多关联字段将被执行该操作
* @param chain 针对中间关联表的名值链。
* @param cnd 针对中间关联表的 WHERE 条件
* @return 共有多少条数据被更新
* @see org.nutz.dao.entity.annotation.ManyMany
*/
int updateRelation(Class<?> classOfT, String regex, Chain chain, Condition cnd);
/**
* 基于版本的更新,版本不一样无法更新到数据
*
* @param obj 需要更新的对象, 必须有version属性
* @return 若更新成功, 大于0, 否则小于0
*/
int updateWithVersion(Object obj);
/**
* 基于版本的更新,版本不一样无法更新到数据
*
* @param obj 需要更新的对象, 必须有version属性
* @param filter 需要过滤的字段设置
* @return 若更新成功, 大于0, 否则小于0
*/
int updateWithVersion(Object obj, FieldFilter filter);
/**
* 乐观锁, 以特定字段的值作为限制条件,更新对象,并自增该字段.
* <p>
* 执行的sql如下:
* <p>
* <code>update t_user set age=30, city="广州", version=version+1 where name="wendal" and version=124;</code>
*
* @param obj 需要更新的对象, 必须带@Id/@Name/@Pk中的其中一种.
* @param fieldFilter 需要过滤的属性. 若设置了哪些字段不更新,那务必确保过滤掉fieldName的字段
* @param fieldName 参考字段的Java属性名.默认是"version",可以是任意数值字段
* @return 若更新成功, 返回值大于0, 否则小于等于0
*/
int updateAndIncrIfMatch(Object obj, FieldFilter fieldFilter, String fieldName);
/**
* 获取某个对象,最大的 ID 值,这个对象必须声明了 '@Id'
*
* @return
*/
int getMaxId();
/**
* 通过long主键删除数据
*
* @param id
* @return
*/
int delete(long id);
/**
* 通过int主键删除数据
*
* @param id
* @return
*/
int delete(int id);
/**
* 通过string主键删除数据
*
* @param id
* @return
*/
int delete(String id);
/**
* 批量删除
*
* @param ids
*/
void delete(Integer[] ids);
/**
* 批量删除
*
* @param ids
*/
void delete(Long[] ids);
/**
* 批量删除
*
* @param ids
*/
void delete(String[] ids);
/**
* 批量删除
*
* @param ids
*/
void delete(List<String> ids);
/**
* 清空表
*
* @return
*/
int clear();
/**
* 清空表
*
* @return
*/
int clear(String tableName);
/**
* 按条件清除一组数据
*
* @return
*/
int clear(Condition cnd);
/**
* 按条件清除一组数据
*
* @return
*/
int clear(String tableName, Condition cnd);
/**
* 伪删除
*
* @param id
* @return
*/
int vDelete(String id);
/**
* 批量伪删除
*
* @param ids
* @return
*/
int vDelete(String[] ids);
/**
* 批量伪删除
*
* @param ids
* @return
*/
int vDelete(List<String> ids);
/**
* 根据条件进行伪删除
*
* @param cnd
* @return
*/
int vDelete(Condition cnd);
/**
* 根据条件进行伪删除
*
* @param cnd
* @return
*/
int vDelete(String tableName, Condition cnd);
/**
* 通过LONG主键获取部分字段值
*
* @param fieldName
* @param id
* @return
*/
T getField(String fieldName, long id);
/**
* 通过INT主键获取部分字段值
*
* @param fieldName
* @param id
* @return
*/
T getField(String fieldName, int id);
/**
* 通过NAME主键获取部分字段值
*
* @param fieldName 支持通配符 ^(a|b)$
* @param name
* @return
*/
T getField(String fieldName, String name);
/**
* 通过条件获取部分字段值
*
* @param fieldName 支持通配符 ^(a|b)$
* @param cnd
* @return
*/
T getField(String fieldName, Condition cnd);
/**
* 查询获取部分字段
*
* @param fieldName 支持通配符 ^(a|b)$
* @param cnd
* @return
*/
List<T> query(String fieldName, Condition cnd);
/**
* 查询一组对象。你可以为这次查询设定条件
*
* @param cnd WHERE 条件。如果为 null,将获取全部数据,顺序为数据库原生顺序<br>
* 只有在调用这个函数的时候, cnd.limit 才会生效
* @return 对象列表
*/
List<T> query(Condition cnd);
/**
* 获取全部数据
*
* @return
*/
List<T> query();
/**
* @param cnd 查询条件
* @param linkName 关联字段,支持正则 ^(a|b)$
* @return
*/
List<T> query(Condition cnd, String linkName);
/**
* 获取表及关联表全部数据(支持子查询)
*
* @param cnd 查询条件
* @param linkName 关联字段,支持正则 ^(a|b)$
* @param linkCnd 关联条件
* @return
*/
List<T> query(Condition cnd, String linkName, Condition linkCnd);
/**
* 获取表及关联表全部数据
*
* @param linkName 关联字段,支持正则 ^(a|b)$
* @return
*/
List<T> query(String linkName);
/**
* 分页关联字段查询
*
* @param cnd 查询条件
* @param linkName 关联字段,支持正则 ^(a|b)$
* @param pager 分页对象
* @return
*/
List<T> query(Condition cnd, String linkName, Pager pager);
/**
* 分页关联字段查询(支持关联条件)
*
* @param cnd 查询条件
* @param linkName 关联字段,支持正则 ^(a|b)$
* @param linkCnd 关联条件
* @param pager 分页对象
* @return
*/
List<T> query(Condition cnd, String linkName, Condition linkCnd, Pager pager);
/**
* 分页查询
*
* @param cnd 查询条件
* @param pager 分页对象
* @return
*/
List<T> query(Condition cnd, Pager pager);
/**
* 查询获取NutMap对象
*
* @param keyColumnName 作为key的字段名
* @param valueColumnName 作为value的字段名
* @param cnd 查询条件
* @return
*/
NutMap query(String keyColumnName, String valueColumnName, Condition cnd);
/**
* 查询获取NutMap对象
*
* @param tableName 表名
* @param keyColumnName 作为key的字段名
* @param valueColumnName 作为value的字段名
* @param cnd 查询条件
* @return
*/
NutMap query(String tableName, String keyColumnName, String valueColumnName, Condition cnd);
/**
* 计算子节点TREEID
*
* @param tableName
* @param colName
* @param value
* @return
*/
String getSubPath(String tableName, String colName, String value);
/**
* 获取TREEID父级
*
* @param path
* @return
*/
String getParentPath(String path);
/**
* 执行一条自定义SQL
*
* @param sql
* @return
*/
Sql execute(Sql sql);
/**
* 自定义SQL返回Record记录集,Record是个MAP但不区分大小写
* 别返回Map对象,因为MySql和Oracle中字段名有大小写之分
*
* @param sql
* @return
*/
List<Record> list(Sql sql);
/**
* 自定义SQL返回NutMap记录集,区分大小写
*
* @param sql
* @return
*/
List<NutMap> listMap(Sql sql);
/**
* 自定义查询,并返回当前实体类对象
*
* @param sql
* @return
*/
List<T> listEntity(Sql sql);
/**
* 自定义sql获取map key-value
*
* @param sql
* @return
*/
Map getMap(Sql sql);
/**
* 自定义sql获取NutMap key-value
*
* @param sql
* @return
*/
NutMap getNutMap(Sql sql);
/**
* 分页查询
*
* @param pageNumber
* @param cnd
* @return
*/
Pagination listPage(Integer pageNumber, Condition cnd);
/**
* 分页查询
*
* @param pageNumber
* @param sql
* @return
*/
Pagination listPage(Integer pageNumber, Sql sql);
/**
* 分页查询(sql)
*
* @param pageNumber
* @param pageSize
* @param sql
* @return
*/
Pagination listPage(Integer pageNumber, int pageSize, Sql sql);
/**
* 分页查询
*
* @param pageNumber
* @param sql 查询语句
* @param countSql 统计语句
* @return
*/
Pagination listPage(Integer pageNumber, Sql sql, Sql countSql);
/**
* 分页查询
*
* @param pageNumber
* @param pageSize
* @param sql 查询语句
* @param countSql 统计语句
* @return
*/
Pagination listPage(Integer pageNumber, int pageSize, Sql sql, Sql countSql);
/**
* 分页查询
*
* @param pageNumber
* @param sql
* @return
*/
Pagination listPageMap(Integer pageNumber, Sql sql);
/**
* 分页查询(sql)
*
* @param pageNumber
* @param pageSize
* @param sql
* @return
*/
Pagination listPageMap(Integer pageNumber, int pageSize, Sql sql);
/**
* 分页查询
*
* @param pageNumber
* @param sql 查询语句
* @param countSql 统计语句
* @return
*/
Pagination listPageMap(Integer pageNumber, Sql sql, Sql countSql);
/**
* 分页查询
*
* @param pageNumber
* @param pageSize
* @param sql 查询语句
* @param countSql 统计语句
* @return
*/
Pagination listPageMap(Integer pageNumber, int pageSize, Sql sql, Sql countSql);
/**
* 分页查询
*
* @param pageNumber
* @param tableName
* @param cnd
* @return
*/
Pagination listPage(Integer pageNumber, String tableName, Condition cnd);
/**
* 分页查询(cnd)
*
* @param pageNumber
* @param pageSize
* @param cnd
* @return
*/
Pagination listPage(Integer pageNumber, int pageSize, Condition cnd);
/**
* 分页查询,获取部分字段(cnd)
*
* @param pageNumber
* @param pageSize
* @param cnd
* @param fieldName 支持通配符 ^(a|b)$
* @return
*/
Pagination listPage(Integer pageNumber, int pageSize, Condition cnd, String fieldName);
/**
* 关联查询
*
* @param pageNumber
* @param pageSize
* @param cnd
* @param linkName 支持通配符 ^(a|b)$
* @return
*/
Pagination listPageLinks(Integer pageNumber, int pageSize, Condition cnd, String linkName);
/**
* 关联查询,带子查询条件
*
* @param pageNumber
* @param pageSize
* @param cnd
* @param linkName 支持通配符 ^(a|b)$
* @param subCnd 子查询条件
* @return
*/
Pagination listPageLinks(Integer pageNumber, int pageSize, Condition cnd, String linkName, Condition subCnd);
/**
* 分页查询(tabelName)
*
* @param pageNumber
* @param pageSize
* @param tableName
* @param cnd
* @return
*/
Pagination listPage(Integer pageNumber, int pageSize, String tableName, Condition cnd);
/**
* 分页查询并返回包含实体类内容的NutMap对象
*
* @param pageNumber
* @param cnd
* @return
*/
Pagination listPageMap(Integer pageNumber, Condition cnd);
/**
* 分页查询并返回包含实体类内容的NutMap对象
*
* @param pageNumber
* @param pageSize
* @param cnd
* @return
*/
Pagination listPageMap(Integer pageNumber, int pageSize, Condition cnd);
/**
* DataTable Page
*
* @param length 页大小
* @param start start
* @param draw draw
* @param orders 排序
* @param columns 字段
* @param cnd 查询条件
* @param linkName 关联查询 支持通配符 ^(a|b)$
* @return
*/
NutMap data(int length, int start, int draw, List<DataTableOrder> orders, List<DataTableColumn> columns, Cnd cnd, String linkName);
/**
* DataTable Page
*
* @param length 页大小
* @param start start
* @param draw draw
* @param orders 排序
* @param columns 字段
* @param cnd 查询条件
* @param linkName 关联查询 支持通配符 ^(a|b)$
* @param subCnd 关联查询条件
* @return
*/
NutMap data(int length, int start, int draw, List<DataTableOrder> orders, List<DataTableColumn> columns, Cnd cnd, String linkName, Cnd subCnd);
/**
* DataTable Page 自定义SQL
*
* @param length 页大小
* @param start start
* @param draw draw
* @param countSql 统计查询语句
* @param orderSql 结果查询语句
* @return
*/
NutMap data(int length, int start, int draw, Sql countSql, Sql orderSql);
/**
* DataTable Page 自定义SQL
*
* @param length 页大小
* @param start start
* @param draw draw
* @param countSql 统计查询语句
* @param orderSql 结果查询语句
* @param countOnly 统计查询语句是否只有count()
* @return
*/
NutMap data(int length, int start, int draw, Sql countSql, Sql orderSql, boolean countOnly);
/**
* DataTable Page
*
* @param length 页大小
* @param start start
* @param draw draw
* @param cnd 查询条件
* @param linkName 关联查询 支持通配符 ^(a|b)$
* @return
*/
NutMap data(int length, int start, int draw, Cnd cnd, String linkName);
}
@@ -0,0 +1,8 @@
package io.v.nutz.base.service;
import cn.wizzer.framework.base.service.BaseService;
import io.v.nutz.base.model.Review;
@Deprecated
public interface ReviewService extends BaseService<Review> {
}
@@ -0,0 +1,11 @@
package io.v.nutz.base.service;
/**
* @author zxy
* @Description TODO
* @createTime 2022年01月04日 13:55:00
*/
public interface SimpleService extends ViService {
}
@@ -0,0 +1,42 @@
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package io.v.nutz.base.service;
import cn.wizzer.framework.base.service.BaseService;
import cn.wizzer.framework.page.Pagination;
import io.v.nutz.base.expression.Exp1;
import io.v.nutz.base.query.PageForm;
import java.util.List;
import org.nutz.dao.Cnd;
import org.nutz.dao.FieldFilter;
import org.nutz.dao.sql.Sql;
import org.nutz.lang.util.NutMap;
public interface ViService<T> extends BaseService<T> {
void transactional(Exp1 var1);
<C extends Cnd> Pagination list(PageForm var1, C var2);
<C extends Cnd> Pagination listLinks(PageForm var1, C var2);
<C extends Cnd> Pagination listLinks(PageForm var1, C var2, FieldFilter var3);
Pagination list(PageForm var1, Sql var2);
<E> List<E> listEntity(Sql var1, Class<E> var2);
List<NutMap> listMap(Sql var1);
NutMap fetch(Sql var1);
T fetchLinks(String var1);
T fetchLinks(long var1);
T fetchLinks(String var1, FieldFilter var2);
T fetchLinks(long var1, FieldFilter var3);
}
@@ -0,0 +1,19 @@
package io.v.nutz.base.service.impl;
import io.v.nutz.base.model.Audit;
import io.v.nutz.base.service.AuditService;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.plugins.wkcache.annotation.CacheDefaults;
@IocBean(
args = {"refer:dao"}
)
@CacheDefaults(
cacheName = "audit"
)
public class AuditServiceImpl extends ViServiceImpl<Audit> implements AuditService {
public AuditServiceImpl(Dao dao) {
super(dao);
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,21 @@
package io.v.nutz.base.service.impl;
import cn.wizzer.framework.base.service.BaseServiceImpl;
import io.v.nutz.base.model.Review;
import io.v.nutz.base.service.ReviewService;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.plugins.wkcache.annotation.CacheDefaults;
@Deprecated
@IocBean(
args = {"refer:dao"}
)
@CacheDefaults(
cacheName = "Review"
)
public class ReviewServiceImpl extends BaseServiceImpl<Review> implements ReviewService {
public ReviewServiceImpl(Dao dao) {
super(dao);
}
}
@@ -0,0 +1,19 @@
package io.v.nutz.base.service.impl;
import io.v.nutz.base.service.SimpleService;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.IocBean;
/**
* @author zxy
* @Description TODO
* @createTime 2022年01月04日 13:55:00
*/
@IocBean(args = {"refer:dao"})
public class SimpleServiceImpl extends ViServiceImpl implements SimpleService {
public SimpleServiceImpl(Dao dao) {
super(dao);
}
}
@@ -0,0 +1,105 @@
package io.v.nutz.base.service.impl;
import cn.wizzer.framework.base.service.BaseServiceImpl;
import cn.wizzer.framework.page.Pagination;
import java.util.List;
import io.v.nutz.base.dao.CndPlus;
import io.v.nutz.base.expression.Exp1;
import io.v.nutz.base.query.PageForm;
import io.v.nutz.base.service.ViService;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.FieldFilter;
import org.nutz.dao.Sqls;
import org.nutz.dao.pager.Pager;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.util.Daos;
import org.nutz.lang.Mirror;
import org.nutz.lang.util.NutMap;
import org.nutz.trans.Atom;
import org.nutz.trans.Trans;
public class ViServiceImpl<T> extends BaseServiceImpl<T> implements ViService<T> {
public ViServiceImpl(Dao dao) {
super(dao);
}
public void transactional(final Exp1 exp) {
Trans.exec(new Atom[]{new Atom() {
public void run() {
exp.run();
}
}});
}
public <T extends Cnd> Pagination list(PageForm pageForm, T cnd) {
if (cnd instanceof CndPlus) {
((CndPlus)cnd).and(pageForm);
}
return super.listPage(pageForm.getPageNumber(), pageForm.getPageSize(), cnd);
}
public <C extends Cnd> Pagination listLinks(PageForm pageForm, C cnd) {
return this.listLinks(pageForm, cnd, (FieldFilter)null);
}
public <C extends Cnd> Pagination listLinks(PageForm pageForm, C cnd, FieldFilter fieldFilter) {
int pageNumber = this.getPageNumber(pageForm.getPageNumber());
int pageSize = this.getPageSize(pageForm.getPageSize());
Pager pager = this.dao().createPager(pageNumber, pageSize);
if (cnd instanceof CndPlus) {
((CndPlus)cnd).and(pageForm);
}
List<T> list = this.dao().query(this.getEntityClass(), cnd, pager);
pager.setRecordCount(this.dao().count(this.getEntityClass(), cnd));
if (null == fieldFilter) {
this.dao().fetchLinks(list, (String)null);
} else {
Daos.ext(this.dao(), fieldFilter).fetchLinks(list, (String)null);
}
return new Pagination(pageNumber, pageSize, pager.getRecordCount(), list);
}
public Pagination list(PageForm pageForm, Sql sql) {
return super.listPageMap(pageForm.getPageNumber(), pageForm.getPageSize(), sql);
}
public <E> List<E> listEntity(Sql sql, Class<E> target) {
sql.setEntity(this.dao().getEntity(Mirror.me(target).getType()));
sql.setCallback(Sqls.callback.entities());
this.dao().execute(sql);
return sql.getList(target);
}
public List<NutMap> listMap(Sql sql) {
sql.setCallback(Sqls.callback.maps());
this.dao().execute(sql);
return sql.getList(NutMap.class);
}
public NutMap fetch(Sql sql) {
sql.setCallback(Sqls.callback.map());
this.dao().execute(sql);
return (NutMap)sql.getObject(NutMap.class);
}
public T fetchLinks(String id) {
return this.fetchLinks(this.fetch(id), (String)null);
}
public T fetchLinks(long id) {
return this.fetchLinks(this.fetch(id), (String)null);
}
public T fetchLinks(String id, FieldFilter fieldFilter) {
return Daos.ext(this.dao(), fieldFilter).fetchLinks(this.fetch(id), (String)null);
}
public T fetchLinks(long id, FieldFilter fieldFilter) {
return Daos.ext(this.dao(), fieldFilter).fetchLinks(this.fetch(id), (String)null);
}
}
@@ -0,0 +1,69 @@
package io.v.nutz.base.starter;
import io.v.nutz.base.annontation.SelectEnum;
import io.v.nutz.base.service.AsyncService;
import io.v.nutz.base.service.impl.ViServiceImpl;
import io.v.nutz.base.utils.ClassScanner;
import io.v.nutz.base.utils.Enum;
import io.v.nutz.base.utils.EnumUtil;
import io.v.nutz.base.utils.ViResource;
import io.v.nutz.zhgh.data.constant.MatchMethod;
import org.nutz.boot.starter.ServerFace;
import org.nutz.dao.Dao;
import org.nutz.dao.entity.annotation.Table;
import org.nutz.ioc.Ioc;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.util.NutMap;
import java.lang.reflect.Field;
import java.util.*;
@IocBean
public class ViStarter implements ServerFace {
protected static final String PRE = "v-nutz.";
protected static final String BASE_PACKAGE = "io.v.nutz";
public static Boolean ENABLE_VALID_PARAM = false;
@Inject("refer:$ioc")
private Ioc ioc;
@Inject
private Dao dao;
@Inject
private AsyncService asyncService;
@Inject
private PropertiesProxy propertiesProxy;
public ViStarter() {
}
public void start() throws Exception {
this.load();
}
private void load() {
ViResource.ioc = this.ioc;
ViResource.dao = this.dao;
Set<Class<?>> classes = cn.hutool.core.lang.ClassScanner.scanPackageByAnnotation("io.v.nutz", Table.class);
Iterator<Class<?>> iterator = classes.iterator();
while (iterator.hasNext()) {
Class<?> next = iterator.next();
if (!this.ioc.has(next.getSimpleName())) {
ViServiceImpl viService = new ViServiceImpl(this.dao);
viService.setEntityType(next);
this.ioc.addBean(next.getSimpleName(), viService);
}
}
Set<Class> selectEnums = ClassScanner.scan(BASE_PACKAGE, SelectEnum.class);
for (Class cla : selectEnums) {
try {
SelectEnum selectEnum = (SelectEnum) cla.getAnnotation(SelectEnum.class);
ViResource.selectEnums.put(cla.getSimpleName(), Enum.transToList(cla, selectEnum.fields().length > 0 ? Arrays.asList(selectEnum.fields()) : null));
} catch (Exception ignored) {
}
}
}
}
@@ -0,0 +1,131 @@
package io.v.nutz.base.utils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.util.StringUtils;
import org.springframework.util.SystemPropertyUtils;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
/**
* @Author: 1V
* @DateTime: 2020/12/3 18:34
* @Description: TODO
*/
public class ClassScanner implements ResourceLoaderAware {
private final List<TypeFilter> includeFilters = new LinkedList<TypeFilter>();
private final List<TypeFilter> excludeFilters = new LinkedList<TypeFilter>();
private ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
private MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(this.resourcePatternResolver);
public static Set<Class> scan(String[] basePackages,
Class<? extends Annotation>... annotations) {
ClassScanner cs = new ClassScanner();
if (ArrayUtils.isNotEmpty(annotations)) {
for (Class anno : annotations) {
cs.addIncludeFilter(new AnnotationTypeFilter(anno));
}
}
Set<Class> classes = new HashSet<Class>();
for (String s : basePackages) {
classes.addAll(cs.doScan(s));
}
return classes;
}
public static Set<Class> scan(String basePackages, Class<? extends Annotation>... annotations) {
return ClassScanner.scan(StringUtils.tokenizeToStringArray(basePackages, ",; \t\n"), annotations);
}
public final ResourceLoader getResourceLoader() {
return this.resourcePatternResolver;
}
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourcePatternResolver = ResourcePatternUtils
.getResourcePatternResolver(resourceLoader);
this.metadataReaderFactory = new CachingMetadataReaderFactory(
resourceLoader);
}
public void addIncludeFilter(TypeFilter includeFilter) {
this.includeFilters.add(includeFilter);
}
public void addExcludeFilter(TypeFilter excludeFilter) {
this.excludeFilters.add(0, excludeFilter);
}
public void resetFilters(boolean useDefaultFilters) {
this.includeFilters.clear();
this.excludeFilters.clear();
}
public Set<Class> doScan(String basePackage) {
Set<Class> classes = new HashSet<Class>();
try {
String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
+ org.springframework.util.ClassUtils
.convertClassNameToResourcePath(SystemPropertyUtils
.resolvePlaceholders(basePackage))
+ "/**/*.class";
Resource[] resources = this.resourcePatternResolver
.getResources(packageSearchPath);
for (int i = 0; i < resources.length; i++) {
Resource resource = resources[i];
if (resource.isReadable()) {
MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(resource);
if ((includeFilters.size() == 0 && excludeFilters.size() == 0)
|| matches(metadataReader)) {
try {
classes.add(Class.forName(metadataReader
.getClassMetadata().getClassName()));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
} catch (IOException ex) {
throw new BeanDefinitionStoreException(
"I/O failure during classpath scanning", ex);
}
return classes;
}
protected boolean matches(MetadataReader metadataReader) throws IOException {
for (TypeFilter tf : this.excludeFilters) {
if (tf.match(metadataReader, this.metadataReaderFactory)) {
return false;
}
}
for (TypeFilter tf : this.includeFilters) {
if (tf.match(metadataReader, this.metadataReaderFactory)) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,136 @@
package io.v.nutz.base.utils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.nutz.lang.Times;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
/**
* Created by wizzer on 2016/6/24.
*/
public class DateUtil {
private static final Locale DEFAULT_LOCALE = Locale.CHINA;
private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static Integer getYear() {
return Calendar.getInstance().get(Calendar.YEAR);
}
/**
* 获取当前时间(HH:mm:ss)
*
* @return
*/
public static String getDate() {
return DateFormatUtils.format(new Date(), "yyyy-MM-dd", DEFAULT_LOCALE);
}
/**
* 获取当前时间(HH:mm:ss)
*
* @return
*/
public static String getTime() {
return DateFormatUtils.format(new Date(), "HH:mm:ss", DEFAULT_LOCALE);
}
/**
* 获取当前时间(yyyy-MM-dd HH:mm:ss)
*
* @return
*/
public static String getDateTime() {
return DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss", DEFAULT_LOCALE);
}
/**
* 转换日期格式(yyyy-MM-dd HH:mm:ss)
*
* @param date
* @return
*/
public static String formatDateTime(Date date) {
if (date == null) return "";
return DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss", DEFAULT_LOCALE);
}
/**
* 转换日期格式(yyyy-MM-dd HH:mm:ss)
*
* @param date
* @param f
* @return
*/
public static String format(Date date, String f) {
if (date == null) return "";
return DateFormatUtils.format(date, f, DEFAULT_LOCALE);
}
/**
* 时间戳日期
*
* @param time
* @return
*/
public static String getDate(long time) {
return DateFormatUtils.format(new Date(time * 1000), "yyyy-MM-dd HH:mm:ss", DEFAULT_LOCALE);
}
/**
* 时间戳日期
*
* @param time
* @param f
* @return
*/
public static String getDate(long time, String f) {
return DateFormatUtils.format(new Date(time * 1000), f, DEFAULT_LOCALE);
}
/**
* 通过字符串时间获取时间戳 nutzwk5.0改为long
*
* @param date
* @return
*/
public static long getTime(String date) {
try {
return Times.parse(sdf, date).getTime() / 1000;
} catch (ParseException e) {
return 0;
}
}
/**
* 通过字符串时间获取时间戳 nutzwk5.0改为long
*
* @param date
* @return
*/
public static long getTime(SimpleDateFormat sdf, String date) {
try {
return Times.parse(sdf, date).getTime() / 1000;
} catch (ParseException e) {
return 0;
}
}
/**
* 通过字符串时间转时间戳
*
* @param data
* @return
*/
public static long formatDate(String data) {
try {
return new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(data).getTime();
} catch (ParseException e) {
e.printStackTrace();
return 0;
}
}
}
@@ -0,0 +1,199 @@
package io.v.nutz.base.utils;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import java.io.*;
/**
* 文档转换util
*/
public class DocConverter {
private static final int environment = 1;// 环境1windows,2:linux(涉及pdf2swf路径问题)
private String fileString;
private String outputPath = "";// 输入路径,如果不设置就输出在默认位置
private String fileName;
private File pdfFile;
private File swfFile;
private File docFile;
public DocConverter(String fileString) {
ini(fileString);
}
/*
* 重新设置 file @param fileString
*/
public void setFile(String fileString) {
ini(fileString);
}
/*
* 初始化 @param fileString
*/
private void ini(String fileString) {
this.fileString = fileString;
fileName = fileString.substring(0, fileString.lastIndexOf("."));
docFile = new File(fileString);
pdfFile = new File(fileName + ".pdf");
swfFile = new File(fileName + ".swf");
}
/*
* 转为PDF @param file
*/
private void doc2pdf() throws Exception {
if (docFile.exists()) {
if (!pdfFile.exists()) {
OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
try {
connection.connect();
DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
converter.convert(docFile, pdfFile);
// close the connection
connection.disconnect();
System.out.println("****pdf转换成功,PDF输出:" + pdfFile.getPath() + "****");
} catch (java.net.ConnectException e) {
// ToDo Auto-generated catch block
e.printStackTrace();
System.out.println("****swf转换异常,openoffice服务未启动!****");
throw e;
} catch (com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException e) {
e.printStackTrace();
System.out.println("****swf转换器异常,读取转换文件失败****");
throw e;
} catch (Exception e) {
e.printStackTrace();
throw e;
}
} else {
System.out.println("****已经转换为pdf,不需要再进行转化****");
}
} else {
System.out.println("****swf转换器异常,需要转换的文档不存在,无法转换****");
}
}
/*
* 转换成swf
*/
private void pdf2swf() throws Exception {
Runtime r = Runtime.getRuntime();
if (!swfFile.exists()) {
if (pdfFile.exists()) {
if (environment == 1)// windows环境处理
{
try {
// 这里根据SWFTools安装路径需要进行相应更改
Process p = r.exec("D:\\ewm\\hj\\pdf2swf\\pdf2swf.exe " + pdfFile.getPath() + " -o " + swfFile.getPath() + " -T 9");
System.out.print(loadStream(p.getInputStream()));
System.err.print(loadStream(p.getErrorStream()));
System.out.print(loadStream(p.getInputStream()));
System.err.println("****swf转换成功,文件输出:" + swfFile.getPath() + "****");
// if (pdfFile.exists()) {
// pdfFile.delete();
// }
} catch (Exception e) {
e.printStackTrace();
throw e;
}
} else if (environment == 2)// linux环境处理
{
try {
Process p = r.exec("pdf2swf " + pdfFile.getPath() + " -o " + swfFile.getPath() + " -T 9");
System.out.print(loadStream(p.getInputStream()));
System.err.print(loadStream(p.getErrorStream()));
System.err.println("****swf转换成功,文件输出:" + swfFile.getPath() + "****");
if (pdfFile.exists()) {
pdfFile.delete();
}
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
} else {
System.out.println("****pdf不存在,无法转换****");
}
} else {
System.out.println("****swf已存在不需要转换****");
}
}
static String loadStream(InputStream in) throws IOException {
int ptr = 0;
//把InputStream字节流 替换为BufferedReader字符流 2013-07-17修改
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder buffer = new StringBuilder();
while ((ptr = reader.read()) != -1) {
buffer.append((char) ptr);
}
return buffer.toString();
}
/*
* 转换主方法
*/
public boolean conver() {
if (swfFile.exists()) {
System.out.println("****swf转换器开始工作,该文件已经转换为swf****");
return true;
}
if (environment == 1) {
System.out.println("****swf转换器开始工作,当前设置运行环境windows****");
} else {
System.out.println("****swf转换器开始工作,当前设置运行环境linux****");
}
try {
doc2pdf();
pdf2swf();
} catch (Exception e) {
// TODO: Auto-generated catch block
e.printStackTrace();
return false;
}
if (swfFile.exists()) {
return true;
} else {
return false;
}
}
/*
* 返回文件路径 @param s
*/
public String getswfPath() {
if (swfFile.exists()) {
String tempString = swfFile.getPath();
tempString = tempString.replaceAll("\\\\", "/");
return tempString;
} else {
return "";
}
}
/*
* 设置输出路径
*/
public void setOutputPath(String outputPath) {
this.outputPath = outputPath;
if (!outputPath.equals("")) {
String realName = fileName.substring(fileName.lastIndexOf("/"), fileName.lastIndexOf("."));
if (outputPath.charAt(outputPath.length()) == '/') {
swfFile = new File(outputPath + realName + ".swf");
} else {
swfFile = new File(outputPath + realName + ".swf");
}
}
}
public static void main(String s[]) {
DocConverter d = new DocConverter("C:\\Users\\mayn\\Desktop\\安全管理系统.docx");
d.conver();
}
}
@@ -0,0 +1,42 @@
package io.v.nutz.base.utils;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import lombok.extern.slf4j.Slf4j;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.Param;
import java.io.File;
/**
* TODO
*
* @Author zhf
* @Date 2022/7/20 13:42
*/
@IocBean
@Slf4j
public class EmailUtil {
public void send(@Param("email") String email, String content, boolean isHtml, File... files) {
try {
MailAccount account = new MailAccount();
account.setHost("smtp.163.com");
account.setPort(25);
account.setSslEnable(false);
account.setStarttlsEnable(false);
account.setAuth(true);
account.setFrom("87785588@163.com");
account.setUser("87785588@163");
account.setPass("NMRRJRHMTCOOLPQV");
String msgId = MailUtil.send(account, email, "智慧工会", content, isHtml,files);
log.debug("邮件发送状态:{},id:{}", "发送成功", msgId);
} catch (Exception e) {
log.debug("邮件发送异常信息:{}", e.getMessage());
throw e;
}
}
}
@@ -0,0 +1,65 @@
package io.v.nutz.base.utils;
import cn.hutool.core.util.ReflectUtil;
import org.nutz.lang.util.NutMap;
import org.springframework.util.Assert;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
/**
* Todo
*
* @author 1V
* @date 2021/1/25
* @since 1.0
*/
public class Enum {
public static <E, C> E instance(Class<E> enumClass, C code) {
Assert.isTrue(enumClass.isEnum(), String.format("%s not a enum", enumClass.getSimpleName()));
Object[] enumConstants = enumClass.getEnumConstants();
Field[] fields = ReflectUtil.getFields(enumClass);
for (Object object : enumConstants) {
for (Field field : fields) {
field.setAccessible(true);
try {
if (code.equals(field.get(object))) {
return (E) object;
}
} catch (IllegalAccessException ignored) {
}
}
}
return null;
}
public static <E> List<NutMap> transToList(Class<E> enumClass) {
return transToList(enumClass, null);
}
public static <E> List<NutMap> transToList(Class<E> enumClass, List<String> fieldNames) {
Assert.isTrue(enumClass.isEnum(), String.format("%s not a enum", enumClass.getSimpleName()));
List<NutMap> result = new ArrayList<>();
Object[] enumConstants = enumClass.getEnumConstants();
Field[] fields = ReflectUtil.getFields(enumClass);
for (Object enumConstant : enumConstants) {
NutMap map = NutMap.NEW();
for (Field field : fields) {
if (fieldNames != null && !fieldNames.contains(field.getName())) {
continue;
}
try {
field.setAccessible(true);
map.setv(field.getName(), field.get(enumConstant));
} catch (IllegalAccessException ignored) {
}
}
result.add(map);
}
return result;
}
}
@@ -0,0 +1,57 @@
package io.v.nutz.base.utils;
import org.apache.commons.lang.StringUtils;
import org.nutz.lang.util.NutMap;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class EnumUtil {
public static List<NutMap> enumToListMap(Class<?> clazz) {
List<NutMap> resultList = null;
// 判断是否是枚举类型
if ("java.lang.Enum".equals(clazz.getSuperclass().getCanonicalName())) {
resultList = new ArrayList<>();
// 获取所有public方法
Method[] methods = clazz.getMethods();
List<Field> fieldList = new ArrayList<>();
for (int i = 0; i < methods.length; i++) {
String methodName = methods[i].getName();
if (methodName.startsWith("get") && !"getDeclaringClass".equals(methodName)
&& !"getClass".equals(methodName)) { // 找到枚举类中的以get开头的(并且不是父类已定义的方法)所有方法
Field field = null;
try {
field = clazz.getDeclaredField(StringUtils.uncapitalize(methodName.substring(3))); // 通过方法名获取自定义字段
} catch (NoSuchFieldException | SecurityException e) {
e.printStackTrace();
}
if (field != null) { // 如果不为空则添加到fieldList集合中
fieldList.add(field);
}
}
}
if (!fieldList.isEmpty()) { // 判断fieldList集合是否为空
NutMap map = null;
Enum[] enums = (Enum[])clazz.getEnumConstants(); // 获取所有枚举
for (int i = 0; i < enums.length; i++) {
map = new NutMap();
for (int l = 0, len = fieldList.size(); l < len; l++) {
Field field = fieldList.get(l);
field.setAccessible(true);
try {
map.put(field.getName(), field.get(enums[i])); // 向map集合添加字段名称 和 字段值
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
resultList.add(map);// 将Map添加到集合中
}
}
}
return resultList;
}
}
@@ -0,0 +1,84 @@
package io.v.nutz.base.utils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.InputStream;
public class ExcelUtil {
/**
* 导出Excel
* @param sheetName sheet名称
* @param title 标题
* @param values 内容
* @param wb HSSFWorkbook对象
* @return
*/
public static HSSFWorkbook getHSSFWorkbook(String sheetName, String []title, String [][]values, HSSFWorkbook wb){
// 第一步,创建一个HSSFWorkbook,对应一个Excel文件
if(wb == null){
wb = new HSSFWorkbook();
}
// 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
HSSFSheet sheet = wb.createSheet(sheetName);
// sheet.setColumnWidth(0, 3766);
// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
HSSFRow row = sheet.createRow(0);
// 第四步,创建单元格,并设置值表头 设置表头居中
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
/*style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
style.setBorderTop(HSSFCellStyle.BORDER_THIN); //上边框
style.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
style.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框*/
HSSFFont font = wb.createFont();
font.setFontName("黑体");
font.setFontHeightInPoints((short) 12);//设置字体大小
style.setFont(font);
//声明列对象
HSSFCell cell = null;
//创建标题
for(int i=0;i<title.length;i++){
cell = row.createCell(i);
cell.setCellValue(title[i]);
cell.setCellStyle(style);
sheet.autoSizeColumn(i);
sheet.setColumnWidth(i, sheet.getColumnWidth(i) * 35 / 10);
}
HSSFCellStyle style1 = wb.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
//style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//创建内容
for(int i=0;i<values.length;i++){
row = sheet.createRow(i + 1);
for(int j=0;j<values[i].length;j++){
HSSFCell cellx = row.createCell(j);
//将内容按顺序赋给对应的列对象
cellx.setCellValue(values[i][j]);
//样式
cellx.setCellStyle(style1);
}
}
return wb;
}
}
@@ -0,0 +1,87 @@
package io.v.nutz.base.utils;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.wizzer.framework.base.Result;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.nutz.integration.jedis.RedisService;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.util.NutMap;
/**
* @ClassName ExpressSelectUtil
* @Description TODO
* @Author zhf
* @Date 2024/5/8 17:39
*/
@IocBean
@Slf4j
public class ExpressSelectUtil {
//快递信息url
private static final String URL = "https://eolink.o.apispace.com/wlgj1/paidtobuy_api/trace_search";
//获取快递公司codeURL
private static final String EXPRESS_COMPANY_URL = "https://eolink.o.apispace.com/wlgj1/paidtobuy_api/mail_discern";
private static final String TOKEN = "vvzpibv7yzp2l89noyp8ut7tdjqqf1fq";
public JSONObject getExpressInfo(String mailNo, String tel) {
if (StrUtil.isBlank(mailNo) || StrUtil.isBlank(tel)) {
// return Result.error("获取物流信息参数错误");
throw new RuntimeException("获取物流信息参数错误");
}
String expressCompanyCode = getExpressCompanyCode(mailNo);
if (StrUtil.isBlank(expressCompanyCode)) {
// return Result.error("获取物流公司代码失败");
throw new RuntimeException("获取物流信息参数错误");
}
NutMap map = new NutMap();
map.setv("cpCode", expressCompanyCode);
map.setv("mailNo", mailNo);
map.setv("tel", tel);
String body = HttpUtil.createPost(URL).header("X-APISpace-Token", TOKEN)
.body(JSON.toJSONString(map))
.execute().body();
JSONObject jsonBody = JSON.parseObject(body);
if (jsonBody.getBoolean("success")) {
JSONObject logisticsTrace = JSON.parseObject(jsonBody.getString("logisticsTrace"));
// return Result.success(logisticsTrace);
return logisticsTrace;
} else {
//失败才返回
// return Result.error(jsonBody.getString("msg"));
throw new RuntimeException(jsonBody.getString("msg"));
}
}
public String getExpressCompanyCode(String mailNo) {
NutMap map = new NutMap();
map.setv("mailNo", mailNo);
String body = HttpUtil.createPost(EXPRESS_COMPANY_URL).header("X-APISpace-Token", TOKEN)
.header("Content-Type", "application/json")
.body(JSON.toJSONString(map))
.execute().body();
JSONObject jsonBody = JSON.parseObject(body);
if (jsonBody.getBoolean("success")) {
JSONArray expressCompanyList = jsonBody.getJSONArray("expressCompanyList");
JSONObject expressCompany = JSON.parseObject(JSON.toJSONString(expressCompanyList.get(0)));
return expressCompany.getString("cpCode");
} else {
return null;
}
}
}
@@ -0,0 +1,69 @@
package io.v.nutz.base.utils;
import io.v.nutz.base.service.BaseService;
import org.nutz.boot.starter.ftp.FtpService;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.entity.Record;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.random.R;
import org.nutz.mvc.upload.TempFile;
/**
* TODO
*
* @author 赵欣雨
* @date 2020/8/18 11:35
*/
@IocBean
public class FileService {
@Inject
private BaseService baseService;
@Inject
private FtpService ftpService;
/**
* @param file 文件
* @param id 关联表id
* @param filePath 文件主路径
*/
public void upload(TempFile file, String id, String filePath) {
try {
String submittedFileName = file.getSubmittedFileName();
String fileType = submittedFileName.substring(submittedFileName.lastIndexOf(".")).toLowerCase();
String fileName = System.currentTimeMillis() + fileType;
ftpService.upload(filePath, fileName, file.getInputStream());
Chain fileChain = Chain.make("id", R.UU32()).add("reid", id).add("filename", submittedFileName).add("filepath", filePath + fileName);
baseService.insert("sys_file", fileChain);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param fileid
* @param filePath
*/
public void delete(String fileid, String filePath) {
try {
Record filedata = baseService.dao().fetch("sys_file", Cnd.where("id", "=", fileid).or("filepath", "=", filePath));
// baseService.clear("sys_file",Cnd.where("id", "=", filedata.getString("id")));
if (null == fileid) {
baseService.clear("sys_file", Cnd.where("filepath", "=", filedata.getString("filepath")));
} else {
baseService.clear("sys_file", Cnd.where("id", "=", filedata.getString("id")));
}
// ftpService.delete(filedata.getString("filepath"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,70 @@
package io.v.nutz.base.utils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Whitelist;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.ParserDelegator;
import java.io.*;
/**
* @author: Aaron
* @create: 2020-10-12 21:13
* @description:
**/
public class Html2Text extends HTMLEditorKit.ParserCallback {
private static Html2Text html2Text = new Html2Text();
StringBuffer s;
public Html2Text() {
}
public void parse(String str) throws IOException {
InputStream iin = new ByteArrayInputStream(str.getBytes());
Reader in = new InputStreamReader(iin);
s = new StringBuffer();
ParserDelegator delegator = new ParserDelegator();
delegator.parse(in, this, Boolean.TRUE);
iin.close();
in.close();
}
@Override
public void handleText(char[] text, int pos) {
s.append(text);
}
public String getText() {
return s.toString();
}
public static String getContent(String str) {
try {
html2Text.parse(str);
} catch (IOException e) {
e.printStackTrace();
}
return html2Text.getText();
}
public static String toPlainText(String html) {
if (StringUtils.isEmpty(html)) {
return "";
}
Document document = Jsoup.parse(html);
Document.OutputSettings outputSettings = new Document.OutputSettings().prettyPrint(false);
document.outputSettings(outputSettings);
document.select("br").append("\\n");
document.select("p").prepend("\\n");
document.select("p").append("\\n");
String newHtml = document.html().replaceAll("\\\\n", "\n");
String plainText = Jsoup.clean(newHtml, "", Whitelist.none(), outputSettings);
String result = StringEscapeUtils.unescapeHtml(plainText.trim());
return result;
}
}
@@ -0,0 +1,93 @@
package io.v.nutz.base.utils;
import io.v.nutz.sys.models.Sys_log;
import io.v.nutz.sys.models.Sys_user;
import io.v.nutz.sys.services.SysUserService;
import io.v.nutz.web.commons.shiro.token.PlatformCaptchaToken;
import io.v.nutz.web.commons.slog.SLogService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ThreadContext;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Lang;
import org.nutz.lang.Times;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* 登录方法
*
* @author jug
* @date 2023/07/06
*/
@IocBean
public class LoginUtil {
public enum LoginOrigin {
APP, WEB, WEB_H5, CAS, QI_YE_WEI_XIN, WEI_XIN;
}
@Inject
private SLogService sLogService;
@Inject
private SysUserService sysUserService;
/**
* 密码登录
*
* @param token 令牌
* @param request 请求
* @param session 会话
* @param loginOrigin 登录起源
*/
public void doLogin(AuthenticationToken token, HttpServletRequest request, HttpSession session, LoginOrigin loginOrigin) {
//设置登录源
PlatformCaptchaToken platformCaptchaToken = (PlatformCaptchaToken) token;
platformCaptchaToken.setLoginOrigin(loginOrigin);
//session失效咯
if (token == null) {
throw new RuntimeException("login.error.system");
}
Subject subject = SecurityUtils.getSubject();
ThreadContext.bind(subject);
subject.login(token);
Sys_user user = (Sys_user) subject.getPrincipal();
int count = user.getLoginCount() == null ? 0 : user.getLoginCount();
org.nutz.dao.Chain userUpdateChain = Chain.make("loginIp", user.getLoginIp()).add("loginAt", Times.getTS()).add("loginCount", count + 1).add("userOnline", true).add("loginSessionId", session.getId());
sysUserService.update(userUpdateChain, Cnd.where("id", "=", user.getId()));
Sys_log sysLog = new Sys_log();
sysLog.setType("info");
sysLog.setTag("用户登陆:" + loginOrigin);
sysLog.setSrc(this.getClass().getName() + "#doLogin");
sysLog.setMsg("成功登录系统!");
sysLog.setIp(Lang.getIP(request));
sysLog.setCreatedBy(user.getId());
sysLog.setUsername(user.getUsername());
sysLog.setLoginname(user.getLoginname());
sLogService.async(sysLog);
}
/**
* 用户名登录
*
* @param loginName 登录名
* @param request 请求
* @param session 会话
* @param loginOrigin 登录起源
*/
public void doLogin(String loginName, HttpServletRequest request, HttpSession session, LoginOrigin loginOrigin) {
PlatformCaptchaToken token = new PlatformCaptchaToken(loginName, loginOrigin);
token.setLoginOrigin(loginOrigin);
doLogin(token, request, session, loginOrigin);
}
}
@@ -0,0 +1,82 @@
package io.v.nutz.base.utils;
import io.v.nutz.base.config.ThreadPoolConfig;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import java.util.List;
/**
* @version 1.0
* @Author zzr
* @nameManyAddOrRenewUtil
* @Date 2024/7/24 16:16
* @注释
*/
@IocBean
public class ManyAddOrRenewUtil {
@Inject
private ThreadPoolConfig threadPoolConfig;
/**
* 批量快速插入,异步执行
*
* @param list 泛型list,任意实体类集合
* @param batchSize 期望单次操作的数量,默认200
* @param <T>
*/
public <T> void asyncExecuteFastInsert(List<T> list, Integer batchSize) {
threadPoolConfig.asyncExecute(list, batchSize, "insert", true);
}
/**
* 批量插入(非快速),异步执行
*
* @param list 泛型list,任意实体类集合
* @param batchSize 期望单次操作的数量,默认200
* @param <T>
*/
public <T> void asyncExecuteInsert(List<T> list, Integer batchSize) {
threadPoolConfig.asyncExecute(list, batchSize, "insert", true);
}
/**
* 批量修改(忽略空值),异步执行
*
* @param list 泛型list,任意实体类集合
* @param batchSize 期望单次操作的数量,默认200
* @param <T>
*/
public <T> void asyncExecuteUpdateIgnoreNull(List<T> list, Integer batchSize) {
threadPoolConfig.asyncExecute(list, batchSize, "update", true);
}
/**
* 批量修改(不忽略空值),异步执行
*
* @param list 泛型list,任意实体类集合
* @param batchSize 期望单次操作的数量,默认200
* @param <T>
*/
public <T> void asyncExecuteUpdate(List<T> list, Integer batchSize) {
threadPoolConfig.asyncExecute(list, batchSize, "update", false);
}
/**
* 新增或修改,异步执行
*
* @param list 泛型list,任意实体类集合
* @param batchSize 期望单次操作的数量,默认200
* @param <T>
*/
public <T> void asyncExecuteInsertOrUpdate(List<T> list, Integer batchSize) {
threadPoolConfig.asyncExecute(list, batchSize, "insertOrUpdate", false);
}
}
@@ -0,0 +1,33 @@
package io.v.nutz.base.utils;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
/**
* Created by wizzer on 2017/7/21.
*/
public class MapUtil {
/**
* 使用 Map按key进行排序
*
* @param map
* @return
*/
public static Map<String, Object> sortMapByKey(Map<String, Object> map) {
if (map == null || map.isEmpty()) {
return null;
}
Map<String, Object> sortMap = new TreeMap<>(
new MapKeyComparator());
sortMap.putAll(map);
return sortMap;
}
}
class MapKeyComparator implements Comparator<String> {
@Override
public int compare(String str1, String str2) {
return str1.compareTo(str2);
}
}
@@ -0,0 +1,129 @@
package io.v.nutz.base.utils;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.v.nutz.base.enums.Env;
import io.v.nutz.web.commons.base.Globals;
import lombok.extern.slf4j.Slf4j;
import org.nutz.integration.jedis.RedisService;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.lang.Lang;
import org.nutz.lang.util.NutMap;
import java.util.List;
/**
* @author zxy
* @Description 消息API
* @createTime 2022年01月27日 11:20:00
*/
@IocBean
@Slf4j
public class MsgApi {
/**
* token -redis - name
*/
private static final String MSG_TOKEN_NAME = "msg_token";
private static final String APP_KEY = "10c51794-45b8-4de5-ba6f-b1ed843c20f3";
private static final String APP_SECRET = "4acbf17e-4b17-4c47-b4bb-1576a066250a";
/**
* 发送消息api
*/
private static final String MSG_API = "https://xxdb.hmc.edu.cn/msgInfo/pushMsgInfo";
private static final String TOKEN_API = "https://xxdb.hmc.edu.cn/accessSystem/getAccessToken";
@Inject
private RedisService redisService;
/**
* @param channels 推送渠道 (INNER:站内消息; SMS:短信; Mail:邮件; WeChat:微信; DingTalk:钉钉;同时推送多个渠道用英文逗号分隔 )
* @param loginNameStr 字符串,多个工号用英文逗号分隔 ","
* @param mtype 消息类型; 0: 图文 1: 文字 2: 外链
* @param title 标题
* @param content 内容
* @param imageUrl 图片URL
* @author zhf
* @description
*/
public void sendMsg(List<String> channels, String loginNameStr, Integer mtype, String title, String content, String imageUrl,String link) {
// try {
// if (!Globals.MyConfig.getBoolean("SendMsg")) {
// log.info("发送失败,消息暂未开启!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
// return;
// }
//
// if (Globals.isEnv(Env.dev)) {
// log.info("开发模式不允许发送短信!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
// return;
// }
//
// if (StrUtil.isBlank(title)||StrUtil.isBlank(content) ||Lang.isEmpty(channels) || Lang.isEmpty(loginNameStr)) {
// log.info("发送失败,缺少需要参数请检查!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
// return;
// }
//
// String msgToken = getMsgToken();
// NutMap map = new NutMap();
// map.put("channel", String.join(",", channels));
// //推送范围(1:普通模式;2:全体教师;3:全体学生;4:全体人员)
// map.put("objScope", 1);
// map.put("objIds", loginNameStr);
// map.put("mtype", mtype);
// map.put("sendStatus", 1);
// map.put("title", title);
// map.put("content", content);
// map.put("imageUrl", imageUrl);
// map.put("link", link);
//
// HttpRequest request = HttpUtil.createPost(MSG_API)
// .header("token", msgToken)
// .body(Json.toJson(map));
// JSONObject jsonObject = JSON.parseObject(request.execute().body());
// int status = jsonObject.getInteger("code");
//
// if (status == 200) {
// log.info("发送成功>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
// } else {
// log.info("发送失败>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
// throw new RuntimeException("Message sending failed with status code: " + status + ", Message: " + jsonObject.getString("message"));
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
}
/**
* 获取token
*
* @return
*/
private String getMsgToken() {
String token = redisService.get(MSG_TOKEN_NAME);
if (StrUtil.isBlank(token)) {
String body = HttpRequest.post(TOKEN_API + "?appKey=" + APP_KEY + "&appSecret=" + APP_SECRET).execute().body();
NutMap map = Json.fromJson(NutMap.class, body);
if (map.getInt("code") == 200) {
NutMap data = Json.fromJson(NutMap.class, map.getString("data"));
token = data.getString("accessToken");
redisService.setex(MSG_TOKEN_NAME, 3600, token);
} else {
token = "";
}
}
return token;
}
}
@@ -0,0 +1,59 @@
package io.v.nutz.base.utils;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter;
import java.io.File;
import java.net.ConnectException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @Author zxy
* Date 2019/10/17
**/
public class Office2Pdf {
public static boolean officeToPDF(String sourceFile, String destFile) {
try {
File inputFile = new File(sourceFile);
if (!inputFile.exists()) {
// 找不到源文件, 则返回false
return false;
}
// 如果目标路径不存在, 则新建该路径
File outputFile = new File(destFile);
if (!outputFile.getParentFile().exists()) {
outputFile.getParentFile().mkdirs();
}
//如果目标文件存在,则删除
if (outputFile.exists()) {
outputFile.delete();
}
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
OpenOfficeConnection connection = new SocketOpenOfficeConnection("127.0.0.1", 8100);
connection.connect();
//用于测试openOffice连接时间
System.out.println("连接时间:" + df.format(new Date()));
/*DocumentConverter converter = new StreamOpenOfficeDocumentConverter(
connection);*/
DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
converter.convert(inputFile, outputFile);
//测试word转PDF的转换时间
System.out.println("转换时间:" + df.format(new Date()));
connection.disconnect();
return true;
} catch (ConnectException e) {
e.printStackTrace();
System.err.println("openOffice连接失败!请检查IP,端口");
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
@@ -0,0 +1,98 @@
package io.v.nutz.base.utils;
import cn.hutool.core.io.FileUtil;
import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 文档转换
*/
@Slf4j
public class OfficePlusUtil {
/**
* 转换
*
* @param sourcePath 源文件路径
* @param targetPath 目标文件路径
*/
public static void convert(String sourcePath, String targetPath) {
String suffix = FileUtil.getSuffix(sourcePath);
if (suffix.equals("doc") || suffix.equals("docx")) {
wordConvertPdf(sourcePath, targetPath);
} else if (suffix.equals("xls") || suffix.equals("xlsx")) {
excelConvertPdf(sourcePath, targetPath);
} else {
throw new RuntimeException("不支持的文档格式");
}
}
/**
* excel转pdf
*
* @param sourcePath 源文件路径
* @param targetPath 目标文件路径
*/
public static void excelConvertPdf(String sourcePath, String targetPath) {
FileOutputStream fileOS = null;
try {
Workbook wb = new Workbook(sourcePath);
fileOS = new FileOutputStream(targetPath);
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
pdfSaveOptions.setOnePagePerSheet(true);
// for (int i = 0; i < 3; i++) {
// wb.getWorksheets().get(i).getHorizontalPageBreaks().clear();
// wb.getWorksheets().get(i).getVerticalPageBreaks().clear();
// }
// for (int i = 1; i < wb.getWorksheets().getCount(); i++) {
// wb.getWorksheets().get(i).setVisible(false);
// }
wb.getWorksheets().get(0).setVisible(true);
wb.save(fileOS, pdfSaveOptions);
fileOS.flush();
} catch (Exception e) {
log.info("转换pdf报错", e);
} finally {
if (fileOS != null) {
try {
fileOS.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* word转pdf
*
* @param sourcePath 源文件路径
* @param targetPath 目标文件路径
*/
public static void wordConvertPdf(String sourcePath, String targetPath) {
FileOutputStream os = null;
try {
File file = new File(targetPath);
os = new FileOutputStream(file);
Document doc = new Document(sourcePath);
doc.save(os, SaveFormat.PDF);
} catch (Exception e) {
log.info("转换pdf报错", e);
} finally {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@@ -0,0 +1,79 @@
package io.v.nutz.base.utils;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import io.v.nutz.sys.models.Sys_office_template;
import lombok.extern.slf4j.Slf4j;
import org.nutz.boot.starter.ftp.FtpService;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
@IocBean
@Slf4j
public class OfficeTemplateUtil {
@Inject
private FtpService ftpService;
@Inject
private Dao dao;
public String getPath(String templateCode) throws IOException {
if (StrUtil.isBlank(templateCode)) {
throw new NullPointerException("templateCode is null");
}
if (StrUtil.isNotBlank(templateCode)) {
Sys_office_template officeTemplate = dao.fetch(Sys_office_template.class, Cnd.where("templateCode", "=", templateCode));
if (null == officeTemplate) {
throw new RuntimeException("officeTemplate is null,please check [templateCode] is right?");
}
String templatePath = officeTemplate.getTemplatePath();
String templateName = officeTemplate.getTemplateName();
String extName = FileUtil.extName(templateName);
Path localTempFilePath = Files.createTempFile(null, "." + extName);
File localTempFile = localTempFilePath.toFile();
FileOutputStream outputStream = new FileOutputStream(localTempFile);
ftpService.download(templatePath, outputStream);
//一分钟后删除临时文件 哈哈哈🙉🙉🙉🙉🙉🙉🙉🙉
new Thread(() -> {
try {
Thread.sleep(1000 * 60);
FileUtil.del(localTempFile);
log.info(">>>>>>>>>>>>临时文件删除成功");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}, "OfficeTemplateUtil_deleteTemp").start();
return localTempFilePath.toString();
}
return null;
}
public InputStream getInputStream(String templateCode) throws IOException {
if (StrUtil.isBlank(templateCode)) {
throw new NullPointerException("templateCode is null");
}
if (StrUtil.isNotBlank(templateCode)) {
Sys_office_template officeTemplate = dao.fetch(Sys_office_template.class, Cnd.where("templateCode", "=", templateCode));
if (null == officeTemplate) {
throw new RuntimeException("officeTemplate is null,please check [templateCode] is right?");
}
return ftpService.connect().retrieveFileStream(officeTemplate.getTemplatePath());
}
return null;
}
}
@@ -0,0 +1,13 @@
package io.v.nutz.base.utils;
import org.nutz.lang.util.NutMap;
/**
* Created by wizzer on 2018.09
*/
public class PageUtil {
public static String getOrder(String key) {
NutMap map = NutMap.NEW().addv("ascending", "asc").addv("descending", "desc");
return map.getString(key);
}
}
@@ -0,0 +1,392 @@
package io.v.nutz.base.utils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.nutz.ioc.loader.annotation.IocBean;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by wizzer on 2017/5/24.
*/
@IocBean
public class RCSCloudAPI {
/**
* 账号
*/
private static String ACCOUNT_SID = "ZH000000075";
/**
* APIKEY
*/
private static String ACCOUNT_APIKEY = "7987b135-8197-43ed-95a3-7f996e382081";
/**
* utf8编码
*/
private static final String CHARSET_UTF8 = "utf-8";
/**
* HttpUrl
*/
private static String HttpUrl = "http://121.41.114.153:8030/rcsapi/rest";
/**
* 发送模板短信
* @param tplId 模板id
* @param mobile 手机号码
* @param content 参数值,多个参数以“||”隔开 如:@1@=HY001||@2@=3281
* @param extno 自定义扩展码,建议1-4位,需申请开通自定义扩展
* @return json字符串,详细描述请参考接口文档
*
* String
*/
public static String sendTplSms(String tplId,String mobile,String content,String extno){
/* DefaultHttpClient httpclient = new DefaultHttpClient();
String resultJson = "";
try {
//签名:Md5(sid+key+tplid+mobile+content)
StringBuilder signStr = new StringBuilder();
signStr.append(ACCOUNT_SID).append(ACCOUNT_APIKEY).append(tplId).append(mobile).append(content);
//如果含有中文字符,按GB2312编码处理
String sign = md5Digest(changeCharset(signStr.toString(), "utf-8"));
//String sign = md5Digest(changeCharset(signStr.toString(), "GB2312"));
//创建HttpPost请求
HttpPost httppost = new HttpPost(HttpUrl +"/sms/sendtplsms.json");//?sid="+ACCOUNT_SID+"&sign="+sign
//构建form
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("sid", ACCOUNT_SID));
nvps.add(new BasicNameValuePair("sign", sign));
nvps.add(new BasicNameValuePair("tplid", tplId));
nvps.add(new BasicNameValuePair("mobile", mobile));
nvps.add(new BasicNameValuePair("content", content));
nvps.add(new BasicNameValuePair("extno", extno));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvps,CHARSET_UTF8);
httppost.setEntity(entity);
//设置请求表头信息,POST请求必须采用application/x-www-form-urlencoded否则提示415错误
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
httppost.setHeader("Content-Encoding", CHARSET_UTF8);
//执行请求
HttpResponse response = httpclient.execute(httppost);
//获取响应Entity
HttpEntity httpEntity = response.getEntity();
//返回JSON字符串格式,用户根据实际业务进行解析处理
if (httpEntity != null)
resultJson = EntityUtils.toString(httpEntity, CHARSET_UTF8);
EntityUtils.consume(entity);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpclient != null)
httpclient.getConnectionManager().shutdown();
}
System.out.println("resultJson=" +resultJson);
return resultJson;*/
return "";
}
/**
* 查询账号信息
* /user/get.json?sid={sid}&sign={sign}
* @return json字符串,详细描述请参考接口文档
* String
*/
public static String queryUser(){
DefaultHttpClient httpclient = new DefaultHttpClient();
String resultJson = "";
try {
//签名
String sign = md5Digest(ACCOUNT_SID + ACCOUNT_APIKEY);
//请求url
StringBuilder url = new StringBuilder();
url.append(HttpUrl).append("/user/get.json").append("?sid=").append(ACCOUNT_SID).append("&sign=").append(sign);
//GET请求
HttpGet httpget = new HttpGet(url.toString());
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null)
resultJson = EntityUtils.toString(entity, CHARSET_UTF8);
EntityUtils.consume(entity);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpclient != null)
httpclient.getConnectionManager().shutdown();
}
System.out.println("resultJson=" + resultJson);
return resultJson;
}
/**
* 查询账号下所有模板信息
* @return json字符串,详细描述请参考接口文档
* String
*/
public static String queryTpls(){
DefaultHttpClient httpclient = new DefaultHttpClient();
String resultJson = "";
try {
//签名
String sign = md5Digest(ACCOUNT_SID + ACCOUNT_APIKEY);
//请求url
StringBuilder url = new StringBuilder();
url.append(HttpUrl).append("/tpl/gets.json").append("?sid=").append(ACCOUNT_SID).append("&sign=").append(sign);
//Http GET方式
HttpGet httpget = new HttpGet(url.toString());
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null)
resultJson = EntityUtils.toString(entity, CHARSET_UTF8);
EntityUtils.consume(entity);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpclient != null)
httpclient.getConnectionManager().shutdown();
}
System.out.println("resultJson=" + resultJson);
return resultJson;
}
/**
* 查询指定模板
* @param tplId 模板id
* @return json字符串,详细描述请参考接口文档
* String
*/
public static String queryTplById(String tplId){
DefaultHttpClient httpclient = new DefaultHttpClient();
String resultJson = "";
try {
//签名
String sign = md5Digest(ACCOUNT_SID + ACCOUNT_APIKEY + tplId);
//
StringBuilder url = new StringBuilder();
url.append(HttpUrl).append("/tpl/get.json").append("?sid=").append(ACCOUNT_SID).append("&sign=").append(sign).append("&tplid=").append(tplId);
//GET请求
HttpGet httpget = new HttpGet(url.toString());
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null)
resultJson = EntityUtils.toString(entity, CHARSET_UTF8);
EntityUtils.consume(entity);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpclient != null)
httpclient.getConnectionManager().shutdown();
}
System.out.println("resultJson=" + resultJson);
return resultJson;
}
/**
* 查询账号下所有模板信息
* @return
* String
*/
public static String queryRpt(){
DefaultHttpClient httpclient = new DefaultHttpClient();
String resultJson = "";
try {
//签名
String sign = md5Digest(ACCOUNT_SID + ACCOUNT_APIKEY);
//请求url
StringBuilder url = new StringBuilder();
url.append(HttpUrl).append("/sms/queryrpt.json").append("?sid=").append(ACCOUNT_SID).append("&sign=").append(sign);
//GET请求
HttpGet httpget = new HttpGet(url.toString());
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null)
resultJson = EntityUtils.toString(entity, CHARSET_UTF8);
EntityUtils.consume(entity);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpclient != null)
httpclient.getConnectionManager().shutdown();
}
System.out.println("resultJson=" + resultJson);
return resultJson;
}
/**
* 获取上行短信,采用GET方式
* /sms/querymo.json?sid={sid}&sign={sign}
* @return json字符串,详细描述请参考接口文档
* String
*/
public static String queryMo(){
DefaultHttpClient httpclient = new DefaultHttpClient();
String resultJson = "";
try {
//签名
String sign = md5Digest(ACCOUNT_SID + ACCOUNT_APIKEY);
//请求url
StringBuilder url = new StringBuilder();
url.append(HttpUrl).append("/sms/querymo.json").append("?sid=").append(ACCOUNT_SID).append("&sign=").append(sign);
//GET请求
HttpGet httpget = new HttpGet(url.toString());
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null)
resultJson = EntityUtils.toString(entity, CHARSET_UTF8);
EntityUtils.consume(entity);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpclient != null)
httpclient.getConnectionManager().shutdown();
}
System.out.println("resultJson=" + resultJson);
return resultJson;
}
/**
* 校验黑名单,采用GET方式
* /assist/bl.json?sid={sid}&sign={sign}&mobile={mobile}
* @return json字符串,详细描述请参考接口文档
* String
*/
public static String validBL(String mobile){
DefaultHttpClient httpclient = new DefaultHttpClient();
String resultJson = "";
try {
//签名,MD5 32位
String sign = md5Digest(ACCOUNT_SID + ACCOUNT_APIKEY);
StringBuilder url = new StringBuilder();
url.append(HttpUrl).append("/assist/bl.json")
.append("?sid=").append(ACCOUNT_SID)
.append("&sign=").append(sign)
.append("&mobile=").append(mobile);
//GET请求
HttpGet httpget = new HttpGet(url.toString());
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null)
resultJson = EntityUtils.toString(entity, CHARSET_UTF8);
EntityUtils.consume(entity);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpclient != null)
httpclient.getConnectionManager().shutdown();
}
System.out.println("resultJson=" + resultJson);
return resultJson;
}
/**
* 校验敏感词,采用GET方式
* /assist/sw.json?sid={sid}& sign={sign}&content={content}
* @param content 内容
* @return json字符串,详细描述请参考接口文档
*/
public static String validSW(String content){
DefaultHttpClient httpclient = new DefaultHttpClient();
String resultJson = "";
try {
//签名
String sign = md5Digest(ACCOUNT_SID + ACCOUNT_APIKEY);
StringBuilder url = new StringBuilder();
url.append(HttpUrl).append("/assist/sw.json")
.append("?sid=").append(ACCOUNT_SID)
.append("&sign=").append(sign)
.append("&content=").append(content);
//GET请求
HttpGet httpget = new HttpGet(url.toString());
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null)
resultJson = EntityUtils.toString(entity, CHARSET_UTF8);
EntityUtils.consume(entity);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpclient != null)
httpclient.getConnectionManager().shutdown();
}
System.out.println("resultJson=" + resultJson);
return resultJson;
}
/**
* MD5算法
* @param src
* @return
* @throws NoSuchAlgorithmException
* @throws UnsupportedEncodingException
* String
*/
public static String md5Digest(String src) throws NoSuchAlgorithmException, UnsupportedEncodingException{
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] b = md.digest(src.getBytes(CHARSET_UTF8));
return byte2HexStr(b);
}
private static String byte2HexStr(byte[] b){
StringBuilder sb = new StringBuilder();
for (int i = 0; i < b.length; ++i) {
String s = Integer.toHexString(b[i] & 0xFF);
if (s.length() == 1)
sb.append("0");
sb.append(s.toUpperCase());
}
return sb.toString();
}
/**
* 字符编码转换
* @param str
* @param newCharset
* @return
* @throws UnsupportedEncodingException
* String
*/
public static String changeCharset(String str, String newCharset)
throws UnsupportedEncodingException {
if (str != null) {
//用默认字符编码解码字符串。
byte[] bs = str.getBytes();
//用新的字符编码生成字符串
return new String(bs, newCharset);
}
return null;
}
}
@@ -0,0 +1,101 @@
package io.v.nutz.base.utils;
import java.util.*;
/**
* 获取随机子列表
*
* @Author: leven
*/
public class RandomLists {
private static Random r;
/**
* 获取随机子列表
*
* @param source 原列表
* @param limit 子列表长度
* @param <T> 列表原类型
* @return 子列表
*/
public static <T> List<T> newRandomList(List<T> source, int limit) {
if (source == null || source.size() == 0 || source.size() <= limit) {
return source;
}
Set<Integer> set = createRandomSet(source.size(), limit);
Integer[] array = set.toArray(new Integer[0]);
return new RandomList<>(source, array);
}
/**
* 创建一个随机的有序下标Set
*
* @param listSize 原列表长度
* @param limit 子列表长度
* @return 随机的下标Set
*/
private static Set<Integer> createRandomSet(int listSize, int limit) {
Random rnd = r;
if (rnd == null)
r = rnd = new Random();
Set<Integer> set = new HashSet<>(limit);
for (int i = 0; i < limit; i++) {
int value = rnd.nextInt(listSize);
if (!add(set, value, listSize)) {
return set;
}
}
return set;
}
/**
* 往Set中添加一个随机值如果有冲突则取随机值+1
*/
private static boolean add(Set<Integer> set, int value, int size) {
if (set.size() == size) {
return false;
}
if (!set.contains(value)) {
return set.add(value);
}
int nextValue = value + 1;
if (nextValue == size) {
nextValue = 0;
}
return add(set, nextValue, size);
}
private static class RandomList<T> extends AbstractList<T> {
final List<T> list;
final Integer[] indexs;
RandomList(List<T> list, Integer[] indexs) {
this.list = list;
this.indexs = indexs;
}
@Override
public T get(int index) {
if (index < 0 || index >= indexs.length)
throw new IndexOutOfBoundsException("The start index was out of bounds: "
+ index + " >= " + indexs.length);
int start = indexs[index];
return list.get(start);
}
@Override
public int size() {
return indexs.length;
}
@Override
public boolean isEmpty() {
return list.isEmpty();
}
}
}
@@ -0,0 +1,292 @@
package io.v.nutz.base.utils;
/**
* @author V
*/
public interface Roles {
/**
* 会员
*/
String MEMBER = "bf904e661ced4e909dea0fdccdc02b2d";
/**
* 福利会员
*/
String WELFARE_MEMBER = "7bb8f9862eb147c9845cda72eb3dbd3d";
/**
* 院级工会管理员
*/
String UNION_MANGER = "5d342e614e9a48288d50154bcdcc75d3";
/**
* 二级单位负责人
*/
String UNIT_MANGER = "dd35baa967f84bcca823ec7e72be2ec8";
/**
* 福利单位管理员
*/
String WELFARE_UNIT_MANAGE = "bfd195fe366e4f308230259bbe3ca9b8";
/**
* 协会负责人
*/
String CLUB_FZR = "c17d7a777dd24d36b4b268037b959faf";
/**
* 代表团团长
*/
String DBT_TZ = "c1765c03459840c2b621d140f575c869";
/**
* 代表团副团长
*/
String DBT_FTZ = "6445f21685c5489aa212a986cfbeecce";
/**
* 正式代表
*/
String ZSDB = "1427083503b74aa0885d104419b33170";
/**
* 列席代表
*/
String LXDB = "f411b5965d364876830aa6d597491038";
/**
* 特邀代表
*/
String TYDB = "f3ca7ab46f764753b13e4a755ef13265";
/**
* 提案提案委员会委员
*/
String JDH_TA_WXY_WY_ROLE_ID = "2b7194f5b17c4cc8b049ad945e6c6d04";
/**
* 委员会主任
*/
String WYH_ZR = "827d20a5f2cb400ab1dff4335539ee9f";
/**
* 委员会副主任
*/
String WYH_FZR = "c3e67e4f4060499a8ce6dbe0a9bb591e";
/**
* 校领导
*/
String XLD = "153cba3fb88b4c88b7c1002f0eb63749";
/**
* 承办单位负责人
*/
String CONTRACTOR_PERSON = "2b17b5d68c754914b4637dddb66ea4ed";
/**
* 承办单位代理答复人
*/
String CONTRACTOR_PROXY_PERSON = "0853cb676a6644b782b11a21526e0d8f";
/**
* 提案分管校领导
*/
String IN_CHARGE_LEADER = "153cba3fb88b4c88b7c1002f0eb63749";
/**
* 提案工作委员会parent_id
*/
String SYS_DICT_WYH_PARENT_ID = "c10faa82946646c78a863220d0f468fa";
/**
* 专门委员会节点id
*/
String ZMWYH = "84519c3978404af89147c42f19e9c5d8";
/**
* 提案工作委员会id
*/
String SYS_DICT_TA_WYH_ID = "425efc05403b49dcbdbbe93122a77513";
/**
* 教职工调解委员会
*/
String SYS_DICT_JZG_TJ_WYH_ID = "e36237c11126485c815688acce5a7228";
/**
* 公共角色
*/
String PUBLIC = "dc72d1f4197146d5b7658682bc718bb6";
/**
* 工会委员会主席
*/
String GH_WYH_ZX = "26fa82e6f7dd4641aa1655d9fa5c875a";
/**
* 工会委员会常务副主席
*/
String GH_WYH_CWFZX = "3dad064faf134a6fb6ec3437ff2e09e2";
/**
* 工会委员会副主席
*/
String GH_WYH_FZX = "3a87d9e925174f59bbbe86fcf2be3a91";
/**
* 工会委员会成员
*/
String GH_WYH_CY = "a48e3049aca5414b9cbc42174bb29567";
/**
* 经费审查委员会主任
*/
String JFSC_WYH_ZR = "09a14a13f0e4490e8fea95d20fdc4066";
/**
* 经费审查委员会副主任
*/
String JFSC_WYH_FZR = "f431140e20b2484489158de03f91c83a";
/**
* 经费审查委员会成员
*/
String JFSC_WYH_CY = "8c92538a928c4d4bb827a18f84fe6f98";
/**
* 女教职工委员会主任
*/
String NJZG_WYH_ZR = "ba09a540ec2f46d18dac2f2f8b33908a";
/**
* 女教职工委员会副主任
*/
String NJZG_WYH_FZR = "100c6e52c8ff4ba397b9bfd0a9310f18";
/**
* 女教职工委员会成员
*/
String NJZG_WYH_CY = "8525916274ce4c54b94b28d87e701f79";
/**
* 争议调解委员会主任
*/
String ZYTJ_WYH_ZR = "c59002613df5490c9650999605eccc23";
/**
* 争议调解委员会主任
*/
String ZYTJ_WYH_FZR = "cb0648154cb34089b4e050b21e5b29aa";
/**
* 争议调解委员会成员
*/
String ZYTJ_WYH_CY = "53dcf219e5084bc99d5773aa097f8475";
/**
* 校工会会计
*/
String XGHKJ = "4f72d9259837486a8092c19897fa9dd6";
/**
* 校工会管理员
*/
String XGHGLY = "9b01918f873645048f8a85a4fc06d135";
/**
* 校工会出纳
*/
String XGHCN = "20270bcf02fd4acfbfa3ab06217e8301";
/**
* 工代会代表
*/
String GDHDB = "5f2fa7750e884b9793c27480977d75ad";
/**
* 工代会列席
*/
String GDHLX = "8bf27c18e3034219876214d09c8fff31";
/**
* 工代会特邀
*/
String GDHTY = "15b2c2beb9e34c96bd30730ad383cde3";
/**
* 校活动管理员
*/
String XGH_HD = "45034013fef74de3b6b7d855dabf3420";
/**
* 校工会女工管理员
*/
String XGH_NG = "ca75df23771c40b6b4d06b00a4afeec0";
/**
* 校会员管理员
*/
String SchoolUnionMemberAdmin = "2fb23e5a6ffb4d4cb5111746d1188957";
/**
* 教代会代表二
*/
String JDH_DB2 = "05e7a279f4274a1eb3a81adb5f8c2454";
/**
* 单位书记
*/
String GH03 = "428969eb99ff4b76883d83f847ee96a5";
/**
* 工会组组长
*/
String ghxzzz = "308dfe9096f44a64a67b4714f67dcd96";
/**
* 协会会长
*/
String club01 = "79b1ecf9d2904393b8a96de599390f39";
/**
* 协会副会长
*/
String club02 = "b48539d87c2b43f999604affdfaae44f";
/**
* 协会秘书长
*/
String club03 = "9a89861023974fc0a5a1511d6b6c2b8f";
/**
* 协会副秘书长
*/
String club04 = "e63de2a29285445abfaede2f76102621";
/**
* 校协会管理员
*/
String xxhgly = "766e9abd52e3438cb632798d3635e766";
/**
* 教代会代表小组组长
*/
String DBZZ = "4d2084fd0bf7476b9080280cfa6eb4d2";
/**
* 教代会代表小组副组长
*/
String DBFZZ = "e625a83bf4bb45daa65fa588c29abb65";
/**
* 供应商录入员
*/
String FLGYSLR = "266844b78e65491a82909816dc59e77b";
/**
* 供应商录入员
*/
String LXYGYSLR = "17c8761a0326495cb140d5809d6375a9";
/**
* 分工会主席
*/
String GH01 = "9c1f19e385914fef82bc35da7c9ded36";
}
@@ -0,0 +1,32 @@
package io.v.nutz.base.utils;
import org.nutz.lang.Lang;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* Created by wizzer on 2018/6/28.
*/
public class SignUtil {
public static String createSign(String appkey, Map<String, Object> params) {
Map<String, Object> map = MapUtil.sortMapByKey(params);
StringBuffer sb = new StringBuffer();
Set<String> keySet = map.keySet();
Iterator<String> it = keySet.iterator();
while (it.hasNext()) {
String k = it.next();
String v = (String) map.get(k);
if (null != v && !"".equals(v)
&& !"sign".equals(k)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("appkey=" + appkey);
String sign = Lang.md5(sb.toString());
return sign;
}
}
@@ -0,0 +1,54 @@
package io.v.nutz.base.utils;
import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class SkipCertificateValidation {
public SkipCertificateValidation() {
}
public static void ignoreSsl() throws Exception {
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
return true;
}
};
trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier(hv);
}
private static void trustAllHttpsCertificates() throws Exception {
TrustManager[] trustAllCerts = new TrustManager[1];
TrustManager tm = new MiTm();
trustAllCerts[0] = tm;
SSLContext sc = SSLContext.getInstance("SSL");
sc.init((KeyManager[])null, trustAllCerts, (SecureRandom)null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
static class MiTm implements TrustManager, X509TrustManager {
MiTm() {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public boolean isServerTrusted(X509Certificate[] certs) {
return true;
}
public boolean isClientTrusted(X509Certificate[] certs) {
return true;
}
public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
}
public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
}
}
}
@@ -0,0 +1,97 @@
package io.v.nutz.base.utils;
/**
* @description:
* @author: zhf
* @time: 2022/4/24 14:15
*/
public class SmsTemplate {
//邀请附议人发送消息
// public static final String inviteSecondedTemplate = "{}邀请您附议[{}]提案,请您通过门户网站或企业微信登录智慧工会平台进行附议。";
public static final String inviteSecondedTemplate = "{}代表,您好,{}代表的提案《{}》,邀请您作为附议人,请您登陆学校智慧工会系统-提案管理系统-附议提案进行附议,感谢您对教代会提案工作的大力支持!";
//附议人通过或者拒绝给提案人发送消息
public static final String FYR_TG_TEMPLATE = "{}代表,已经附议通过您的“{}”";
public static final String FYR_JJ_TEMPLATE = "{}代表拒绝附议您的“{}”,提案至少需要{}个代表附议,才能提交。请关注!";
//附议完给团长发送消息
// public static final String TZ_TEMPLATE = "[{}]提案待您审核,请您通过门户网站或企业微信登录智慧工会平台进行审核";
public static final String TZ_TEMPLATE = "{}代表团团长,您好,{}代表的提案《{}》,已经完成附议,请您登陆学校智慧工会系统-提案管理系统-附议提案进行审核,感谢您对教代会提案工作的大力支持!";
//团长审核给提案人发送消息
public static final String tzPassTemplate = "团长审核通过您的“{}”!";
public static final String tzRollBackTemplate = "团长退回您的“{}”,请修改后,再次邀请代表附议!";
//团长审核给预审核发送消息
public static final String yshSendTemplate = "“{}”团长审核通过“{}”,请预审!";
//预审核通过发送
public static final String yshPassTemplate = "您的“{}”已经通过预审核!";
public static final String yshRollBackTemplate = "您的“{}”未通过预审核,请修改后再次邀请代表附议!原因是“{}”";
//点击按钮委员会成员意见
public static final String wyhCyTemplate = "各位委员,提案已经预审完毕,请登录智慧工会平台,选择委员会成员意见功能,对每个提案进行投票并提出意见!";
//点击执行会主任审核发送消息
public static final String zxhZrTemplate = "提案委员会已经对所有提案进行立案预审核,请{}主任批示!";
//点击分管校领导审核发送消息
public static final String xldTemplate = "提案委员会已经对所有提案进行立案预审核,请您作为承办单位的分管校领导进行审核!";
//点击分管校领导审核发送消息
public static final String xzTemplate = "提案委员会已经对所有提案进行立案预审核,请{}校长或书记批示!";
//承办单位审核完发送消息
public static final String wyhLaTemplate = "您的“{}”已立案为“{}”提案,承办单位分别是“{}”。";
public static final String wyhYjTemplate = "您的“{}”已作为意见建议,承办单位分别是“{}”。";
public static final String wyhByLaTemplate = "您的“{}”因{}原因,不予立案,请关注!";
//给承办单位负责人发消息
public static final String cbDwTemplate = "经提案委员会立案审核,分管校领导审批,“{}”由您单位作为“{}”进行办理及答复,请关注!";
//承办单位答复完发送提案人反馈
public static final String cbFkTemplate = "您的“{}”承办单位已经答复,结果是“{}”,请评价!";
//分管领导答复完发送提案人反馈
public static final String fgFkTemplate = "您的“{}”承办单位已答复,同时分管领导也已审批,请评价!";
//分管领导退回发送给承办单位
public static final String fgThTemplate = "“{}”需要重新答复,原因是“{}”,请关注!";
//点击分管领导审批答复发消息
public static final String fgTemplate = "承办单位“{}”已经完成所有提案的答复,请您审批!";
//完结
public static final String wjTemplate = "您的“{}”已经办理完结,请关注!";
/**
* 协会年度考核
*/
//申请完发送消息给会长
public static final String CLUB_EXAMINE_REGISTER_TEMPLATE = "{}年度{}考核内容已填写完毕并提交,请登陆“智慧工会”进行审核操作。";
//会长审核完发送给校工会
public static final String CLUB_EXAMINE_REGISTER_SCHOOL_TEMPLATE = "{}{}年度考核已提交,请登陆“智慧工会”进行审核操作。";
//校工会审核完返回修改发送给会长
public static final String CLUB_EXAMINE_SCHOOL_FHXG_TEMPLATE = "{}{}年度考核审核未通过,请登陆“智慧工会”进行修改补充。";
//校工会审核完注销发送给会长
public static final String CLUB_EXAMINE_SCHOOL_ZX_TEMPLATE = "抱歉通知您,{}{}年度年审考核未通过!按照《中国地质大学(武汉)教职工协会管理办法》(地大工字〔2022〕17号)相关规定,该协会将予以注销,敬请知悉。";
}
@@ -0,0 +1,161 @@
package io.v.nutz.base.utils;
import io.v.nutz.sys.models.Sys_user;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.nutz.lang.Strings;
import org.nutz.mvc.Mvcs;
import javax.servlet.http.HttpServletRequest;
import java.util.Random;
/**
* Created by wizzer on 2018/3/17.
*/
public class StringUtil {
/**
* 获取平台当前登录用户的所在单位
*
* @return
*/
public static String getPlatformUserUnitId() {
try {
Subject subject = SecurityUtils.getSubject();
if (subject != null) {
Sys_user user = (Sys_user) subject.getPrincipal();
if (user != null) {
return Strings.sNull(user.getUnitid());
}
}
} catch (Exception e) {
}
return "";
}
/**
* 获取平台后台登陆UID
*
* @return
*/
public static String getPlatformUid() {
try {
HttpServletRequest request = Mvcs.getReq();
if (request != null) {
return Strings.sNull(request.getSession(true).getAttribute("platform_uid"));
}
} catch (Exception e) {
}
return "";
}
/**
* 获取平台后台登陆用户名称
*
* @return
*/
public static String getPlatformLoginname() {
try {
HttpServletRequest request = Mvcs.getReq();
if (request != null) {
return Strings.sNull(request.getSession(true).getAttribute("platform_loginname"));
}
} catch (Exception e) {
}
return "";
}
/**
* 获取平台后台登陆用户名称
*
* @return
*/
public static String getPlatformUsername() {
try {
HttpServletRequest request = Mvcs.getReq();
if (request != null) {
return Strings.sNull(request.getSession(true).getAttribute("platform_username"));
}
} catch (Exception e) {
}
return "";
}
/**
* 去掉URL中?后的路径
*
* @param p
* @return
*/
public static String getPath(String p) {
if (Strings.sNull(p).contains("?")) {
return p.substring(0, p.indexOf("?"));
}
return Strings.sNull(p);
}
/**
* 获得父节点ID
*
* @param s
* @return
*/
public static String getParentId(String s) {
if (!Strings.isEmpty(s) && s.length() > 4) {
return s.substring(0, s.length() - 4);
}
return "";
}
/**
* 得到n位随机数
*
* @param s
* @return
*/
public static String getRndNumber(int s) {
Random ra = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s; i++) {
sb.append(String.valueOf(ra.nextInt(8)));
}
return sb.toString();
}
/**
* 判断是否以字符串开头
*
* @param str
* @param s
* @return
*/
public boolean startWith(String str, String s) {
return Strings.sNull(str).startsWith(Strings.sNull(s));
}
/**
* 判断是否包含字符串
*
* @param str
* @param s
* @return
*/
public boolean contains(String str, String s) {
return Strings.sNull(str).contains(Strings.sNull(s));
}
/**
* 将对象转为JSON字符串页面上使用
*
* @param obj
* @return
*/
public String toJson(Object obj) {
return Json.toJson(obj, JsonFormat.compact());
}
}
+348
View File
@@ -0,0 +1,348 @@
package io.v.nutz.base.utils;
import com.deepoove.poi.data.PictureRenderData;
import io.v.nutz.base.service.BaseService;
import io.v.nutz.sys.models.*;
import io.v.nutz.zhgh.jdh.model.cb.Jdh_jdhxx;
import io.v.nutz.sys.services.SysMenuService;
import io.v.nutz.sys.services.SysUserRoleService;
import io.v.nutz.sys.services.SysUserService;
import io.v.nutz.web.commons.utils.ShiroUtil;
import org.nutz.boot.starter.ftp.FtpService;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.Record;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.util.Daos;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.Mvcs;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
/**
* @Author: 1V
* @DateTime: 2020/8/28 14:45
* @Description: TODO
*/
@IocBean
public class Vi {
@Inject
private Dao dao;
@Inject
private BaseService baseService;
@Inject
private SysUserService sysUserService;
@Inject
private SysUserRoleService sysUserRoleService;
/**
* @return 当前登录用户的福利单位
*/
public static String getWelfareUnitId() {
Sys_user sys_user = (Sys_user) ShiroUtil.getPrincipal();
return sys_user.getUnit().getWelfareUnitId();
}
/**
* @return 当前登录用户管理的院级工会
*/
public String getMangeUnionStr() {
return "(SELECT sur.unionid FROM sys_user_role sur WHERE sur.userId = '" + ShiroUtil.getPrincipalProperty("id") + "' and sur.roleId = '" + Roles.UNION_MANGER + "')";
}
/**
* @return 当前登录用户的工会
*/
public static Sys_union getUnion() {
Sys_user sys_user = (Sys_user) ShiroUtil.getPrincipal();
return sys_user.getUnion();
}
/**
* @return 当前登录用户的单位
*/
public static Sys_unit getUnit() {
Sys_user sys_user = (Sys_user) ShiroUtil.getPrincipal();
return sys_user.getUnit();
}
/**
* @return 当前指定用户的工会
*/
public String getUnionId(String userid) {
Sys_user user = sysUserService.fetchLinks(sysUserService.fetch(userid), "unit");
return user.getUnit() == null ? "" : user.getUnit().getUnionid();
}
/**
* @return 当前登录用户的工会id
*/
public static String getUnionId() {
return getUnion() == null ? "" : getUnion().getId();
}
/**
* 获取工会小组id
*/
public static String getUnionGroupId() {
Sys_user sys_user = (Sys_user) ShiroUtil.getPrincipal();
return Optional.ofNullable(sys_user.getThreeUnit()).map(Sys_unit::getUnionGroupId).orElse(null);
}
/**
* @return 当前登录用户的所负责的协会id
*/
public String getClubId() {
Sys_user_role userRole = sysUserRoleService.fetch(Cnd.where("userId", "=", ShiroUtil.getPrincipalProperty("id")).and("roleId", "=", Roles.club01));
return userRole == null ? "" : userRole.getStid();
}
/**
* @return 当前登录用户管理的协会协会
*/
public String getMangeClubStr() {
return "(SELECT sur.stid FROM sys_user_role sur WHERE sur.userId = '" + ShiroUtil.getPrincipalProperty("id") + "' and sur.roleId = '" + Roles.club01 + "')";
}
/**
* @return 当前登录用户的代表团id
*/
public String getDbtId() {
return "SELECT dbtid FROM `sys_user_role` WHERE userid = '" + ShiroUtil.getPrincipalProperty("id") + "'";
}
/**
* 根据userid查询最新届次教代会的代表团id
*
* @param userId
* @return
*/
public static String getLastDelegationId(String userId) {
Dao dao = Mvcs.getIoc().get(Dao.class);
Sql sql = Sqls.create("""
SELECT
dbtid
FROM
jdh_db
WHERE
jdhid = ( SELECT id FROM jdh_jdhxx WHERE jdhkqzt = 1 ORDER BY jdhkqsj DESC LIMIT 1 )\s
AND dbid = @userId
""");
sql.setParam("userId", userId);
return (String) Daos.query(dao, sql.toString(), Sqls.callback.str());
}
/**
* 获取最新一届的教代会Id
*
* @return
*/
public String getLastTeacherMeetingId() {
Jdh_jdhxx jdhxx = dao.fetch(Jdh_jdhxx.class, Cnd.NEW().desc("jdhkqsj"));
if (Lang.isNotEmpty(jdhxx)) {
return jdhxx.getId();
}
return null;
}
@Inject
private SysMenuService sysMenuService;
public String getIconByPath(String path) {
Sys_menu menu = sysMenuService.fetch(Cnd.where("href", "=", path));
return menu == null ? "" : "fa " + menu.getIcon();
}
/**
* 获取客户端真实IP
*
* @param request
* @return
*/
public static String getIpAddress(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
if (ip.contains(",")) {
return ip.split(",")[0];
} else {
return ip;
}
}
public static PictureRenderData getImg(String base64) throws IOException {
String s = base64.split(",")[1];
byte[] bytes = Base64.getDecoder().decode(s);
return new PictureRenderData(70, 30, ".png", bytes);
}
public static String getCron(Date time) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(time);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int date = calendar.get(Calendar.DATE);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
String cronString = second + " " + minute + " " + hour + " " + date + " " + month + " ? " + year;
return cronString;
}
/**
* 根据指定name从request拿到cookie
*
* @param request
* @param name
* @return
*/
public static Cookie getCookie(HttpServletRequest request, String name) {
for (Cookie cookie : request.getCookies()) {
if (name.equals(cookie.getName())) {
return cookie;
}
}
return null;
}
public static void cndPlus(Cnd cnd, String key, String symbol, Object val) {
if (val == null) {
return;
}
if (val instanceof String) {
String s = val.toString();
if (Strings.isNotBlank(s)) {
cnd.and(key, symbol, val);
}
} else {
cnd.and(key, symbol, val);
}
}
public static boolean isNotBlank(Object... strings) {
return Arrays.stream(strings).allMatch(val -> {
if (val instanceof String) {
return Strings.isNotBlank(val.toString());
} else {
return val != null;
}
});
}
@Inject
private FtpService ftpService;
public void deleteSysFiles(List<Sys_file> files) {
try {
files.forEach(file -> {
ftpService.delete(file.getFilepath());
});
} catch (Exception e) {
}
}
/**
* 根据关联的reid删除所有文件
*
* @param reid
*/
public void deleteAllSysFilesRe(String reid) {
List<Sys_file> files = baseService.dao().query(Sys_file.class, Cnd.where("reid", "=", reid));
deleteSysFiles(files);
baseService.dao().clear(Sys_file.class, Cnd.where("reid", "=", reid));
}
/**
* 根据关联的reid删除文件
*
* @param reid
* @param ids 排除的文件id
*/
public void deleteSysFilesRe(String reid, List<String> ids) {
Cnd and = Cnd.where("reid", "=", reid);
if (!ids.isEmpty()) {
and.and("id", "not in", ids);
}
List<Sys_file> files = baseService.dao().query(Sys_file.class, and);
deleteSysFiles(files);
baseService.dao().clear(Sys_file.class, and);
}
public static List<NutMap> getClubManage(String id) {
Dao dao = Mvcs.getIoc().get(Dao.class);
Sql sql = Sqls.create("""
SELECT
u.loginname as loginName,
u.username as userName,
u.unitid as unitId,
u.unitname as unitName,
u.mobile,
c.`name`
FROM
sys_user_role r
LEFT JOIN
`user` u ON r.userId = u.id
LEFT JOIN
sys_club c ON c.id = r.stid
$condition
""");
Cnd cnd = Cnd.NEW();
cnd.and("stid", "=", id);
cnd.and("roleId", "in", Lang.array(Roles.club01, Roles.club02, Roles.club03, Roles.club04));
sql.setCondition(cnd);
return (List<NutMap>) Daos.query(dao, sql.toString(), Sqls.callback.maps());
}
/**
* 获取校工会会计工号
* @return
*/
public static List<String> getSchoolUnionAccountant() {
Dao dao = Mvcs.getIoc().get(Dao.class);
Sql sql = Sqls.create("""
SELECT
u.loginname
FROM
sys_user_role sur
LEFT JOIN sys_user u ON u.id = sur.userid
WHERE
sur.roleId = '4f72d9259837486a8092c19897fa9dd6'
GROUP BY
sur.userId
""");
List<NutMap> list = (List<NutMap>) Daos.query(dao, sql.toString(), Sqls.callback.maps());
return list.stream().map(v-> v.getString("loginname")).collect(Collectors.toList());
}
//查询校工会主席
public List<User> getSchoolPresident() {
List<Sys_user_role> userRoles = baseService.dao().query(Sys_user_role.class, Cnd.where("roleid", "=", Roles.GH_WYH_ZX));
List<String> list = userRoles.stream().map(Sys_user_role::getUserId).distinct().collect(Collectors.toList());
return baseService.dao().query(User.class, Cnd.where("id", "in", list));
}
}
@@ -0,0 +1,18 @@
package io.v.nutz.base.utils;
import org.nutz.dao.Dao;
import org.nutz.ioc.Ioc;
import org.nutz.lang.util.NutMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ViResource {
public static Ioc ioc = null;
public static Dao dao = null;
public static Map<String, List<NutMap>> selectEnums = new HashMap<>();
public ViResource() {
}
}
@@ -0,0 +1,95 @@
package io.v.nutz.base.utils;
import com.deepoove.poi.data.PictureRenderData;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Base64;
@IocBean
public class ViTool {
public ViTool() {
}
public static void excelResponse(HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
response.setContentType("application/octet-stream");
String var10002 = new String(fileName.getBytes("utf-8"), "ISO8859-1");
response.setHeader("Content-Disposition", "attachment;filename=" + var10002);
}
public static String getIpAddress(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip.contains(",") ? ip.split(",")[0] : ip;
}
public static Cookie getCookie(HttpServletRequest request, String name) {
Cookie[] var2 = request.getCookies();
int var3 = var2.length;
for(int var4 = 0; var4 < var3; ++var4) {
Cookie cookie = var2[var4];
if (name.equals(cookie.getName())) {
return cookie;
}
}
return null;
}
public static void cndPlus(Cnd cnd, String key, String symbol, Object val) {
if (val != null) {
if (val instanceof String) {
String s = val.toString();
if (Strings.isNotBlank(s)) {
cnd.and(key, symbol, val);
}
} else {
cnd.and(key, symbol, val);
}
}
}
public static boolean isNotBlank(Object... values) {
return Arrays.stream(values).allMatch((val) -> {
if (val instanceof String) {
return Strings.isNotBlank(val.toString());
} else {
return val != null;
}
});
}
public static PictureRenderData poiBase64Image(String base64, Integer width, Integer height) {
try{
String s = base64.split(",")[1];
byte[] bytes = Base64.getDecoder().decode(s);
return new PictureRenderData(width, height, ".png", bytes);
}catch (Exception e){
return new PictureRenderData(width, height, ".png", new byte[0]);
}
}
public static PictureRenderData poiBase64Image7030(String base64) throws IOException {
return poiBase64Image(base64, 70, 30);
}
}
@@ -0,0 +1,99 @@
package io.v.nutz.base.utils;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLConverter;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFPictureData;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
/**
* @author jug
* @date 2024/02/29
*/
@Slf4j
public class WordUtil {
public static String checkConvert2Html(File file) throws Exception {
String fileName = file.getName().toLowerCase();
if (fileName.endsWith(".doc")) {
return doc2Html(file);
} else if (fileName.endsWith(".docx")) {
return docx2Html(file);
} else {
return "";
}
}
public static String doc2Html(File file) throws Exception {
try (FileInputStream inputStream = new FileInputStream(file)) {
HWPFDocument wordDocument = new HWPFDocument(inputStream);
WordToHtmlConverter converter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
converter.setPicturesManager((bytes, pictureType, s, v, v1) -> {
String type = pictureType.name();
return "data:image/" + type + ";base64," + Base64.getEncoder().encodeToString(bytes);
});
converter.processDocument(wordDocument);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "html");
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
transformer.transform(new DOMSource(converter.getDocument()), new StreamResult(outputStream));
return outputStream.toString(StandardCharsets.UTF_8);
} catch (Exception e) {
log.error("Error converting doc to html: " + e.getMessage());
throw e;
}
}
public static String docx2Html(File file) throws Exception {
try (FileInputStream inputStream = new FileInputStream(file);
XWPFDocument document = new XWPFDocument(inputStream)) {
List<XWPFPictureData> list = document.getAllPictures();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
XHTMLConverter.getInstance().convert(document, outputStream, null);
String html = new String(outputStream.toByteArray());
Document doc = Jsoup.parse(html);
Elements elements = doc.getElementsByTag("img");
if (elements != null && elements.size() > 0 && list != null) {
for (Element element : elements) {
String src = element.attr("src");
for (XWPFPictureData data : list) {
if (src.contains(data.getFileName())) {
String type = src.substring(src.lastIndexOf(".") + 1);
String base64 = "data:image/" + type + ";base64," + Base64.getEncoder().encodeToString(data.getData());
element.attr("src", base64);
break;
}
}
}
}
return doc.html();
} catch (Exception e) {
log.error("Error converting docx to html: " + e.getMessage());
throw e;
}
}
}
@@ -0,0 +1,166 @@
package io.v.nutz.base.utils;
import okhttp3.*;
import org.nutz.http.Header;
import org.nutz.http.Http;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.upload.TempFile;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* @author: Aaron
* @create: 2020-09-02 14:19
* @description:
**/
@IocBean
public class WxHttpUtil {
private static final Log log = Logs.get();
@Inject
private WxTokenUtil wxTokenUtil;
private final OkHttpClient okHttpClient = new OkHttpClient();
private final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private final MediaType formData = MediaType.parse("multipart/form-data");
private final NutMap jsonHeader = NutMap.NEW().setv("Content-Type", "application/json");
public static String env = "jiangnan-7g769v4nce8a4fd2";
public String queryUrl = "https://api.weixin.qq.com/tcb/databasequery?access_token=ACCESS_TOKEN";
public String insertUrl = "https://api.weixin.qq.com/tcb/databaseadd?access_token=ACCESS_TOKEN";
public String updateUrl = "https://api.weixin.qq.com/tcb/databaseupdate?access_token=ACCESS_TOKEN";
public String deleteUrl = "https://api.weixin.qq.com/tcb/databasedelete?access_token=ACCESS_TOKEN";
public String uploadUrl = "https://api.weixin.qq.com/tcb/uploadfile?access_token=ACCESS_TOKEN";
public String downloadUrl = "https://api.weixin.qq.com/tcb/batchdownloadfile?access_token=ACCESS_TOKEN";
public String cloudUrl = "https://api.weixin.qq.com/tcb/invokecloudfunction?access_token=ACCESS_TOKEN&env=ENV&name=FUNCTION_NAME";
public String aggregateUrl = "https://api.weixin.qq.com/tcb/databaseaggregate?access_token=ACCESS_TOKEN";
public String countUrl = "https://api.weixin.qq.com/tcb/databasecount?access_token=ACCESS_TOKEN";
public NutMap getWxResult(String url, String query) throws IOException {
String queryUrl = url.replace("ACCESS_TOKEN", wxTokenUtil.getAccessToken());
Map<String, String> reqBody = new HashMap<>();
reqBody.put("env", this.env);
reqBody.put("query", query);
Header header = Header.create(jsonHeader);
org.nutz.http.Response response = Http.post3(queryUrl, Json.toJson(reqBody), header, 200000);
return Json.fromJson(NutMap.class, new InputStreamReader(response.getStream()));
}
public NutMap getCloudResult(String queryUrl, String name, Map<String, Object> reqBody) throws IOException {
String url = queryUrl.replace("ACCESS_TOKEN", wxTokenUtil.getAccessToken())
.replace("ENV", this.env).replace("FUNCTION_NAME", name);
RequestBody b = RequestBody.create(Json.toJson(reqBody), JSON);
Request request = new Request.Builder()
.url(url)
.post(b)
.build();
Call call = okHttpClient.newCall(request);
Response response = call.execute();
return Json.fromJson(NutMap.class, Objects.requireNonNull(response.body()).string());
}
/**
* 返回文件url
*
* @param fileid
* @return
* @throws IOException
*/
public String getWxFileUrl(String fileid) throws IOException {
String url = this.downloadUrl.replace("ACCESS_TOKEN", wxTokenUtil.getAccessToken());
Map mf = new HashMap<String, String>();
mf.put("fileid", fileid);
mf.put("max_age", 7200);
ArrayList<Map> fm = new ArrayList<>();
fm.add(mf);
Map reqbody = new HashMap<String, String>();
reqbody.put("env", this.env);
reqbody.put("file_list", fm);
Header header = Header.create(jsonHeader);
org.nutz.http.Response response = Http.post3(url, Json.toJson(reqbody), header, 200000);
NutMap map = Json.fromJson(NutMap.class, new InputStreamReader(response.getStream()));
if (map.getInt("errcode") == 0 && map.getString("errmsg").equals("ok")) {
NutMap res = map.getAsList("file_list", NutMap.class).get(0);
return res.getString("download_url");
} else {
log.error(map.getString("errmsg"));
return null;
}
}
/**
* 获取
* url string 上传url
* token string token
* authorization string authorization
* file_id string 文件ID
* cos_file_id string cos文件ID
*
* @param wxfilePath 文件的路径 微信端
* @return
*/
public NutMap getUploadFile(String wxfilePath) throws Exception {
String Url = this.uploadUrl.replace("ACCESS_TOKEN", wxTokenUtil.getAccessToken());
Map reqbody = new HashMap<String, String>();
reqbody.put("env", this.env);
reqbody.put("path", wxfilePath);
Header header = Header.create(jsonHeader);
org.nutz.http.Response response = Http.post3(Url, Json.toJson(reqbody), header, 200000);
NutMap map = Json.fromJson(NutMap.class, new InputStreamReader(response.getStream()));
return map;
}
/**
* @param map
* @param file 文件
* @param wxfilePath 储存在微信云端的路径
* @return 文件id
* @throws Exception
*/
public String uploadFile(NutMap map, TempFile file, String wxfilePath) throws Exception {
String url = map.getString("url");
String token = map.getString("token");
String authorization = map.getString("authorization");
String file_id = map.getString("file_id");
String cos_file_id = map.getString("cos_file_id");
RequestBody fb = RequestBody.create(file.getFile(), formData);
RequestBody b = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("key", wxfilePath)
.addFormDataPart("Signature", authorization)
.addFormDataPart("x-cos-security-token", token)
.addFormDataPart("x-cos-meta-fileid", cos_file_id)
.addFormDataPart("file", "filename", fb)
.build();
Request request = new Request.Builder()
.url(url)
.post(b)
.build();
Call call = okHttpClient.newCall(request);
Response response = call.execute();
//没有返回的内容 怎么判断是否成功 难道去查
return file_id;
}
}
@@ -0,0 +1,68 @@
package io.v.nutz.base.utils;
import cn.hutool.core.util.StrUtil;
import io.v.nutz.base.constant.RedisConstant;
import lombok.extern.slf4j.Slf4j;
import org.nutz.http.Http;
import org.nutz.integration.jedis.RedisService;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import java.util.HashMap;
/**
* @author jug
* @date 2024/01/15
*/
@IocBean
@Slf4j
public class WxTokenUtil {
@Inject
private RedisService redisService;
private static final String APPID = "wxffb8d1c4eef5da73";
private static final String APP_SECRET = "393e63d77631af9b883c1f1e116d41d3";
private String getTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
/**
* 获取token
*
* @return {@link String}
*/
public String getAccessToken() {
String token = redisService.get(RedisConstant.REDIS_KEY_WE_APP_ACCESS_TOKEN);
if (StrUtil.isNotBlank(token)) {
return token;
}
String url = getTokenUrl.replace("APPID", APPID).replace("APPSECRET", APP_SECRET);
String result = Http.get(url).getContent();
HashMap<String, Object> tokenObject = Json.fromJson(HashMap.class, result);
if (tokenObject.containsKey("errcode")) {
log.error("获取token失败------" + tokenObject.get("errmsg"));
throw new RuntimeException("获取token失败------" + tokenObject.get("errmsg"));
}
redisService.setex(RedisConstant.REDIS_KEY_WE_APP_ACCESS_TOKEN, 7200 - 200, (String) tokenObject.get("access_token"));
return (String) tokenObject.get("access_token");
}
public String jsTicket() {
String jsApiTicket = redisService.get("weixin_js_api_ticket");
if (StrUtil.isBlank(jsApiTicket)) {
String jsApiTicketContent = Http.get("https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=" + getAccessToken()).getContent();
NutMap jsApiTicketMap = Json.fromJson(NutMap.class, jsApiTicketContent);
if (jsApiTicketMap.getInt("errcode") == 0) {
redisService.setex("weixin_js_api_ticket", jsApiTicketMap.getInt("expires_in") - 200, jsApiTicketMap.getString("ticket"));
return jsApiTicketMap.getString("ticket");
}
}
return jsApiTicket;
}
}
@@ -0,0 +1,7 @@
package io.v.nutz.sys.constant;
import java.util.Date;
public class SysLocalProcessConstant {
}
@@ -0,0 +1,64 @@
package io.v.nutz.sys.constant.club;
/**
* @Author JyuHsin
* @Date 2023/3/31
* @Description
*/
public class ClubEvaluateAuditState {
/**
* 未提交
*/
public static final Integer NOT_SUBMIT = 2000;
/**
* 待秘书长审核
*/
public static final Integer MSZ_READY = 2010;
/**
* 秘书长审核退回修改
*/
public static final Integer MSZ_BACK_MODIFY = 2020;
/**
* 秘书长审核拒绝
*/
public static final Integer MSZ_REJECTED = 2030;
/**
* 待会长审核
*/
public static final Integer HZ_READY = 2040;
/**
* 会长审核退回修改
*/
public static final Integer HZ_BACK_MODIFY = 2050;
/**
* 会长审核拒绝
*/
public static final Integer HZ_REJECTED = 2060;
/**
* 待校工会委员会审核
*/
public static final Integer XGH_READY = 2070;
/**
* 校工会委员会核退回修改
*/
public static final Integer XGH_BACK_MODIFY = 2080;
/**
* 校工会委员会审核拒绝
*/
public static final Integer XGH_REJECTED = 2090;
/**
* 审核通过
*/
public static final Integer SCHOOL_PASS = 2100;
}
@@ -0,0 +1,84 @@
package io.v.nutz.sys.constant.club;
/**
* @Author JyuHsin
* @Date 2023/3/24
* @Description
*/
public class ClubRegistAuditState {
/**
* 未提交
*/
public static final Integer NOT_SUBMIT = 800;
/**
* 待分工会审核
*/
public static final Integer UNIT_PART_READY = 801;
/**
* 分工会退回修改
*/
public static final Integer UNIT_PART_BACK_MODIFY = 802;
/**
* 分工会审核拒绝
*/
public static final Integer UNIT_PART_REJECTED = 803;
/**
* 待校办公室主管审核
*/
public static final Integer XT_READY = 810;
/**
* 校办公室主管退回修改
*/
public static final Integer XT_BACK_MODIFY = 820;
/**
* 校办公室主管审核拒绝
*/
public static final Integer XT_REJECTED = 830;
/**
* 待分管副主席审核
*/
public static final Integer XLD_READY = 840;
/**
* 分管副主席退回修改
*/
public static final Integer XLD_BACK_MODIFY = 850;
/**
* 分管副主席审核拒绝
*/
public static final Integer XLD_REJECTED = 860;
/**
* 待校工会批复
*/
public static final Integer XGH_READY = 870;
/**
* 校工会批复退回修改
*/
public static final Integer XGH_BACK_MODIFY = 880;
/**
* 校工会批复拒绝
*/
public static final Integer XGH_REJECTED = 890;
/**
* 待协会确定相关资料
*/
public static final Integer ST_CONFIRM = 900;
/**
* 审核通过
*/
public static final Integer SCHOOL_PASS = 930;
}
@@ -0,0 +1,225 @@
package io.v.nutz.sys.controllers.open.file;
import io.v.nutz.base.result.Result;
import io.v.nutz.base.utils.DateUtil;
import io.v.nutz.web.commons.base.Globals;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Files;
import org.nutz.lang.random.R;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.*;
import org.nutz.mvc.impl.AdaptorErrorContext;
import org.nutz.mvc.upload.TempFile;
import org.nutz.mvc.upload.UploadAdaptor;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
;
/**
* Created by Wizzer on 2016/7/5.
*/
@IocBean
@At("/open/file/upload")
public class UploadController {
private static final Log log = Logs.get();
@Inject
private PropertiesProxy conf;
@AdaptBy(type = UploadAdaptor.class, args = {"ioc:fileUpload"})
@POST
@At
@Ok("json")
@RequiresAuthentication
//AdaptorErrorContext必须是最后一个参数
public Object file(@Param("Filedata") TempFile tf, HttpServletRequest req, AdaptorErrorContext err) {
try {
if (err != null && err.getAdaptorErr() != null) {
return NutMap.NEW().addv("code", 1).addv("msg", "文件不合法");
} else if (tf == null) {
return Result.error("空文件");
} else {
String suffixName = tf.getSubmittedFileName().substring(tf.getSubmittedFileName().lastIndexOf(".")).toLowerCase();
String filePath = Globals.AppUploadBase + "/file/" + DateUtil.format(new Date(), "yyyyMMdd") + "/";
String fileName = R.UU32() + suffixName;
String url = filePath + fileName;
String staticPath = conf.get("jetty.staticPath", "/files");
Files.write(staticPath + url, tf.getInputStream());
return Result.success("上传成功", NutMap.NEW().addv("file_type", suffixName).addv("file_name", tf.getSubmittedFileName()).addv("file_size", tf.getSize()).addv("file_url", url));
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return Result.error("系统错误");
} catch (Throwable e) {
log.error(e.getMessage(), e);
return Result.error("文件格式错误");
}
}
@AdaptBy(type = UploadAdaptor.class, args = {"ioc:videoUpload"})
@POST
@At
@Ok("json")
@RequiresAuthentication
//AdaptorErrorContext必须是最后一个参数
public Object video(@Param("Filedata") TempFile tf, HttpServletRequest req, AdaptorErrorContext err) {
try {
if (err != null && err.getAdaptorErr() != null) {
return NutMap.NEW().addv("code", 1).addv("msg", "文件不合法");
} else if (tf == null) {
return Result.error("空文件");
} else {
String suffixName = tf.getSubmittedFileName().substring(tf.getSubmittedFileName().lastIndexOf(".")).toLowerCase();
String filePath = Globals.AppUploadBase + "/video/" + DateUtil.format(new Date(), "yyyyMMdd") + "/";
String fileName = R.UU32() + suffixName;
String url = filePath + fileName;
String staticPath = conf.get("jetty.staticPath", "/files");
Files.write(staticPath + url, tf.getInputStream());
return Result.success("上传成功", NutMap.NEW().addv("file_type", suffixName).addv("file_name", tf.getSubmittedFileName()).addv("file_size", tf.getSize()).addv("file_url", url));
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return Result.error("系统错误");
} catch (Throwable e) {
log.error(e.getMessage(), e);
return Result.error("文件格式错误");
}
}
@AdaptBy(type = UploadAdaptor.class, args = {"ioc:imageUpload"})
@POST
@At
@Ok("json")
@RequiresAuthentication
//AdaptorErrorContext必须是最后一个参数
public Object image(@Param("Filedata") TempFile tf, HttpServletRequest req, AdaptorErrorContext err) {
try {
if (err != null && err.getAdaptorErr() != null) {
return NutMap.NEW().addv("code", 1).addv("msg", "文件不合法");
} else if (tf == null) {
return Result.error("空文件");
} else {
String suffixName = tf.getSubmittedFileName().substring(tf.getSubmittedFileName().lastIndexOf(".")).toLowerCase();
String filePath = Globals.AppUploadBase + "/image/" + DateUtil.format(new Date(), "yyyyMMdd") + "/";
String fileName = R.UU32() + suffixName;
String url = filePath + fileName;
String staticPath = conf.get("jetty.staticPath", "/files");
Files.write(staticPath + url, tf.getInputStream());
return Result.success("上传成功", url);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return Result.error("系统错误");
} catch (Throwable e) {
log.error(e.getMessage(), e);
return Result.error("图片格式错误");
}
}
@AdaptBy(type = UploadAdaptor.class, args = {"ioc:fileUpload"})
@POST
@At
@Ok("json")
@RequiresAuthentication
//AdaptorErrorContext必须是最后一个参数
public Object cmsfile(@Param("Filedata") TempFile tf, @Param("site") String site, HttpServletRequest req, AdaptorErrorContext err) {
try {
if (err != null && err.getAdaptorErr() != null) {
return NutMap.NEW().addv("code", 1).addv("msg", "文件不合法");
} else if (tf == null) {
return Result.error("空文件");
} else {
String suffixName = tf.getSubmittedFileName().substring(tf.getSubmittedFileName().lastIndexOf(".")).toLowerCase();
String prefix = "/" + site + "/www";
String filePath = "/upload/file/" + DateUtil.format(new Date(), "yyyyMMdd") + "/";
String fileName = R.UU32() + suffixName;
String url = filePath + fileName;
String staticPath = conf.get("jetty.staticPath", "/files");
Files.write(staticPath + prefix + url, tf.getInputStream());
return Result.success("上传成功", NutMap.NEW().addv("file_type", suffixName).addv("file_name", tf.getSubmittedFileName()).addv("file_size", tf.getSize()).addv("file_url", url));
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return Result.error("系统错误");
} catch (Throwable e) {
log.error(e.getMessage(), e);
return Result.error("文件格式错误");
}
}
@AdaptBy(type = UploadAdaptor.class, args = {"ioc:videoUpload"})
@POST
@At
@Ok("json")
@RequiresAuthentication
//AdaptorErrorContext必须是最后一个参数
public Object cmsvideo(@Param("Filedata") TempFile tf, @Param("site") String site, HttpServletRequest req, AdaptorErrorContext err) {
try {
if (err != null && err.getAdaptorErr() != null) {
return NutMap.NEW().addv("code", 1).addv("msg", "文件不合法");
} else if (tf == null) {
return Result.error("空文件");
} else {
String suffixName = tf.getSubmittedFileName().substring(tf.getSubmittedFileName().lastIndexOf(".")).toLowerCase();
String prefix = "/" + site + "/www";
String filePath = "/upload/video/" + DateUtil.format(new Date(), "yyyyMMdd") + "/";
String fileName = R.UU32() + suffixName;
String url = filePath + fileName;
String staticPath = conf.get("jetty.staticPath", "/files");
Files.write(staticPath + prefix + url, tf.getInputStream());
return Result.success("上传成功", NutMap.NEW().addv("file_type", suffixName).addv("file_name", tf.getSubmittedFileName()).addv("file_size", tf.getSize()).addv("file_url", url));
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return Result.error("系统错误");
} catch (Throwable e) {
log.error(e.getMessage(), e);
return Result.error("文件格式错误");
}
}
@AdaptBy(type = UploadAdaptor.class, args = {"ioc:imageUpload"})
@POST
@At
@Ok("json")
@RequiresAuthentication
//AdaptorErrorContext必须是最后一个参数
public Object cmsimage(@Param("Filedata") TempFile tf, @Param("site") String site, HttpServletRequest req, AdaptorErrorContext err) {
try {
if (err != null && err.getAdaptorErr() != null) {
return NutMap.NEW().addv("code", 1).addv("msg", "文件不合法");
} else if (tf == null) {
return Result.error("空文件");
} else {
String suffixName = tf.getSubmittedFileName().substring(tf.getSubmittedFileName().lastIndexOf(".")).toLowerCase();
String prefix = "/" + site + "/www";
String filePath = "/upload/image/" + DateUtil.format(new Date(), "yyyyMMdd") + "/";
String fileName = R.UU32() + suffixName;
String url = filePath + fileName;
String staticPath = conf.get("jetty.staticPath", "/files");
Files.write(staticPath + prefix + url, tf.getInputStream());
return Result.success("上传成功", url);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return Result.error("系统错误");
} catch (Throwable e) {
log.error(e.getMessage(), e);
return Result.error("图片格式错误");
}
}
}
@@ -0,0 +1,58 @@
package io.v.nutz.sys.controllers.platform;
import io.v.nutz.base.annontation.ViReturn;
import io.v.nutz.sys.models.Sys_menu;
import io.v.nutz.sys.models.Sys_user;
import io.v.nutz.sys.services.SysUserService;
import io.v.nutz.web.commons.utils.ShiroUtil;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* 待办
*/
@At("/platfotm/agenda")
@IocBean
@Ok("json:full")
public class AgendaController {
@Inject
private SysUserService sysUserService;
@At
@ViReturn
public Object getQuickentry() {
List<NutMap> list = new ArrayList<>();
// list.add(new NutMap().addv("iconClass", "fa fa-address-card-o").addv("label", "代表推选").addv("url", "/platform/teacherMeet/push").addv("color", "#0CB2B7"));
list.add(new NutMap().addv("iconClass", "fa el-icon-user").addv("label", "申请入会").addv("url", "/platform/member/apply/submit").addv("color", "#0CB2B7"));
list.add(new NutMap().addv("iconClass", "fa fa-pencil-square-o").addv("label", "撰写提案").addv("url", "/platform/proposal/transact/writeproposal").addv("color", "#018BE2"));
list.add(new NutMap().addv("iconClass", "fa fa-bed").addv("label", "慰问申请").addv("url", "/platform/fw/condolence/apply").addv("color", "#E14D4C"));
list.add(new NutMap().addv("iconClass", "fa fa-handshake-o").addv("label", "困难帮扶申请").addv("url", "/platform/fw/difficulty/apply").addv("color", "#E0891D"));
list.add(new NutMap().addv("iconClass", "fa el-icon-edit").addv("label", "活动报名").addv("url", "/platform/hd/hdbm").addv("color", "#3EA3B1"));
list.add(new NutMap().addv("iconClass", "fa el-icon-edit").addv("label", "活动报销申请").addv("url", "/platform/jf/activity_bx/apply").addv("color", "#E5821B"));
list.add(new NutMap().addv("iconClass", "fa fa-bicycle").addv("label", "加入协会").addv("url", "/platform/sys/club/sq").addv("color", "#0294A9"));
list.add(new NutMap().addv("iconClass", "fa fa-trophy").addv("label", "会籍变更").addv("url", "/platform/member/change/apply").addv("color", "#FB8C00"));
// list.add(new NutMap().addv("iconClass", "fa el-icon-add-location").addv("label", "活动场地预约").addv("url", "/platform/activity/site/reserve").addv("color", "#20A4C9"));
// list.add(new NutMap().addv("iconClass", "fa el-icon-school").addv("label", "会员高级管理").addv("url", "/platform/member/change/mange").addv("color", "#3D97BB"));
// list.add(new NutMap().addv("iconClass", "fa fa-trophy").addv("label", "\"三育人\"选题申报").addv("url", "/platfotm/syr/info/xtsb").addv("color", "#DB5B5B"));
// list.add(new NutMap().addv("iconClass", "fa fa-graduation-cap").addv("label", "子女入学信息登记").addv("url", "/platform/zgfw/rxdjsq").addv("color", "#DD8C0D"));
// list.add(new NutMap().addv("iconClass", "fa el-icon-medal").addv("label", "荣誉申请(个人)").addv("url", "/platfotm/ry/gr/grsq").addv("color", "#2699D4"));
// list.add(new NutMap().addv("iconClass", "fa el-icon-medal").addv("label", "荣誉申请(集体)").addv("url", "/platfotm/ry/jt/jtsq"));
list.add(new NutMap().addv("iconClass", "fa el-icon-chat-line-square").addv("label", "问卷调查").addv("url", "/platform/zgfw/question"));
Sys_user user = (Sys_user) ShiroUtil.getPrincipal();
List<Sys_menu> menus = user.getMenus();
return list.stream().filter(v -> Strings.isNotBlank(v.getString("url")) && menus.stream().anyMatch(x -> Strings.isNotBlank(x.getHref()) && v.getString("url").contains(x.getHref()))).distinct().collect(Collectors.toList());
}
}
@@ -0,0 +1,342 @@
package io.v.nutz.sys.controllers.platform.caredata;
import cn.wizzer.framework.base.Result;
import cn.wizzer.framework.base.service.BaseService;
import io.v.nutz.base.utils.Vi;
import io.v.nutz.sys.models.Sys_user;
import io.v.nutz.sys.services.SysUserService;
import io.v.nutz.web.commons.utils.ShiroUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.Record;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.dao.util.cri.Static;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
/**
* @Author: 1V
* @DateTime: 2020/10/15 10:37
* @Description: 职工关爱大数据
*/
@At("/platform/caredata/staff")
@IocBean
@Ok("json")
public class StaffCareDataCon {
private static final Log log = Logs.get();
@At("")
@Ok("beetl:/platform/caredata/StaffCareData.html")
@RequiresPermissions("caredata.staff")
public void index() {
}
@Inject
private SysUserService sysUserService;
@Inject
private BaseService baseService;
@Inject
private Vi vi;
@At
@RequiresPermissions("caredata.staff")
public Object getNumByYear(Integer yearnum, String userid, Integer startYear, Integer endYear) {
try {
Sys_user user = sysUserService.fetch(userid);
ArrayList<Object> result = new ArrayList<>();
if (startYear == null && endYear == null) {
int year = Calendar.getInstance().get(Calendar.YEAR);
yearnum = yearnum == null ? 10 : yearnum;
startYear = year - yearnum + 1;
endYear = year;
}
for (int i = startYear; i <= endYear; i++) {
final int y = i;
List list = baseService.list(Sqls.create("SELECT '职工慰问' type,count( 1 ) value, YEAR ( con.apply_time ) `year` FROM condolence con WHERE YEAR ( con.apply_time ) = @year and con.manager = @user GROUP BY YEAR ( con.apply_time )").setParam("year", i).setParam("user", userid));
result.addAll(list.size() > 0 ? list : new ArrayList<Object>() {{
add(new HashMap<String, Object>() {{
put("type", "职工慰问");
put("value", 0);
put("year", y);
}});
}});
List list1 = baseService.list(Sqls.create("SELECT '困难帮扶' type,count(1) value,year(bf.sqsj) `year` from zgfw_knbf bf WHERE YEAR ( bf.sqsj ) = @year and bf.sqr = @user GROUP BY YEAR(bf.sqsj) ").setParam("year", i).setParam("user", userid));
result.addAll(list1.size() > 0 ? list1 : new ArrayList<Object>() {{
add(new HashMap<String, Object>() {{
put("type", "困难帮扶");
put("value", 0);
put("year", y);
}});
}});
List list3 = baseService.list(Sqls.create("SELECT '子女入学' type,count(1) value ,CAST(rx.dj_year as SIGNED) `year` from fw_rxdj rx WHERE rx.dj_jzgid = @user and rx.dj_year = @year GROUP BY dj_year").setParam("year", i).setParam("user", userid));
result.addAll(list3.size() > 0 ? list3 : new ArrayList<Object>() {{
add(new HashMap<String, Object>() {{
put("type", "子女入学");
put("value", 0);
put("year", y);
}});
}});
result.add(new HashMap<String, Object>() {{
put("type", "撰写提案");
put("value", baseService.count(Sqls.create("SELECT count(1) from proposal_info info where info.createUser = @user and YEAR(info.createTime) = @year").setParam("year", y).setParam("user", userid)));
put("year", y);
}});
result.add(new HashMap<String, Object>() {{
put("type", "参与活动");
/*
put("value", baseService.count(Sqls.create("SELECT (SELECT count(1) from hd_xhdbm bm left join hd_xhd hd on bm.hdid = hd.id WHERE year(hd.bmkssj) = @year and bm.userid = @userid) + (SELECT count(1) from hd_fhdbm bm left join hd_fhhd hd on bm.hdid = hd.id WHERE year(hd.bmkssj) = @year and bm.userid = @userid) + (SELECT count(1) from hd_sthdbm bm left join hd_sthd hd on bm.sthdid = hd.id WHERE year(hd.bmkssj) = @year and bm.userid = @userid) + (SELECT count(1) from ( SELECT 1 from hd_wm_sbxx sb WHERE sb.hdsbrid = @userid and year(sb.hdsbsj) = @year GROUP BY sb.hdid) tab) + (SELECT count(1) from ( SELECT 1 from hd_ca_sbxx sb WHERE sb.sbr = @userid and year(sb.sbsj) = @year GROUP BY sb.hdid) tab) ").setParam("year", y).setParam("userid", userid)));
*/
put("value", baseService.count(Sqls.create("""
SELECT
(
SELECT
count( 1 )
FROM
activity_school_apply apply
LEFT JOIN activity_school school ON apply.activityId = school.id
WHERE
YEAR ( school.startTime ) = @year
AND apply.userId = @user
) + (
SELECT
count( 1 )
FROM
(
SELECT
1
FROM
hd_wm_sbxx sb
WHERE
sb.hdsbrid = @user
AND YEAR ( sb.hdsbsj ) = @year
GROUP BY
sb.hdid
) tab
) + (
SELECT
count( 1 )
FROM
(
SELECT
1
FROM
hd_ca_sbxx sb
WHERE
sb.sbr = @user
AND YEAR ( sb.sbsj ) = @year
GROUP BY
sb.hdid
) tab)
""").setParam("year", y).setParam("userid", userid)));
put("year", y);
}});
result.add(new HashMap<String, Object>() {{
put("type", "经费报销");
put("value", baseService.count(Sqls.create("SELECT count(1) from activity_bx bx WHERE bx.user_id = @user and year(bx.apply_time) = @year").setParam("year", y).setParam("user", userid)));
put("year", y);
}});
}
return Result.success().addData(result);
} catch (Exception e) {
return Result.error();
}
}
@At
@RequiresPermissions("caredata.staff")
public Object getYearNumAndAllNum(String userid) {
try {
HashMap<Object, Object> map = new HashMap<>();
int year = Calendar.getInstance().get(Calendar.YEAR);
Sys_user user = sysUserService.fetch(userid);
map.put("now_year", new HashMap<String, Object>() {{
put("zgww", baseService.count(Sqls.create("SELECT count(1) FROM condolence con WHERE YEAR ( con.apply_time ) = @year and con.manager = @user").setParam("year", year).setParam("user", userid)));
put("knbf", baseService.count(Sqls.create("SELECT count(1) FROM zgfw_knbf bf WHERE YEAR ( bf.sqsj ) = @year and bf.sqr = @user").setParam("year", year).setParam("user", userid)));
put("znrx", baseService.count(Sqls.create("SELECT count(1) FROM fw_rxdj rx WHERE rx.dj_jzgid = @user and rx.dj_year = @year").setParam("year", year).setParam("user", userid)));
put("ta", baseService.count(Sqls.create("SELECT count(1) from proposal_info info where info.createUser = @user and YEAR(info.createTime) = @year").setParam("year", year).setParam("user", userid)));
put("hd", baseService.count(Sqls.create("""
SELECT
(
SELECT
count( 1 )
FROM
activity_school_apply apply
LEFT JOIN activity_school school ON apply.activityId = school.id
WHERE
YEAR ( school.startTime ) = @year
AND apply.userId = @user
) + (
SELECT
count( 1 )
FROM
(
SELECT
1
FROM
hd_wm_sbxx sb
WHERE
sb.hdsbrid = @user
AND YEAR ( sb.hdsbsj ) = @year
GROUP BY
sb.hdid
) tab
) + (
SELECT
count( 1 )
FROM
(
SELECT
1
FROM
hd_ca_sbxx sb
WHERE
sb.sbr = @user
AND YEAR ( sb.sbsj ) = @year
GROUP BY
sb.hdid
) tab)
""").setParam("year", year).setParam("userid", userid)));
put("jfbx", baseService.count(Sqls.create("SELECT count(1) from activity_bx bx WHERE bx.user_id = @user and year(bx.apply_time) = @year").setParam("year", year).setParam("user", userid)));
}});
map.put("all", new HashMap<String, Object>() {{
put("zgww", baseService.count(Sqls.create("SELECT count(1) FROM condolence con WHERE con.manager = @user").setParam("user", userid)));
put("knbf", baseService.count(Sqls.create("SELECT count(1) FROM zgfw_knbf bf WHERE bf.sqr = @user").setParam("user", userid)));
put("znrx", baseService.count(Sqls.create("SELECT count(1) FROM fw_rxdj rx WHERE rx.dj_jzgid = @user").setParam("user", userid)));
put("ta", baseService.count(Sqls.create("SELECT count(1) from proposal_info info where info.createUser = @user").setParam("user", userid)));
put("hd", baseService.count(Sqls.create("""
SELECT
(
SELECT
count( 1 )
FROM
activity_school_apply apply
LEFT JOIN activity_school school ON apply.activityId = school.id
WHERE
apply.userId = @USER
) + ( SELECT count( 1 ) FROM ( SELECT 1 FROM hd_wm_sbxx sb WHERE sb.hdsbrid = @userid GROUP BY sb.hdid ) tab ) + (
SELECT
count( 1 )
FROM
( SELECT 1 FROM hd_ca_sbxx sb WHERE sb.sbr = @userid GROUP BY sb.hdid ) tab)
""").setParam("userid", userid)));
put("jfbx", baseService.count(Sqls.create("SELECT count(1) from activity_bx bx WHERE bx.user_id = @user").setParam("user", userid)));
}});
return Result.success().addData(map);
} catch (Exception e) {
return Result.error();
}
}
@At
@RequiresPermissions("caredata.staff")
public Object queryUser(String key) {
try {
Sql sql = Sqls.create("SELECT u.id,u.username,u.loginname,u.sex,u.birthday,un.`name` unitname,gh.unionname from sys_user u left join sys_unit un on u.unitid = un.id left join sys_union gh on un.unionid = gh.id $condition");
Cnd cnd = Cnd.NEW();
SqlExpressionGroup group = new SqlExpressionGroup();
group.orLike("u.username", key);
group.orLike("u.loginname", key);
cnd.and(group);
if (ShiroUtil.hasAnyRoles(new String[]{"sysadmin", "SchoolUnionAdmin"})) {
} else if (ShiroUtil.hasRole("H04")) {
cnd.and(new Static("un.unionid in " + vi.getMangeUnionStr()));
}
sql.setCondition(cnd);
return Result.success().addData(baseService.listPage(1, 50, sql));
} catch (Exception e) {
log.error(e);
return Result.error();
}
}
@At
@RequiresPermissions("caredata.staff")
public Object timeLine(String userid, String type, Boolean desc, String startTime, String endTime) {
try {
Sys_user user = sysUserService.fetch(userid);
Sql sql = Sqls.create("SELECT * from (\n" +
"SELECT con.id id,con.apply_time time,'zgww' type FROM condolence con WHERE con.manager= @user\n" +
"union all \n" +
"SELECT bf.id id ,bf.sqsj time,'knbf' type FROM zgfw_knbf bf WHERE bf.sqr = @user\n" +
"union all\n" +
"SELECT zn.dj_id id , zn.dj_tbrq time , 'znrx' type from fw_rxdj zn where zn.dj_jzgid = @user\n" +
"union all\n" +
"SELECT info.id id, info.createTime time , 'ta' type from proposal_info info where info.createUser = @user\n" +
"union all\n" +
"SELECT school.id, school.startTime time , 'xhd' type from activity_school_apply apply left join activity_school school on apply.activityId = school.id WHERE apply.userId = @user\n" +
"union all\n" +
"SELECT bx.id id , bx.apply_time time ,'yybx' type from activity_bx bx WHERE bx.user_id = @user\n" +
") tab WHERE 1=1 $type $year\n" +
"ORDER BY tab.time $order");
if (Strings.isNotBlank(type) && !type.equals("all")) {
sql.setVar("type", "AND tab.type = '" + type + "'");
}
if (Strings.isNotBlank(startTime) && Strings.isNotBlank(endTime)) {
sql.setVar("year", "AND tab.time >= '" + startTime + "' AND tab.time <= '" + endTime + "'");
}
if (desc == null || desc) {
sql.setVar("order", "desc");
} else {
sql.setVar("order", "asc");
}
sql.setParam("user", userid);
sql.setParam("loginname", user.getLoginname());
List<Record> list = sysUserService.list(sql);
return Result.success().addData(list);
} catch (Exception e) {
log.error(e);
return Result.error();
}
}
@At
@RequiresPermissions("caredata.staff")
public Object initUser() {
try {
Sql sql = Sqls.create("SELECT u.id,u.username,u.loginname,u.sex,u.birthday,un.`name` unitname,gh.unionname from sys_user u left join sys_unit un on u.unitid = un.id left join sys_union gh on un.unionid = gh.id $condition");
Cnd cnd = Cnd.NEW();
cnd.and("u.id", "=", ShiroUtil.getPrincipalProperty("id"));
sql.setCondition(cnd);
return Result.success().addData(baseService.list(sql).get(0));
} catch (Exception e) {
log.error(e);
return Result.error();
}
}
}
@@ -0,0 +1,679 @@
package io.v.nutz.sys.controllers.platform.caredata;
import cn.wizzer.framework.base.Result;
import cn.wizzer.framework.base.service.BaseService;
import io.v.nutz.base.utils.Vi;
import io.v.nutz.sys.services.SysUserService;
import io.v.nutz.web.commons.utils.ShiroUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.Record;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import java.util.*;
/**
* @Author: 1V
* @DateTime: 2020/10/15 11:39
* @Description: 工会大数据
*/
@At("/platform/caredata/union")
@IocBean
@Ok("json")
public class UnionCareDataCon {
private static final Log log = Logs.get();
@At("")
@Ok("beetl:/platform/caredata/UnionCareData.html")
@RequiresPermissions("caredata.union")
public void index() {
}
@Inject
private BaseService baseService;
@Inject
private SysUserService sysUserService;
@Inject
private Vi vi;
@At
@RequiresPermissions("caredata.union")
public Object getNumData() {
try {
Sql sql1 = Sqls.create("SELECT count(1) FROM member u WHERE 1= 1 $fgh");
Sql sql2 = Sqls.create("SELECT count(1) from sys_union");
Sql sql3 = Sqls.create("SELECT count(1) from sys_club st left join sys_user u on st.fzr = u.id left join sys_unit un on u.unitid = un.id left join sys_union fgh on fgh.id = un.unionid WHERE 1=1 $fgh");
Sql sql4 = Sqls.create("SELECT count( 1 ) FROM activity_school hd WHERE date(now()) >= hd.startTime AND date(now()) < hd.endTime");
Sql sql5 = Sqls.create("SELECT count(1) from activity_tissue hd left join sys_union fgh on hd.unionId = fgh.id WHERE date(now()) >= hd.startTime and date(now()) < hd.endTime AND hd.type=1 $fgh");
Sql sql6 = Sqls.create("""
SELECT
COUNT( 1 )
FROM
activity_tissue hd
LEFT JOIN `user` us ON hd.unionId = us.unionid
LEFT JOIN sys_club cl ON cl.fzr = us.id
WHERE
date(
now()) >= hd.startTime
AND date(
now()) < hd.endTime
AND hd.type =2 $fgh
""");
if (!ShiroUtil.hasAnyRoles(new String[]{"sysadmin", "SchoolUnionAdmin"}) && ShiroUtil.hasRole("H04")) {
String fghs = vi.getMangeUnionStr();
sql1.setVar("fgh", "AND unionid in " + fghs);
sql2.setVar("fgh", "AND fgh.id in " + fghs);
sql3.setVar("fgh", "AND fgh.id in " + fghs);
/* sql4.setVar("fgh", "AND fgh.id in " + fghs);*/
sql5.setVar("fgh", "AND fgh.id in " + fghs);
sql6.setVar("fgh", "AND us.unionId in " + fghs);
}
Map result = new HashMap() {{
put("hy_num", baseService.count(sql1));
put("fgh_num", baseService.count(sql2));
put("st_num", baseService.count(sql3));
put("xhd_num", baseService.count(sql4));
put("fhhd_num", baseService.count(sql5));
put("sthd_num", baseService.count(sql6));
}};
return Result.success().addData(result);
} catch (Exception e) {
log.error(e);
return Result.error();
}
}
@At
@RequiresPermissions("caredata.union")
public Object getHyNumBySex() {
try {
Sql sql1 = Sqls.create("SELECT IFNULL(count(1),0) FROM member u WHERE u.sex='男' and unionid!='' $fgh");
Sql sql2 = Sqls.create("SELECT IFNULL(count(1),0) FROM member u WHERE u.sex='女' and unionid!='' $fgh");
if (!ShiroUtil.hasAnyRoles(new String[]{"sysadmin", "SchoolUnionAdmin"}) && ShiroUtil.hasRole("H04")) {
String fghs = vi.getMangeUnionStr();
sql1.setVar("fgh", "AND unionid in " + fghs);
sql2.setVar("fgh", "AND unionid in " + fghs);
}
return Result.success().addData(new ArrayList<Object>() {{
add(new HashMap<String, Object>() {{
put("name", "");
put("value", baseService.count(sql1));
}});
add(new HashMap<String, Object>() {{
put("name", "");
put("value", baseService.count(sql2));
}});
}});
} catch (Exception e) {
log.error(e);
return Result.error();
}
}
@At
@RequiresPermissions("caredata.union")
public Object getYearHyNum(Integer startYear, Integer endYear) {
try {
Sql sql = Sqls.create("""
select count(1) from member_his where year = @year $union
""");
Sql sql2 = Sqls.create("""
select count(1) from member where 1 = 1 $union
""");
if (!ShiroUtil.hasAnyRoles(new String[]{"sysadmin", "SchoolUnionAdmin"}) && ShiroUtil.hasRole("H04")) {
String fghs = vi.getMangeUnionStr();
sql.setVar("fgh", "AND unionid in " + fghs);
sql2.setVar("fgh", "AND unionid in " + fghs);
}
ArrayList<Object> list = new ArrayList<>();
int nowYear = Calendar.getInstance().get(Calendar.YEAR);
if (startYear == null || endYear == null) {
startYear = nowYear - 9;
endYear = nowYear;
}
for (int i = startYear; i <= endYear; i++) {
int count = 0;
if (i != nowYear) {
count = baseService.count(sql.setParam("year", i));
} else {
count = baseService.count(sql2);
}
list.add(Map.of("year", i, "num", count));
}
return Result.success().addData(list);
} catch (Exception e) {
log.error(e);
return Result.error();
}
}
@At
@RequiresPermissions("caredata.union")
public Object getHdTypeNum() {
try {
Sql sql1 = Sqls.create("SELECT count(1) from activity_school");
Sql sql2 = Sqls.create("SELECT count(1) from activity_tissue hd left join sys_union fgh on hd.unionid = fgh.id WHERE hd.type=1 $fgh");
Sql sql3 = Sqls.create("""
SELECT
COUNT( 1 )
FROM
activity_tissue hd
LEFT JOIN `user` us ON hd.unionId = us.unionid
LEFT JOIN sys_club cl ON cl.fzr = us.id
WHERE
date(
now()) >= hd.startTime
AND date(
now()) < hd.endTime
AND hd.type =2 $fgh
""");
if (!ShiroUtil.hasAnyRoles(new String[]{"sysadmin", "SchoolUnionAdmin"}) && ShiroUtil.hasRole("H04")) {
String fghs = vi.getMangeUnionStr();
/* sql1.setVar("fgh", "AND fgh.id in " + fghs);*/
sql2.setVar("fgh", "AND fgh.id in " + fghs);
sql3.setVar("fgh", "AND us.unionId " + fghs);
}
ArrayList<Object> list = new ArrayList<>();
list.add(new HashMap<String, Object>() {{
put("type", "校工会活动");
put("num", baseService.count(sql1));
}});
list.add(new HashMap<String, Object>() {{
put("type", "分工会活动");
put("num", baseService.count(sql2));
}});
list.add(new HashMap<String, Object>() {{
put("type", "协会活动");
put("num", baseService.count(sql3));
}});
return Result.success().addData(list);
} catch (Exception e) {
log.error(e);
return Result.error();
}
}
@At
@RequiresPermissions("caredata.union")
public Object getYearHdJF(Integer startYear, Integer endYear) {
try {
Sql sql1 = Sqls.create("SELECT IFNULL( sum( funding ), 0 ) jf FROM activity_school hd WHERE YEAR(hd.startTime) = @year");
Sql sql2 = Sqls.create("SELECT IFNULL(sum(usedQuota),0) jf from jf_yjgh jy left join sys_union fgh on jy.unionId = fgh.id WHERE 1=1 $fgh and jy.`year` = @year");
Sql sql3 = Sqls.create("SELECT IFNULL(sum(used_quota),0) jf from jf_club hd left join sys_club st on st.id = hd.club_id left join sys_user u on u.id = st.fzr left join sys_unit un on u.unitid = un.id left join sys_union fgh on fgh.id = un.unionid WHERE 1=1 $fgh and hd.`year` = @year");
if (!ShiroUtil.hasAnyRoles(new String[]{"sysadmin", "SchoolUnionAdmin"}) && ShiroUtil.hasRole("H04")) {
String fghs = vi.getMangeUnionStr();
sql2.setVar("fgh", "AND fgh.id in " + fghs);
sql3.setVar("fgh", " fgh.id in " + fghs);
}
ArrayList<Object> list = new ArrayList<>();
if (startYear == null || endYear == null) {
int nowYear = Calendar.getInstance().get(Calendar.YEAR);
startYear = nowYear - 9;
endYear = nowYear;
}
for (int i = startYear; i <= endYear; i++) {
final int year = i;
list.add(new HashMap<String, Object>() {{
put("year", year);
put("type", "校工会活动");
put("num", sysUserService.list(sql1.setParam("year", year)).get(0).getDouble("jf"));
}});
list.add(new HashMap<String, Object>() {{
put("year", year);
put("type", "分工会活动");
put("num", sysUserService.list(sql2.setParam("year", year)).get(0).getDouble("jf"));
}});
list.add(new HashMap<String, Object>() {{
put("year", year);
put("type", "协会活动");
put("num", sysUserService.list(sql3.setParam("year", year)).get(0).getDouble("jf"));
}});
}
return Result.success().addData(list);
} catch (Exception e) {
log.error(e);
return Result.error();
}
}
@At
@RequiresPermissions("caredata.union")
public Object getZgwwMoneyByYear(Integer startYear, Integer endYear) {
try {
ArrayList<Object> result = new ArrayList<>();
Sql sql = Sqls.create("""
SELECT YEAR
( con.apply_time ) `year`,
IFNULL( sum( con.money ), 0 ) money
FROM
condolence con
LEFT JOIN `user` us ON us.id=con.manager
where YEAR (con.apply_time ) = @year $fgh
""");
if (!ShiroUtil.hasAnyRoles(new String[]{"sysadmin", "SchoolUnionAdmin"}) && ShiroUtil.hasRole("H04")) {
String fghs = vi.getMangeUnionStr();
sql.setVar("fgh", "AND us.unionid in " + fghs);
}
if (startYear == null || endYear == null) {
int nowYear = Calendar.getInstance().get(Calendar.YEAR);
startYear = nowYear - 9;
endYear = nowYear;
}
for (int i = startYear; i <= endYear; i++) {
final int y = i;
result.add(new HashMap<String, Object>() {{
List<Record> list = sysUserService.list(sql.setParam("year", y));
put("year", y);
put("type", "职工慰问");
put("num", list.size() > 0 ? list.get(0).getDouble("money") : 0);
}});
}
return Result.success().addData(result);
} catch (Exception e) {
return Result.error();
}
}
@At
@RequiresPermissions("caredata.union")
public Object getGhys(Integer year) {
try {
Sql sql1 = Sqls.create("SELECT\n" +
"\tfgh.unionname,\n" +
"\tIFNULL( sum( ys.usedQuota ), 0 ) money,\n" +
"\t'已使用' type \n" +
"FROM\n" +
"\tsys_union fgh\n" +
"\tLEFT JOIN jf_yjgh ys ON fgh.id = ys.unionId \n" +
"\tAND ys.`year` = @year \n" +
"GROUP BY\n" +
"\tfgh.id \n" +
"ORDER BY\n" +
"\tfgh.unionname").setParam("year", year == null ? Calendar.getInstance().get(Calendar.YEAR) : year);
Sql sql2 = Sqls.create("SELECT\n" +
"\tfgh.unionname,\n" +
"\tIFNULL( sum(totalQuota) - sum( ys.usedQuota ), 0 ) money,\n" +
"\t'未使用' type \n" +
"FROM\n" +
"\tsys_union fgh\n" +
"\tLEFT JOIN jf_yjgh ys ON fgh.id = ys.unionId \n" +
"\tAND ys.`year` = @year \n" +
"GROUP BY\n" +
"\tfgh.id \n" +
"ORDER BY\n" +
"\tfgh.unionname").setParam("year", year == null ? Calendar.getInstance().get(Calendar.YEAR) : year);
List list = baseService.list(sql1);
list.addAll(baseService.list(sql2));
return Result.success().addData(list);
} catch (Exception e) {
return Result.error();
}
}
@At
@RequiresPermissions("caredata.union")
public Object getStys(Integer year) {
try {
Sql sql1 = Sqls.create("SELECT\n" +
"\tclub.`name`,\n" +
"\tIFNULL( sum( ys.used_quota ), 0 ) money,\n" +
"\t'已使用' type \n" +
"FROM\n" +
"\tsys_club club\n" +
"\tLEFT JOIN jf_club ys ON club.id = ys.club_id \n" +
"\tAND ys.`year` = @year \n" +
"\tleft join sys_user u on club.fzr = u.id\n" +
"\tleft join sys_unit un on u.unitid = un.id\n" +
"\tleft join sys_union fgh on un.unionid = fgh.id WHERE 1 = 1 $fgh\n" +
"GROUP BY\n" +
"\tclub.id \n" +
"ORDER BY\n" +
"\tclub.`name`").setParam("year", year == null ? Calendar.getInstance().get(Calendar.YEAR) : year);
Sql sql2 = Sqls.create("SELECT\n" +
"\tclub.`name`,\n" +
"\tIFNULL( sum( ys.total_quota ) - sum( ys.used_quota ), 0 ) money,\n" +
"\t'未使用' type \n" +
"FROM\n" +
"\tsys_club club\n" +
"\tLEFT JOIN jf_club ys ON club.id = ys.club_id \n" +
"\tAND ys.`year` = @year \n" +
"\tleft join sys_user u on club.fzr = u.id\n" +
"\tleft join sys_unit un on u.unitid = un.id\n" +
"\tleft join sys_union fgh on un.unionid = fgh.id WHERE 1 = 1 $fgh\n" +
"GROUP BY\n" +
"\tclub.id \n" +
"ORDER BY\n" +
"\tclub.`name`").setParam("year", year == null ? Calendar.getInstance().get(Calendar.YEAR) : year);
if (!ShiroUtil.hasAnyRoles(new String[]{"sysadmin", "SchoolUnionAdmin"}) && ShiroUtil.hasRole("H04")) {
String fghs = vi.getMangeUnionStr();
sql1.setVar("fgh", "AND fgh.id in " + fghs);
sql2.setVar("fgh", "AND fgh.id in " + fghs);
}
List list = baseService.list(sql1);
list.addAll(baseService.list(sql2));
return Result.success().addData(list);
} catch (Exception e) {
return Result.error();
}
}
@At
@RequiresPermissions("caredata.union")
public Object getZgwwNumByYear(Integer startYear, Integer endYear) {
try {
ArrayList<Object> result = new ArrayList<>();
Sql sql = Sqls.create("""
SELECT
'职工慰问' type,
count( 1 ) VALUE,
YEAR ( con.apply_time ) `year`
FROM
condolence con
LEFT JOIN `user` us ON us.id=con.manager
WHERE
YEAR ( con.apply_time ) = @year AND con.state_id=2040 $fgh
GROUP BY
YEAR (con.apply_time )
""");
if (!ShiroUtil.hasAnyRoles(new String[]{"sysadmin", "SchoolUnionAdmin"}) && ShiroUtil.hasRole("H04")) {
String fghs = vi.getMangeUnionStr();
sql.setVar("fgh", "AND us.unionid in " + fghs);
}
if (startYear == null || endYear == null) {
int nowYear = Calendar.getInstance().get(Calendar.YEAR);
startYear = nowYear - 9;
endYear = nowYear;
}
for (int i = startYear; i <= endYear; i++) {
final int y = i;
List<Record> list = sysUserService.list(sql.setParam("year", i));
result.add(new HashMap<String, Object>() {{
put("value", list.size() > 0 ? list.get(0).getInt("value") : 0);
put("year", y);
}});
}
return Result.success().addData(result);
} catch (Exception e) {
return Result.error();
}
}
@At
@RequiresPermissions("caredata.union")
public Object getKnbfNumByYear(Integer startYear, Integer endYear) {
try {
ArrayList<Object> result = new ArrayList<>();
Sql sql = Sqls.create("""
SELECT
'困难帮扶' type,
count( 1 )
VALUE
,
YEAR ( bf.sqsj ) `year`
FROM
zgfw_knbf bf
LEFT JOIN `user` us ON us.id=bf.sqr
WHERE
YEAR ( bf.sqsj ) = @year
AND bf.zt = 500 $fgh
GROUP BY
YEAR (bf.sqsj)
""");
if (!ShiroUtil.hasAnyRoles(new String[]{"sysadmin", "SchoolUnionAdmin"}) && ShiroUtil.hasRole("H04")) {
String fghs = vi.getMangeUnionStr();
sql.setVar("fgh", "AND us.unionid in " + fghs);
}
if (startYear == null || endYear == null) {
int nowYear = Calendar.getInstance().get(Calendar.YEAR);
startYear = nowYear - 9;
endYear = nowYear;
}
for (int i = startYear; i <= endYear; i++) {
final int y = i;
List<Record> list = sysUserService.list(sql.setParam("year", i));
result.add(new HashMap<String, Object>() {{
put("value", list.size() > 0 ? list.get(0).getInt("value") : 0);
put("year", y);
}});
}
return Result.success().addData(result);
} catch (Exception e) {
return Result.error();
}
}
@At
@RequiresPermissions("caredata.union")
public Object getKnbfMoneyByYear(Integer startYear, Integer endYear) {
try {
ArrayList<Object> result = new ArrayList<>();
Sql sql1 = Sqls.create("SELECT YEAR ( bf.sq_sqsj ) `year`, IFNULL(sum(bf.sq_bzje) ,0) money FROM zgfw_knbfsq bf \n" +
"left join sys_user u on bf.sq_sqr = u.id left join sys_unit un on u.unitid = un.id left join hy_unioninfomgr fgh on un.unioninfomgr_id = fgh.unioninfomgr_id\n" +
"WHERE YEAR ( bf.sq_sqsj ) = @year and bf.sq_sqzt = 5 $fgh");
if (!ShiroUtil.hasAnyRoles(new String[]{"sysadmin", "SchoolUnionAdmin"}) && ShiroUtil.hasRole("H04")) {
String fghs = vi.getMangeUnionStr();
sql1.setVar("fgh", "AND fgh.unioninfomgr_id in " + fghs);
}
if (startYear == null || endYear == null) {
int nowYear = Calendar.getInstance().get(Calendar.YEAR);
startYear = nowYear - 9;
endYear = nowYear;
}
for (int i = startYear; i <= endYear; i++) {
final int y = i;
result.add(new HashMap<String, Object>() {{
List<Record> list = sysUserService.list(sql1.setParam("year", y));
put("year", y);
put("type", "困难帮扶");
put("num", list.size() > 0 ? list.get(0).getDouble("money") : 0);
}});
}
return Result.success().addData(result);
} catch (Exception e) {
return Result.error();
}
}
@At
@RequiresPermissions("caredata.union")
public Object getRxbmCountByYear(Integer startYear, Integer endYear) {
try {
ArrayList<Object> result = new ArrayList<>();
Sql sql1 = Sqls.create("SELECT count( 1 ) c FROM fw_rxdj rx LEFT JOIN sys_user u ON rx.dj_jzgid = u.id LEFT JOIN sys_unit un ON u.unitid = un.id LEFT JOIN sys_union fgh ON un.unionid = fgh.id WHERE rx.dj_year = @year AND rx.dj_djlx = 1 $fgh ");
Sql sql2 = Sqls.create("SELECT count( 1 ) c FROM fw_rxdj rx LEFT JOIN sys_user u ON rx.dj_jzgid = u.id LEFT JOIN sys_unit un ON u.unitid = un.id LEFT JOIN sys_union fgh ON un.unionid = fgh.id WHERE rx.dj_year = @year AND rx.dj_djlx = 2 $fgh ");
Sql sql3 = Sqls.create("SELECT count( 1 ) c FROM fw_rxdj rx LEFT JOIN sys_user u ON rx.dj_jzgid = u.id LEFT JOIN sys_unit un ON u.unitid = un.id LEFT JOIN sys_union fgh ON un.unionid = fgh.id WHERE rx.dj_year = @year AND rx.dj_djlx = 3 $fgh ");
if (!ShiroUtil.hasAnyRoles(new String[]{"sysadmin", "SchoolUnionAdmin"}) && ShiroUtil.hasRole("H04")) {
String fghs = vi.getMangeUnionStr();
sql1.setVar("fgh", "AND fgh.id in " + fghs);
sql2.setVar("fgh", "AND fgh.id in " + fghs);
sql3.setVar("fgh", "AND fgh.id in " + fghs);
}
if (startYear == null || endYear == null) {
int nowYear = Calendar.getInstance().get(Calendar.YEAR);
startYear = nowYear - 9;
endYear = nowYear;
}
for (int i = startYear; i <= endYear; i++) {
final int y = i;
result.add(new HashMap<String, Object>() {{
List<Record> list = sysUserService.list(sql1.setParam("year", y));
put("year", y);
put("type", "幼儿园");
put("num", list.size() > 0 ? list.get(0).getInt("c") : 0);
}});
result.add(new HashMap<String, Object>() {{
List<Record> list = sysUserService.list(sql2.setParam("year", y));
put("year", y);
put("type", "小学");
put("num", list.size() > 0 ? list.get(0).getInt("c") : 0);
}});
result.add(new HashMap<String, Object>() {{
List<Record> list = sysUserService.list(sql3.setParam("year", y));
put("year", y);
put("type", "初中");
put("num", list.size() > 0 ? list.get(0).getInt("c") : 0);
}});
}
return Result.success().addData(result);
} catch (Exception e) {
return Result.error();
}
}
@At
@RequiresPermissions("caredata.union")
public Object getRxnumYey(Integer year) {
try {
Sql sql1 = Sqls.create("SELECT\n" +
"\tcount( 1 ) num,\n" +
"\trx.dj_sqxx type \n" +
"FROM\n" +
"\tfw_rxdj rx\n" +
"\tLEFT JOIN sys_user u ON rx.dj_jzgid = u.id\n" +
"\tLEFT JOIN sys_unit un ON u.unitid = un.id\n" +
"\tLEFT JOIN sys_union fgh ON un.unionid = fgh.id \n" +
"WHERE\n" +
"\trx.dj_djlx = 1 \n" +
"\tAND rx.dj_year = @year \n" +
"\t$fgh group by rx.dj_sqxx order by rx.dj_sqxx");
sql1.setParam("year", year == null ? Calendar.getInstance().get(Calendar.YEAR) : year);
if (!ShiroUtil.hasAnyRoles(new String[]{"sysadmin", "SchoolUnionAdmin"}) && ShiroUtil.hasRole("H04")) {
String fghs = vi.getMangeUnionStr();
sql1.setVar("fgh", "AND fgh.id in " + fghs);
}
return Result.success().addData(baseService.list(sql1));
} catch (Exception e) {
log.error(e);
return Result.error();
}
}
@At
public Object getRxnumXx(Integer year) {
try {
Sql sql1 = Sqls.create("SELECT\n" +
"\tcount( 1 ) num,\n" +
"\trx.dj_sqxx type \n" +
"FROM\n" +
"\tfw_rxdj rx\n" +
"\tLEFT JOIN sys_user u ON rx.dj_jzgid = u.id\n" +
"\tLEFT JOIN sys_unit un ON u.unitid = un.id\n" +
"\tLEFT JOIN sys_union fgh ON un.unionid = fgh.id \n" +
"WHERE\n" +
"\trx.dj_djlx = 2 \n" +
"\tAND rx.dj_year = @year \n" +
"\t$fgh group by rx.dj_sqxx order by rx.dj_sqxx");
sql1.setParam("year", year == null ? Calendar.getInstance().get(Calendar.YEAR) : year);
if (!ShiroUtil.hasAnyRoles(new String[]{"sysadmin", "SchoolUnionAdmin"}) && ShiroUtil.hasRole("H04")) {
String fghs = vi.getMangeUnionStr();
sql1.setVar("fgh", "AND fgh.id in " + fghs);
}
return Result.success().addData(baseService.list(sql1));
} catch (Exception e) {
log.error(e);
return Result.error();
}
}
@At
@RequiresPermissions("caredata.union")
public Object getRxnumCz(Integer year) {
try {
Sql sql1 = Sqls.create("SELECT\n" +
"\tcount( 1 ) num,\n" +
"\trx.dj_sqxx type \n" +
"FROM\n" +
"\tfw_rxdj rx\n" +
"\tLEFT JOIN sys_user u ON rx.dj_jzgid = u.id\n" +
"\tLEFT JOIN sys_unit un ON u.unitid = un.id\n" +
"\tLEFT JOIN sys_union fgh ON un.unionid = fgh.id \n" +
"WHERE\n" +
"\trx.dj_djlx = 3 \n" +
"\tAND rx.dj_year = @year \n" +
"\t $fgh group by rx.dj_sqxx order by rx.dj_sqxx");
sql1.setParam("year", year == null ? Calendar.getInstance().get(Calendar.YEAR) : year);
if (!ShiroUtil.hasAnyRoles(new String[]{"sysadmin", "SchoolUnionAdmin"}) && ShiroUtil.hasRole("H04")) {
String fghs = vi.getMangeUnionStr();
sql1.setVar("fgh", "AND fgh.id in " + fghs);
}
return Result.success().addData(baseService.list(sql1));
} catch (Exception e) {
log.error(e);
return Result.error();
}
}
}
@@ -0,0 +1,56 @@
package io.v.nutz.sys.controllers.platform.sys;
import cn.hutool.core.util.StrUtil;
import io.v.nutz.base.utils.LoginUtil;
import io.v.nutz.web.commons.base.Globals;
import org.apache.shiro.authc.*;
import org.jasig.cas.client.util.AbstractCasFilter;
import org.jasig.cas.client.validation.Assertion;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* 单点登录
*/
@At("/sso")
@IocBean
public class CasController {
@Inject
private LoginUtil loginUtil;
@At("/login")
@Ok("re")
public Object user(HttpServletRequest request, HttpSession session, @Param("redirect") String redirect) {
Assertion assertion = (Assertion) request.getSession().getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
if (assertion == null) {
return "->:/";
}
String loginName = assertion.getPrincipal().toString();
try {
loginUtil.doLogin(loginName, request, session, LoginUtil.LoginOrigin.CAS);
if (StrUtil.isNotBlank(redirect)) {
return ">>:" + redirect;
}
return ">>:" + Globals.AppDomain + "/platform/home";
} catch (LockedAccountException e) {
request.setAttribute("errMsg", "帐号被锁定,请5分钟后再试");
return ">>:" + Globals.AppDomain + "/platform/home/LockedAccountError";
} catch (UnknownAccountException e) {
request.setAttribute("errMsg", "系统中没有此用户");
return ">>:" + Globals.AppDomain + "/platform/home/UnknownAccountError";
} catch (Exception e) {
request.setAttribute("errMsg", "用户名或密码错误");
return ">>:" + Globals.AppDomain + "/platform/home/500";
}
}
}
@@ -0,0 +1,45 @@
package io.v.nutz.sys.controllers.platform.sys;
import javax.net.ssl.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.Security;
import java.security.cert.X509Certificate;
public class SSLContextTrustAnyHostname {
public static void trustAllHosts() {
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
SSLContext sc = null;
try {
sc = SSLContext.getInstance("SSL");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
try {
sc.init(null, trustAllCerts, new SecureRandom());
} catch (KeyManagementException e) {
e.printStackTrace();
}
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}
}
@@ -0,0 +1,103 @@
package io.v.nutz.sys.controllers.platform.sys;
import io.v.nutz.base.utils.PageUtil;
import io.v.nutz.sys.services.SysApiService;
import io.v.nutz.web.commons.slog.annotation.SLog;
import io.v.nutz.base.result.Result;;
import io.v.nutz.web.commons.utils.ShiroUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import javax.servlet.http.HttpServletRequest;
/**
* Created by wizzer on 2016/6/24.
*/
@IocBean
@At("/platform/sys/api")
public class SysApiController {
private static final Log log = Logs.get();
@Inject
private SysApiService sysApiService;
@At("")
@Ok("beetl:/platform/sys/api/index.html")
@RequiresPermissions("sys.manager.api")
public void index() {
}
@At
@Ok("json")
@RequiresPermissions("sys.manager.api.add")
@SLog(tag = "新建密钥", msg = "应用名称:${name}")
public Object addDo(@Param("name") String name, HttpServletRequest req) {
try {
sysApiService.createAppkey(name, ShiroUtil.getPlatformUid());
return Result.success();
} catch (Exception e) {
return Result.error();
}
}
@At("/delete/?")
@Ok("json")
@RequiresPermissions("sys.manager.api.delete")
@SLog(tag = "删除密钥", msg = "Appid:${appid}")
public Object delete(String appid, HttpServletRequest req) {
try {
sysApiService.deleteAppkey(appid);
return Result.success();
} catch (Exception e) {
return Result.error();
}
}
@At("/enable/?")
@Ok("json")
@RequiresPermissions("sys.manager.api.edit")
@SLog(tag = "启用密钥", msg = "Appid:${appid}")
public Object enable(String appid, HttpServletRequest req) {
try {
sysApiService.updateAppkey(appid, false);
return Result.success();
} catch (Exception e) {
return Result.error();
}
}
@At("/disable/?")
@Ok("json")
@RequiresPermissions("sys.manager.api.edit")
@SLog(tag = "禁用密钥", msg = "Appid:${appid}")
public Object disable(String appid, HttpServletRequest req) {
try {
sysApiService.updateAppkey(appid, true);
return Result.success();
} catch (Exception e) {
return Result.error();
}
}
@At
@Ok("json:full")
@RequiresPermissions("sys.manager.api")
public Object data(@Param("pageNumber") int pageNumber, @Param("pageSize") int pageSize, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {
try {
Cnd cnd = Cnd.NEW();
if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
cnd.orderBy(pageOrderName, PageUtil.getOrder(pageOrderBy));
}
return Result.success().addData(sysApiService.listPage(pageNumber, pageSize, cnd));
} catch (Exception e) {
return Result.error();
}
}
}
@@ -0,0 +1,437 @@
package io.v.nutz.sys.controllers.platform.sys;
import io.v.nutz.base.constant.RedisConstant;
import io.v.nutz.base.result.Result;
import io.v.nutz.base.utils.PageUtil;
import io.v.nutz.sys.models.Sys_app_conf;
import io.v.nutz.sys.models.Sys_app_list;
import io.v.nutz.sys.models.Sys_app_task;
import io.v.nutz.sys.services.SysAppConfService;
import io.v.nutz.sys.services.SysAppListService;
import io.v.nutz.sys.services.SysAppTaskService;
import io.v.nutz.web.commons.slog.annotation.SLog;
import io.v.nutz.web.commons.utils.ShiroUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.boot.starter.logback.exts.loglevel.LoglevelCommand;
import org.nutz.boot.starter.logback.exts.loglevel.LoglevelProperty;
import org.nutz.boot.starter.logback.exts.loglevel.LoglevelService;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.pager.Pager;
import org.nutz.integration.jedis.RedisService;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.lang.Files;
import org.nutz.lang.Streams;
import org.nutz.lang.Strings;
import org.nutz.lang.stream.StringInputStream;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import redis.clients.jedis.ScanParams;
import redis.clients.jedis.ScanResult;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* Created by wizzer on 2019/2/27.
*/
@IocBean
@At("/platform/sys/app")
public class SysAppController {
private static final Log log = Logs.get();
@Inject
private LoglevelService loglevelService;
@Inject
private SysAppListService sysAppListService;
@Inject
private SysAppConfService sysAppConfService;
@Inject
private SysAppTaskService sysAppTaskService;
@Inject
private RedisService redisService;
@Inject
private PropertiesProxy conf;
@At("")
@Ok("beetl:/platform/sys/app/index.html")
@RequiresPermissions("sys.operation.app")
public void index() {
}
@At
@Ok("json:full")
@RequiresPermissions("sys.operation.app")
@SuppressWarnings("unchecked")
public Object data(@Param("hostName") String hostName) {
try {
List<NutMap> hostList = new ArrayList<>();
NutMap map = loglevelService.getData();
List<LoglevelProperty> dataList = new ArrayList<>();
//对数据进行整理,获得左侧主机列表及右侧实例数据
for (Map.Entry<String, Object> entry : map.entrySet()) {
List<LoglevelProperty> list = (List) entry.getValue();
for (LoglevelProperty property : list) {
NutMap nutMap = NutMap.NEW().addv("hostName", property.getHostName()).addv("hostAddress", property.getHostAddress());
if (!hostList.contains(nutMap))
hostList.add(nutMap);
if (Strings.isBlank(hostName) || (Strings.isNotBlank(hostName) && property.getHostName().equals(hostName))) {
dataList.add(property);
}
}
}
return Result.success().addData(NutMap.NEW().addv("hostList", hostList).addv("appList", dataList));
} catch (Exception e) {
return Result.error();
}
}
@At
@Ok("json:full")
@RequiresPermissions("sys.operation.app")
@SuppressWarnings("unchecked")
public Object osData(@Param("hostName") String hostName) {
try {
List<String> list = new ArrayList<>();
ScanParams match = new ScanParams().match(RedisConstant.PLATFORM_REDIS_PREFIX+"logback:deploy:" + hostName + ":*");
ScanResult<String> scan = null;
do {
scan = redisService.scan(scan == null ? ScanParams.SCAN_POINTER_START : scan.getStringCursor(), match);
list.addAll(scan.getResult());//增量式迭代查询,可能还有下个循环,应该是追加
} while (!scan.isCompleteIteration());
Collections.sort(list);
List<NutMap> dataList = new ArrayList<>();
for (String key : list) {
dataList.add(Json.fromJson(NutMap.class, redisService.get(key)));
}
return Result.success().addData(dataList);
} catch (Exception e) {
return Result.error();
}
}
@At("/version")
@Ok("json")
@RequiresPermissions("sys.operation.app")
public Object version(@Param("name") String name) {
try {
List<Sys_app_list> appVerList = sysAppListService.query(Cnd.where("disabled", "=", false).and("appName", "=", name).desc("createdAt"), new Pager().setPageNumber(1).setPageSize(10));
List<Sys_app_conf> confVerList = sysAppConfService.query(Cnd.where("disabled", "=", false).and("confName", "=", name).desc("createdAt"), new Pager().setPageNumber(1).setPageSize(10));
return Result.success().addData(NutMap.NEW().addv("appVerList", appVerList).addv("confVerList", confVerList));
} catch (Exception e) {
return Result.error();
}
}
@At("/jar")
@Ok("beetl:/platform/sys/app/jar.html")
@RequiresPermissions("sys.operation.app")
public void jar() {
}
@At("/jar/data")
@Ok("json:{locked:'password|salt',ignoreNull:false}")
@RequiresPermissions("sys.operation.app.jar")
public Object jarData(@Param("appName") String appName, @Param("pageNumber") int pageNumber, @Param("pageSize") int pageSize, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {
try {
Cnd cnd = Cnd.NEW();
if (Strings.isNotBlank(appName)) {
cnd.and("appName", "like", "%" + appName + "%");
}
if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
cnd.orderBy(pageOrderName, PageUtil.getOrder(pageOrderBy));
}
return Result.success().addData(sysAppListService.listPageLinks(pageNumber, pageSize, cnd, "^(user)$"));
} catch (Exception e) {
return Result.error();
}
}
@At("/jar/addDo")
@Ok("json")
@RequiresPermissions("sys.operation.app.jar")
@SLog(tag = "添加安装包", msg = "应用名称:${sysAppList.appName}")
public Object jarAddDo(@Param("..") Sys_app_list sysAppList, HttpServletRequest req) {
try {
int num = sysAppListService.count(Cnd.where("appName", "=", Strings.trim(sysAppList.getAppName())).and("appVersion", "=", Strings.trim(sysAppList.getAppVersion())));
if (num > 0) {
return Result.error("版本号已存在");
}
sysAppList.setAppName(Strings.trim(sysAppList.getAppName()));
sysAppList.setAppVersion(Strings.trim(sysAppList.getAppVersion()));
sysAppList.setCreatedBy(ShiroUtil.getPlatformUid());
sysAppListService.insert(sysAppList);
return Result.success();
} catch (Exception e) {
return Result.error();
}
}
@At("/jar/search")
@Ok("json")
@RequiresPermissions("sys.operation.app.jar")
public Object jarSearch(@Param("appName") String appName) {
return Result.NEW().addData(sysAppListService.getAppNameList());
}
@At("/jar/delete/?")
@Ok("json")
@RequiresPermissions("sys.operation.app.jar")
@SLog(tag = "删除Jar包", msg = "ID:${id}")
public Object jarDelete(String id, HttpServletRequest req) {
try {
Sys_app_list appList = sysAppListService.fetch(id);
String staticPath = conf.get("jetty.staticPath", "/files");
Files.deleteFile(new File(staticPath + appList.getFilePath()));
sysAppListService.delete(id);
return Result.success();
} catch (Exception e) {
return Result.error();
}
}
@At("/jar/enable/?")
@Ok("json")
@RequiresPermissions("sys.operation.app.jar")
@SLog(tag = "启用Jar包", msg = "ID:${id}")
public Object jarEnable(String id, HttpServletRequest req) {
try {
sysAppListService.update(Chain.make("disabled", false), Cnd.where("id", "=", id));
return Result.success();
} catch (Exception e) {
return Result.error();
}
}
@At("/jar/disable/?")
@Ok("json")
@RequiresPermissions("sys.operation.app.jar")
@SLog(tag = "禁用Jar包", msg = "ID:${id}")
public Object jarDisable(String id, HttpServletRequest req) {
try {
sysAppListService.update(Chain.make("disabled", true), Cnd.where("id", "=", id));
return Result.success();
} catch (Exception e) {
return Result.error();
}
}
@At("/conf")
@Ok("beetl:/platform/sys/app/conf.html")
@RequiresPermissions("sys.operation.app")
public void conf() {
}
@At("/conf/data")
@Ok("json:{locked:'confData|password|salt',ignoreNull:false}")
@RequiresPermissions("sys.operation.app.conf")
public Object confData(@Param("confName") String confName, @Param("pageNumber") int pageNumber, @Param("pageSize") int pageSize, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {
try {
Cnd cnd = Cnd.NEW();
if (Strings.isNotBlank(confName)) {
cnd.and("confName", "like", "%" + confName + "%");
}
if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
cnd.orderBy(pageOrderName, PageUtil.getOrder(pageOrderBy));
}
return Result.success().addData(sysAppConfService.listPageLinks(pageNumber, pageSize, cnd, "^(user)$"));
} catch (Exception e) {
return Result.error();
}
}
@At("/conf/addDo")
@Ok("json")
@RequiresPermissions("sys.operation.app.conf")
@SLog(tag = "添加配置文件", msg = "应用名称:${sysAppConf.confName}")
public Object confAddDo(@Param("..") Sys_app_conf sysAppConf, HttpServletRequest req) {
try {
int num = sysAppConfService.count(Cnd.where("confName", "=", Strings.trim(sysAppConf.getConfName())).and("confVersion", "=", Strings.trim(sysAppConf.getConfVersion())));
if (num > 0) {
return Result.error("版本号已存在");
}
sysAppConf.setConfName(Strings.trim(sysAppConf.getConfName()));
sysAppConf.setConfVersion(Strings.trim(sysAppConf.getConfVersion()));
sysAppConf.setCreatedBy(ShiroUtil.getPlatformUid());
sysAppConfService.insert(sysAppConf);
return Result.success();
} catch (Exception e) {
return Result.error();
}
}
@At("/conf/search")
@Ok("json")
@RequiresPermissions("sys.operation.app.conf")
public Object confSearch(@Param("confName") String confName) {
return Result.NEW().addData(sysAppConfService.getConfNameList());
}
@At("/conf/delete/?")
@Ok("json")
@RequiresPermissions("sys.operation.app.conf")
@SLog(tag = "删除配置文件", msg = "ID:${id}")
public Object confDelete(String id, HttpServletRequest req) {
try {
sysAppConfService.delete(id);
return Result.success();
} catch (Exception e) {
return Result.error();
}
}
@At("/conf/enable/?")
@Ok("json")
@RequiresPermissions("sys.operation.app.conf")
@SLog(tag = "启用配置文件", msg = "ID:${id}")
public Object confEnable(String id, HttpServletRequest req) {
try {
sysAppConfService.update(Chain.make("disabled", false), Cnd.where("id", "=", id));
return Result.success();
} catch (Exception e) {
return Result.error();
}
}
@At("/conf/disable/?")
@Ok("json")
@RequiresPermissions("sys.operation.app.conf")
@SLog(tag = "禁用配置文件", msg = "ID:${id}")
public Object confDisable(String id, HttpServletRequest req) {
try {
sysAppConfService.update(Chain.make("disabled", true), Cnd.where("id", "=", id));
return Result.success();
} catch (Exception e) {
return Result.error();
}
}
@At("/conf/download/?")
@Ok("void")
@RequiresPermissions("sys.operation.app.conf")
public void confDownload(String id, HttpServletResponse response) {
try {
Sys_app_conf conf = sysAppConfService.fetch(id);
String fileName = conf.getConfName() + "-" + conf.getConfVersion() + ".properties";
response.setHeader("Content-Type", "text/plain");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
try (InputStream in = new StringInputStream(conf.getConfData())) {
Streams.writeAndClose(response.getOutputStream(), in);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
@At("/conf/edit/?")
@Ok("json")
@RequiresPermissions("sys.operation.app.conf")
public Object confEdit(@Param("id") String id) {
return Result.NEW().addData(sysAppConfService.fetch(id));
}
@At("/conf/editDo")
@Ok("json")
@RequiresPermissions("sys.operation.app.conf")
@SLog(tag = "修改配置文件", msg = "应用名称:${sysAppConf.confName}")
public Object confEditDo(@Param("..") Sys_app_conf sysAppConf, HttpServletRequest req) {
try {
sysAppConf.setUpdatedBy(ShiroUtil.getPlatformUid());
sysAppConfService.updateIgnoreNull(sysAppConf);
return Result.success();
} catch (Exception e) {
return Result.error();
}
}
@At("/task/addDo")
@Ok("json")
@RequiresPermissions("sys.operation.app.instance")
@SLog(tag = "创建任务", msg = "应用名称:${appTask.getName()} 动作:${appTask.getAction()}")
public Object taskAddDo(@Param("..") Sys_app_task appTask, HttpServletRequest req) {
try {
Cnd cnd = Cnd.where("name", "=", appTask.getName()).and("action", "=", "stop")
.and("appVersion", "=", appTask.getAppVersion())
.and("confVersion", "=", appTask.getConfVersion())
.and("hostName", "=", appTask.getHostName())
.and("hostAddress", "=", appTask.getHostAddress())
.and(Cnd.exps("status", "=", 0).or("status", "=", 1));
if ("stop".equals(appTask.getAction())) {
cnd.and("processId", "=", appTask.getProcessId());
}
int num = sysAppTaskService.count(cnd);
if (num > 0) {
return Result.error("任务已存在,请耐心等待执行结果");
}
appTask.setUpdatedBy(ShiroUtil.getPlatformUid());
appTask.setStatus(0);
sysAppTaskService.insert(appTask);
return Result.success();
} catch (Exception e) {
return Result.error();
}
}
@At("/task/data")
@Ok("json:{locked:'confData',ignoreNull:false}")
@RequiresPermissions("sys.operation.app")
public Object taskData(@Param("pageNumber") int pageNumber, @Param("pageSize") int pageSize, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {
try {
Cnd cnd = Cnd.NEW();
if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
cnd.orderBy(pageOrderName, PageUtil.getOrder(pageOrderBy));
}
return Result.success().addData(sysAppTaskService.listPageLinks(pageNumber, pageSize, cnd, "^(user)$"));
} catch (Exception e) {
return Result.error();
}
}
@At("/task/cannel/?")
@Ok("json")
@RequiresPermissions("sys.operation.app.instance")
@SLog(tag = "取消任务", msg = "任务ID:${id}")
public Object taskAddDo(String id, HttpServletRequest req) {
try {
//加上status条件,防止执行前状态已变更
sysAppTaskService.update(Chain.make("status", 4), Cnd.where("id", "=", id).and("status", "=", 0));
return Result.success();
} catch (Exception e) {
return Result.error();
}
}
@At
@Ok("json")
@RequiresPermissions("sys.operation.app.loglevel")
public Object loglevel(@Param("action") String action, @Param("name") String name, @Param("processId") String processId, @Param("loglevel") String loglevel) {
try {
LoglevelCommand loglevelCommand = new LoglevelCommand();
loglevelCommand.setAction(action);
loglevelCommand.setLevel(loglevel);
if ("processId".equals(action)) {
loglevelCommand.setProcessId(processId);
}
loglevelCommand.setName(name);
loglevelService.changeLoglevel(loglevelCommand);
return Result.success();
} catch (Exception e) {
return Result.error();
}
}
}
@@ -0,0 +1,148 @@
package io.v.nutz.sys.controllers.platform.sys;
import cn.wizzer.framework.base.Result;
import io.v.nutz.base.annontation.ViReturn;
import io.v.nutz.sys.models.SysAppMenu;
import io.v.nutz.sys.models.SysAppModule;
import io.v.nutz.sys.models.Sys_role;
import io.v.nutz.web.commons.utils.ShiroUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Lang;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import java.util.List;
import java.util.stream.Collectors;
/**
* app菜单
*
* @author jug
* @date 2023/03/09
*/
@IocBean
@At("/platform/sys/appMenu")
@Ok("json:full")
public class SysAppMenuController {
@Inject
private Dao dao;
@At("")
@Ok("beetl:/platform/sys/appMenu/index.html")
@RequiresPermissions("sys.appMenu.list")
public void index() {
}
@At
@RequiresPermissions("sys.appMenu.list")
public Object saveModule(SysAppModule appModule) {
int count = dao.count(SysAppModule.class, Cnd.where("moduleName", "=", appModule.getModuleName()));
if (count > 0) {
return Result.error("模块名称已存在!");
}
dao.insert(appModule);
return Result.success();
}
@At
@Aop(TransAop.READ_COMMITTED)
@RequiresPermissions("sys.appMenu.list")
public Object delModule(String id) {
dao.delete(SysAppModule.class, id);
dao.clear(SysAppMenu.class, Cnd.where("moduleId", "=", id));
return Result.success();
}
@At
@RequiresPermissions("sys.appMenu.list")
public Result updateModule(SysAppModule appModule) {
dao.update(appModule);
return Result.success();
}
@At
@RequiresPermissions("sys.appMenu.list")
public Result moduleList() {
List<SysAppModule> list = dao.query(SysAppModule.class, Cnd.NEW().asc("orderNum"));
return Result.success(list);
}
@At
@RequiresPermissions("sys.appMenu.list")
public Result roles() {
List<Sys_role> roles = dao.query(Sys_role.class, Cnd.NEW().asc("serialNumber"));
return Result.success(roles);
}
@At
@RequiresPermissions("sys.appMenu.list")
public Result saveMenu(@Param("appMenu") SysAppMenu appMenu) {
dao.insert(appMenu);
return Result.success();
}
@At
@Aop(TransAop.READ_COMMITTED)
@RequiresPermissions("sys.appMenu.list")
public Result delMenu(String id) {
dao.delete(SysAppMenu.class, id);
return Result.success();
}
@At
@RequiresPermissions("sys.appMenu.list")
public Result updateMenu(@Param("appMenu") SysAppMenu appMenu) {
dao.update(appMenu);
return Result.success();
}
@At
@RequiresPermissions("sys.appMenu.list")
@ViReturn
public Result menuList(String moduleId, @Param(value = "menuName", required = false) String menuName) {
List<SysAppMenu> list = dao.query(SysAppMenu.class, Cnd.NEW().and("moduleId", "=", moduleId)
.and(Cnd.likeEX("menuName", menuName))
.asc("orderNum"));
return Result.success(list);
}
/**
* 手机端菜单
*
* @return {@link Result}
*/
@At
@ViReturn
public Result appMenus() {
List<SysAppModule> appModules = dao.query(SysAppModule.class, Cnd.NEW().asc("orderNum"));
dao.fetchLinks(appModules, "menuList", Cnd.NEW().and("enable", "=", 1).asc("orderNum"));
for (SysAppModule appModule : appModules) {
List<SysAppMenu> menuList = appModule.getMenuList();
List<SysAppMenu> filterMenus = menuList.stream().filter(v -> ShiroUtil.hasAnyRoles(v.getMenuRoles()) || ShiroUtil.hasRole("sysadmin")).collect(Collectors.toList());
appModule.setMenuList(filterMenus);
}
return Result.success(appModules.stream().filter(v -> Lang.isNotEmpty(v.getMenuList())).collect(Collectors.toList()));
}
@At
@ViReturn
@Aop(TransAop.READ_COMMITTED)
public Result sortMenus(String moduleId, @Param("menuIds") String[] menuIds) {
for (int i = 0; i < menuIds.length; i++) {
dao.update(SysAppMenu.class, Chain.make("orderNum", i + 1), Cnd.where("menuId", "=", menuIds[i]).and("moduleId", "=", moduleId));
}
return null;
}
}
@@ -0,0 +1,77 @@
package io.v.nutz.sys.controllers.platform.sys;
import cn.hutool.core.date.DateUtil;
import io.v.nutz.base.annontation.ViReturn;
import io.v.nutz.base.service.BaseService;
import io.v.nutz.base.dao.CndPlus;
import io.v.nutz.zhgh.mainPage.models.NeedItems;
import io.v.nutz.zhgh.mainPage.service.MainPageNeedItemsService;
import io.v.nutz.sys.models.Sys_completed;
import io.v.nutz.web.commons.utils.ShiroUtil;
import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@IocBean
@At("/platform/sys/completed")
@Ok("json")
public class SysCompletedController {
@Inject
private BaseService baseService;
@Inject
private MainPageNeedItemsService mainPageNeedItemsService;
@At
@ViReturn
public Object getCompletes(){
CndPlus cnd = CndPlus.create();
cnd.and("auditBy","=", ShiroUtil.getPrincipalProperty("id"));
cnd.and("YEAR(auditTime)","=",DateUtil.thisYear());
cnd.desc("auditTime");
return baseService.dao().query(Sys_completed.class,cnd);
}
@At
@ViReturn
@Aop(TransAop.READ_COMMITTED)
public Object addCompletes(@Param("data") NeedItems[] items){
//审核完成前的待办
List<NeedItems> itemsList = Arrays.asList(items);
//审核完成后的待办
List<NeedItems> needItemsList = mainPageNeedItemsService.getNeedItems();
//过滤没有移动端地址和数量为0的待办
List<NeedItems> needItems = needItemsList.stream().filter(v-> v.getCount()>0 && Strings.isNotBlank(v.getMobileHref())).collect(Collectors.toList());
//审核前与审核后待办取差集
List<NeedItems> list = itemsList.stream().filter(item -> !needItems.contains(item) && item.getCount()>0).collect(Collectors.toList());
//上差集会出现两条记录,差集与审核完成前的待办取交集
List<NeedItems> collect = itemsList.stream().filter(list::contains).collect(Collectors.toList());
//添加已办
if (!collect.isEmpty()){
List<Sys_completed> completes = new ArrayList<>();
collect.forEach(v->{
Sys_completed completed = new Sys_completed();
completed.setModuleName(v.getTitle());
completed.setAuditBy((String) ShiroUtil.getPrincipalProperty("id"));
completed.setAuditTime(DateUtil.dateSecond());
completed.setAuditState(v.getName());
completed.setMobileUrl(v.getMobileHref());
completes.add(completed);
});
baseService.dao().insert(completes);
}
return null;
}
}
@@ -0,0 +1,132 @@
package io.v.nutz.sys.controllers.platform.sys;
import io.v.nutz.base.result.Result;
import io.v.nutz.base.utils.PageUtil;
import io.v.nutz.sys.models.Sys_config;
import io.v.nutz.sys.services.SysConfigService;
import io.v.nutz.web.commons.slog.annotation.SLog;
import io.v.nutz.web.commons.utils.ShiroUtil;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Cnd;
import org.nutz.integration.jedis.pubsub.PubSubService;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import java.util.Optional;
;
/**
* Created by wizzer on 2016/6/28.
*/
@IocBean
@At("/platform/sys/conf")
public class SysConfController {
private static final Log log = Logs.get();
@Inject
private SysConfigService sysConfigService;
@Inject
private PubSubService pubSubService;
@At("")
@Ok("beetl:/platform/sys/conf/index.html")
@RequiresPermissions("sys.manager.conf")
public void index() {
}
@At
@Ok("json")
@RequiresPermissions("sys.manager.conf.add")
@SLog(tag = "添加参数", msg = "${conf.configKey}:${conf.configValue}")
public Object addDo(@Param("..") Sys_config conf) {
try {
conf.setCreatedBy(ShiroUtil.getPlatformUid());
if (sysConfigService.insert(conf) != null) {
pubSubService.fire("nutzwk:web:platform", "sys_config");
}
return Result.success();
} catch (Exception e) {
return Result.error();
}
}
@At("/edit/?")
@Ok("json")
@RequiresPermissions("sys.manager.conf")
public Object edit(String id) {
try {
return Result.success().addData(sysConfigService.fetch(id));
} catch (Exception e) {
return Result.error();
}
}
@At
@Ok("json")
@RequiresPermissions("sys.manager.conf.edit")
@SLog(tag = "修改参数", msg = "${conf.configKey}:${conf.configValue}")
public Object editDo(@Param("..") Sys_config conf) {
try {
conf.setUpdatedBy(ShiroUtil.getPlatformUid());
if (sysConfigService.updateIgnoreNull(conf) > 0) {
pubSubService.fire("nutzwk:web:platform", "sys_config");
}
return Result.success();
} catch (Exception e) {
return Result.error();
}
}
@At("/delete/?")
@Ok("json")
@RequiresPermissions("sys.manager.conf.delete")
@SLog(tag = "删除参数", msg = "参数:${configKey}")
public Object delete(String configKey) {
try {
if (Strings.sBlank(configKey).startsWith("App")) {
return Result.error("系统参数不可删除");
}
if (sysConfigService.delete(configKey) > 0) {
pubSubService.fire("nutzwk:web:platform", "sys_config");
}
return Result.success();
} catch (Exception e) {
return Result.error();
}
}
@At
@Ok("json:full")
@RequiresPermissions("sys.manager.conf")
public Object data(@Param("pageNumber") int pageNumber, @Param("pageSize") int pageSize, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {
try {
Cnd cnd = Cnd.NEW();
if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
cnd.orderBy(pageOrderName, PageUtil.getOrder(pageOrderBy));
}
return Result.success().addData(sysConfigService.listPage(pageNumber, pageSize, cnd));
} catch (Exception e) {
return Result.error();
}
}
@At
@Ok("json:full")
@RequiresAuthentication
public Object getValue(@Param("key") String key) {
try {
Sys_config configKey = sysConfigService.fetch(Cnd.where("configKey", "=", key));
return Result.success().addData(Optional.ofNullable(configKey).map(v -> v.getConfigValue()).orElse(null));
} catch (Exception e) {
return Result.error();
}
}
}
@@ -0,0 +1,256 @@
package io.v.nutz.sys.controllers.platform.sys;
import io.v.nutz.base.result.Result;
import io.v.nutz.sys.models.Sys_dict;
import io.v.nutz.sys.services.SysDictService;
import io.v.nutz.web.commons.slog.annotation.SLog;
import io.v.nutz.web.commons.utils.ShiroUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
;
/**
* Created by wizzer on 2016/6/24.
*/
@IocBean
@At("/platform/sys/dict")
public class SysDictController {
private static final Log log = Logs.get();
@Inject
private SysDictService sysDictService;
@At("")
@Ok("beetl:/platform/sys/dict/index.html")
@RequiresPermissions("sys.manager.dict")
public Object index() {
return sysDictService.query(Cnd.where("parentId", "=", "").or("parentId", "is", null).asc("location").asc("path"));
}
@At("/child")
@Ok("json")
@RequiresAuthentication
public Object child(@Param("pid") String pid, HttpServletRequest req) {
List<Sys_dict> list = new ArrayList<>();
List<NutMap> treeList = new ArrayList<>();
Cnd cnd = Cnd.NEW();
if (Strings.isBlank(pid)) {
cnd.and("parentId", "=", "").or("parentId", "is", null);
} else {
cnd.and("parentId", "=", pid);
}
cnd.asc("location").asc("path");
list = sysDictService.query(cnd);
for (Sys_dict sysDict : list) {
if (sysDictService.count(Cnd.where("parentId", "=", sysDict.getId())) > 0) {
sysDict.setHasChildren(true);
}
NutMap map = Lang.obj2nutmap(sysDict);
map.addv("expanded", false);
map.addv("children", new ArrayList<>());
treeList.add(map);
}
return Result.success().addData(treeList);
}
@At("/tree")
@Ok("json")
@RequiresAuthentication
public Object tree(@Param("pid") String pid, HttpServletRequest req) {
try {
List<NutMap> treeList = new ArrayList<>();
if (Strings.isBlank(pid)) {
NutMap root = NutMap.NEW().addv("value", "root").addv("label", "不选择菜单").addv("leaf",true);
treeList.add(root);
}
Cnd cnd = Cnd.NEW();
if (Strings.isBlank(pid)) {
cnd.and("parentId", "=", "").or("parentId", "is", null);
} else {
cnd.and("parentId", "=", pid);
}
cnd.asc("location").asc("path");
List<Sys_dict> list = sysDictService.query(cnd);
for (Sys_dict sysDict : list) {
NutMap map = NutMap.NEW().addv("value", sysDict.getId()).addv("label", sysDict.getName());
if (sysDict.isHasChildren()) {
map.addv("children", new ArrayList<>());
map.addv("leaf",false);
}else {
map.addv("leaf",true);
}
treeList.add(map);
}
return Result.success().addData(treeList);
} catch (Exception e) {
return Result.error();
}
}
@At
@Ok("json")
@RequiresPermissions("sys.manager.dict.add")
@SLog(tag = "新建字典", msg = "字典名称:${args[0].name}")
public Object addDo(@Param("..") Sys_dict dict, @Param(value = "parentId",df = "") String parentId, HttpServletRequest req) {
try {
if("root".equals(parentId)){
parentId="";
}
dict.setHasChildren(false);
dict.setCreatedBy(ShiroUtil.getPlatformUid());
sysDictService.save(dict, parentId);
sysDictService.clearCache();
return Result.success("system.success");
} catch (Exception e) {
return Result.error("system.error");
}
}
@At("/edit/?")
@Ok("json")
@RequiresPermissions("sys.manager.dict")
public Object edit(String id, HttpServletRequest req) {
try {
return Result.success().addData(sysDictService.fetch(id));
} catch (Exception e) {
return Result.error();
}
}
@At
@Ok("json")
@RequiresPermissions("sys.manager.dict.edit")
@SLog(tag = "编辑字典", msg = "字典名称:${args[0].name}")
public Object editDo(@Param("..") Sys_dict dict, @Param("parentId") String parentId, HttpServletRequest req) {
try {
dict.setUpdatedBy(ShiroUtil.getPlatformUid());
sysDictService.updateIgnoreNull(dict);
sysDictService.clearCache();
return Result.success();
} catch (Exception e) {
return Result.error();
}
}
@At("/delete/?")
@Ok("json")
@RequiresPermissions("sys.manager.dict.delete")
@SLog(tag = "删除字典", msg = "字典名称:${args[1].getAttribute('name')}")
public Object delete(String id, HttpServletRequest req) {
try {
Sys_dict dict = sysDictService.fetch(id);
req.setAttribute("name", dict.getName());
sysDictService.delete(id);
sysDictService.clear(Cnd.where("parentId", "=", id));
sysDictService.deleteAndChild(dict);
sysDictService.clearCache();
return Result.success();
} catch (Exception e) {
return Result.error();
}
}
@At("/enable/?")
@Ok("json")
@RequiresPermissions("sys.manager.dict.edit")
@SLog(tag = "启用菜单", msg = "菜单名称:${args[1].getAttribute('name')}")
public Object enable(String menuId, HttpServletRequest req) {
try {
req.setAttribute("name", sysDictService.fetch(menuId).getName());
sysDictService.update(org.nutz.dao.Chain.make("disabled", false), Cnd.where("id", "=", menuId));
sysDictService.clearCache();
return Result.success();
} catch (Exception e) {
return Result.error();
}
}
@At("/disable/?")
@Ok("json")
@RequiresPermissions("sys.manager.dict.edit")
@SLog(tag = "禁用菜单", msg = "菜单名称:${args[1].getAttribute('name')}")
public Object disable(String menuId, HttpServletRequest req) {
try {
req.setAttribute("name", sysDictService.fetch(menuId).getName());
sysDictService.update(org.nutz.dao.Chain.make("disabled", true), Cnd.where("id", "=", menuId));
sysDictService.clearCache();
return Result.success();
} catch (Exception e) {
return Result.error();
}
}
@At("/menuAll")
@Ok("json")
@RequiresPermissions("sys.manager.dict")
public Object menuAll(HttpServletRequest req) {
try {
List<Sys_dict> list = sysDictService.query(Cnd.NEW().asc("location").asc("path"));
NutMap menuMap = NutMap.NEW();
for (Sys_dict unit : list) {
List<Sys_dict> list1 = menuMap.getList(unit.getParentId(), Sys_dict.class);
if (list1 == null) {
list1 = new ArrayList<>();
}
list1.add(unit);
menuMap.put(unit.getParentId(), list1);
}
return Result.success().addData(getTree(menuMap, ""));
} catch (Exception e) {
return Result.error();
}
}
private List<NutMap> getTree(NutMap menuMap, String pid) {
List<NutMap> treeList = new ArrayList<>();
List<Sys_dict> subList = menuMap.getList(pid, Sys_dict.class);
for (Sys_dict menu : subList) {
NutMap map = Lang.obj2nutmap(menu);
map.put("label", menu.getName());
if (menu.isHasChildren() || (menuMap.get(menu.getId()) != null)) {
map.put("children", getTree(menuMap, menu.getId()));
}
treeList.add(map);
}
return treeList;
}
@At
@Ok("json")
@RequiresPermissions("sys.manager.dict.edit")
public Object sortDo(@Param("ids") String ids, HttpServletRequest req) {
try {
String[] menuIds = StringUtils.split(ids, ",");
int i = 0;
sysDictService.execute(Sqls.create("update sys_dict set location=0"));
for (String s : menuIds) {
if (!Strings.isBlank(s)) {
sysDictService.update(org.nutz.dao.Chain.make("location", i), Cnd.where("id", "=", s));
i++;
}
}
sysDictService.clearCache();
return Result.success();
} catch (Exception e) {
return Result.error();
}
}
}
@@ -0,0 +1,107 @@
package io.v.nutz.sys.controllers.platform.sys;
import cn.wizzer.framework.base.Result;
import io.v.nutz.sys.models.Sys_dq;
import io.v.nutz.sys.models.Sys_gx;
import io.v.nutz.sys.services.SysDqService;
import io.v.nutz.sys.services.SysGxService;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.Record;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import java.util.List;
/**
* 高校地区管理
* 何鹏飞
* 15:54 2019/7/26
*/
@At("/platform/sys/dq")
@IocBean
public class SysDqController {
private Log log = Logs.get();
@At("")
@Ok("beetl:/platform/sys/unit/dqindex.html")
public void index() {
}
@Inject
private SysDqService sysDqService;
@Inject
private SysGxService sysGxService;
@At
@Ok("json")
public Object data(@Param("searchKeyword") String searchKeyword, @Param("searchName") String searchName) {
Cnd cnd = Cnd.NEW();
if (Strings.isNotBlank(searchKeyword)) {
cnd.and("dq_name", "like", "%" + searchKeyword + "%");
}
if (Strings.isNotBlank(searchName)) {
cnd.and("gxid", "=", searchName);
}
Sql sql = Sqls.create("select * FROM sys_dq LEFT JOIN sys_gx on sys_dq.gx_id=sys_gx.gxid $condition");
sql.setCondition(cnd);
List<Record> list = sysDqService.list(sql);
List<Sys_gx> gxs = sysGxService.query();
NutMap nutMap = new NutMap();
nutMap.put("dq", list);
nutMap.put("gx", gxs);
return Result.success().addData(nutMap);
}
@At
@Ok("json")
public Object add(Sys_dq sys_dq) {
try {
sysDqService.insert(sys_dq);
return Result.success().addMsg("添加成功");
} catch (Exception e) {
e.printStackTrace();
return Result.error().addMsg("添加失败");
}
}
@At
@Ok("json")
public Object upd(Sys_dq sys_dq) {
try {
sysDqService.update(sys_dq);
return Result.success().addMsg("修改成功");
} catch (Exception e) {
e.printStackTrace();
return Result.error().addMsg("修改失败");
}
}
@At
@Ok("json")
public Object del(String dq_id) {
try {
sysDqService.delete(dq_id);
return Result.success().addMsg("删除成功");
} catch (Exception e) {
e.printStackTrace();
return Result.error().addMsg("删除失败");
}
}
}
@@ -0,0 +1,228 @@
package io.v.nutz.sys.controllers.platform.sys;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import io.v.nutz.base.annontation.ViReturn;
import io.v.nutz.sys.models.SysEntranceModule;
import io.v.nutz.sys.models.SysUserEntrance;
import io.v.nutz.sys.models.Sys_menu;
import io.v.nutz.sys.models.Sys_user;
import io.v.nutz.sys.services.SysUserService;
import io.v.nutz.web.commons.utils.ShiroUtil;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Lang;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.nutz.trans.Trans;
import java.util.List;
import java.util.stream.Collectors;
/**
* @FileName io.v.nutz.web.controllers.platform.sys.SysEntranceModuleController
* @Description: TODO
* @Author zxc
* @Date 2022/8/31:10:50
* @Version V1.0
**/
@IocBean
@At("/platform/sys/entranceModule")
@Ok("json:full")
public class SysEntranceModuleController {
@Inject
private Dao dao;
@Inject
private SysUserService sysUserService;
@At("")
@Ok("beetl:/platform/sys/entranceModule/index.html")
@RequiresPermissions("sys.entrance.module")
public void index() {
}
/**
* 页面数据
*
* @return {@link Object}
*/
@At
@ViReturn
@RequiresAuthentication
public Object pageData() {
Cnd cnd = Cnd.NEW();
cnd.asc("sortNum");
return dao.query(SysEntranceModule.class, cnd);
}
/**
* 做添加
*
* @param entranceModule 入口模块
* @return {@link Object}
*/
@At
@ViReturn
@RequiresAuthentication
public Object doAdd(@Param("entranceModule") SysEntranceModule entranceModule) {
Integer maxNum = (Integer) dao.func2(SysEntranceModule.class, "max", "sortNum");
if (maxNum == null) {
maxNum = 0;
}
entranceModule.setSortNum(maxNum + 1);
dao.insert(entranceModule);
return null;
}
/**
* 做编辑
*
* @param entranceModule 入口模块
* @return {@link Object}
*/
@At
@ViReturn
@RequiresAuthentication
public Object doEdit(@Param("entranceModule") SysEntranceModule entranceModule) {
dao.update(entranceModule);
return null;
}
/**
* 做删除
*
* @param id id
* @return {@link Object}
*/
@At("/doDelete/?")
@ViReturn
@RequiresAuthentication
public Object doDelete(String id) {
Assert.notBlank(id);
SysEntranceModule entranceModule = dao.fetch(SysEntranceModule.class, id);
int sortNum = entranceModule.getSortNum();
List<SysEntranceModule> gtEntranceModules = dao.query(SysEntranceModule.class, Cnd.where("sortNum", ">", sortNum));
for (SysEntranceModule module : gtEntranceModules) {
module.setSortNum(module.getSortNum() - 1);
}
Trans.exec(() -> {
dao.delete(entranceModule);
dao.update(gtEntranceModules);
});
return null;
}
/**
* 获取首级菜单
*
* @return {@link Object}
*/
@At
@ViReturn
@RequiresAuthentication
public Object findFirstMenus() {
Cnd cnd = Cnd.NEW();
cnd.and("disabled", "=", 0);
cnd.and(Cnd.exps("parentId", "is", null).or("parentId", "=", ""));
cnd.and("type", "=", "menu");
cnd.asc("location");
return dao.query(Sys_menu.class, cnd);
}
/**
* 获取用户需要显示的入口模块
*
* @return {@link Object}
*/
@At
@ViReturn
@RequiresAuthentication
public Object getEntranceModule() {
Sys_user principal = (Sys_user) ShiroUtil.getPrincipal();
assert principal != null;
List<Sys_menu> userMenus = principal.getMenus();
List<String> firstUserMenuIds = userMenus.stream().filter(v -> StrUtil.isBlank(v.getParentId()) && "menu".equals(v.getType())).map(v -> v.getId()).collect(Collectors.toList());
List<SysEntranceModule> entranceModules = dao.query(SysEntranceModule.class, Cnd.NEW().asc("sortNum"));
List<SysEntranceModule> finalEntranceModules = entranceModules.stream().filter(v -> v.getContainsMenu().stream().anyMatch(firstUserMenuIds::contains)).collect(Collectors.toList());
return finalEntranceModules;
}
/**
* 得到第二个菜单
*
* @return {@link Object}
*/
@At
@ViReturn
@RequiresAuthentication
public Object getSecondMenus() {
Sys_user principal = (Sys_user) ShiroUtil.getPrincipal();
return principal.getSecondMenus();
}
/**
* 根据模块获取菜单
*
* @param entranceModuleId 入口模块id
* @return {@link Object}
*/
@At
@ViReturn
@RequiresAuthentication
public Object getFirstMenus(@Param(value = "entranceModuleId", required = false) String entranceModuleId) {
Sys_user principal = (Sys_user) ShiroUtil.getPrincipal();
List<Sys_menu> firstMenus = principal.getFirstMenus();
if (StrUtil.isBlank(entranceModuleId)) {
return firstMenus;
}
SysEntranceModule entranceModule = dao.fetch(SysEntranceModule.class, Cnd.where("id", "=", entranceModuleId));
List<String> containsMenu = entranceModule.getContainsMenu();
return firstMenus.stream().filter(v -> containsMenu.contains(v.getId())).collect(Collectors.toList());
}
@At
@ViReturn
@RequiresAuthentication
public Object getUserDefaultEntranceModuleId() {
SysUserEntrance sysUserEntrance = dao.fetch(SysUserEntrance.class, Cnd.where("userId", "=", ShiroUtil.getPrincipalProperty("id")));
if (Lang.isEmpty(sysUserEntrance)) {
return null;
}
return sysUserEntrance.getDefaultModuleId();
}
@At
@ViReturn
@RequiresAuthentication
public Object setUserDefaultEntranceModuleId(@Param("moduleId") String moduleId) {
SysUserEntrance sysUserEntrance = dao.fetch(SysUserEntrance.class, Cnd.where("userId", "=", ShiroUtil.getPrincipalProperty("id")));
if (Lang.isEmpty(sysUserEntrance)) {
sysUserEntrance = new SysUserEntrance();
sysUserEntrance.setUserId((String) ShiroUtil.getPrincipalProperty("id"));
}
sysUserEntrance.setDefaultModuleId(moduleId);
dao.insertOrUpdate(sysUserEntrance);
sysUserService.deleteCache(sysUserEntrance.getUserId());
return null;
}
@At
@ViReturn
@RequiresAuthentication
public Object getHasSetMenus() {
List<SysEntranceModule> list = dao.query(SysEntranceModule.class, Cnd.NEW());
return list.stream().map(SysEntranceModule::getContainsMenu).flatMap(List::stream).distinct().collect(Collectors.toList());
}
}
@@ -0,0 +1,69 @@
package io.v.nutz.sys.controllers.platform.sys;
import io.v.nutz.base.annontation.ViReturn;
import io.v.nutz.base.query.PageForm;
import io.v.nutz.sys.services.SysFileService;
import io.v.nutz.sys.services.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 文件管理
*
* @author jug
* @date 2023/06/08
*/
@IocBean
@At("/platform/sys/file")
@Slf4j
public class SysFileController {
@Inject
private SysUserService sysUserService;
@Inject
private SysFileService sysFileService;
@At("")
@Ok("beetl:/platform/sys/file/index.html")
@RequiresPermissions("sys.manager.file")
public void index() {
}
/**
* 页面数据
*
* @param pageForm 页面形式
* @return {@link Object}
*/
@At
@ViReturn
@RequiresPermissions("sys.manager.file")
public Object pageData(PageForm pageForm) {
Sql sql = Sqls.create("select * from sys_file $condition");
Cnd cnd = Cnd.NEW();
sql.setCondition(cnd);
return sysUserService.listPageMap(pageForm.getPageNumber(), pageForm.getPageSize(), sql);
}
@At
@Ok("void")
@ViReturn
@RequiresAuthentication
public void convertPDF(String id, HttpServletRequest request, HttpServletResponse response) throws IOException {
sysFileService.convertPDF(id, request, response);
}
}
@@ -0,0 +1,126 @@
package io.v.nutz.sys.controllers.platform.sys;
import cn.wizzer.framework.base.Result;
import io.v.nutz.base.utils.StringUtil;
import io.v.nutz.sys.models.Sys_gx;
import io.v.nutz.sys.services.SysGxService;
import io.v.nutz.sys.services.SysUnitService;
import io.v.nutz.web.commons.slog.annotation.SLog;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Cnd;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.Times;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
/**
* Created by lyx on 高校信息controller
*/
@IocBean
@At("/platform/sys/gx")
public class SysGxController {
private static final Log log = Logs.get();
@Inject
private SysGxService sysGxService;
@Inject
private SysUnitService sysUnitService;
@At("")
@Ok("beetl:/platform/sys/unit/gxindex.html")
@RequiresPermissions("sys.manager.gx")
public void index() {
}
@At("/data")
@Ok("json")
@RequiresAuthentication
public Object data(@Param("searchName") String searchName, @Param("searchKeyword") String searchKeyword, HttpServletRequest req) {
List<Sys_gx> list = new ArrayList<>();
List<NutMap> treeList = new ArrayList<>();
SqlExpressionGroup ea;
Cnd cnd = Cnd.NEW();
if (Strings.isNotBlank(searchName) && Strings.isNotBlank(searchKeyword)) {
cnd.and(searchName, "like", "%" + searchKeyword + "%");
}
cnd.asc("gxid");
list = sysGxService.query(cnd);
return Result.success().addData(list);
}
@At
@Ok("json")
@SLog(tag = "新建高校", msg = "高校名称:${args[0].gxname}")
public Object addDo(@Param("..") Sys_gx gx, HttpServletRequest req) {
try {
gx.setOpBy(StringUtil.getPlatformUid());
sysGxService.insert(gx);
return Result.success();
} catch (Exception e) {
return Result.error();
}
}
@At("/edit/?")
@Ok("json")
public Object edit(String id, HttpServletRequest req) {
try {
Sys_gx gx = sysGxService.fetch(id);
return Result.success().addData(gx);
} catch (Exception e) {
return Result.error();
}
}
@At
@Ok("json")
@SLog(tag = "编辑高校", msg = "高校名称:${args[0].gxname}")
public Object editDo(@Param("..") Sys_gx gx, HttpServletRequest req) {
try {
int c = sysGxService.count(Cnd.where("gxname", "=", gx.getGxname()));
if (c > 0) {
return Result.error("高校名称已经存在!");
}
gx.setOpBy(StringUtil.getPlatformUid());
gx.setOpAt(Times.getTS());
sysGxService.updateIgnoreNull(gx);
return Result.success();
} catch (Exception e) {
return Result.error();
}
}
@At("/delete/?")
@Ok("json")
@SLog(tag = "删除高校", msg = "高校名称:${args[1].getAttribute('gxname')}")
public Object delete(String id, HttpServletRequest req) {
try {
int unitcount = sysUnitService.count(Cnd.where("gxid", "=", id));
if (unitcount > 0) {
return Result.error("当前高校下有单位数据存在,不能删除!");
}
sysGxService.delete(id);
return Result.success();
} catch (Exception e) {
return Result.error();
}
}
}
@@ -0,0 +1,134 @@
package io.v.nutz.sys.controllers.platform.sys;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.wizzer.framework.base.Result;
import cn.wizzer.framework.page.Pagination;
import io.v.nutz.sys.models.Sys_home_activity;
import io.v.nutz.sys.param.SysHomeActivityPageForm;
import io.v.nutz.sys.services.SysHomeActivityService;
import io.v.nutz.web.commons.utils.ShiroUtil;
import io.v.nutz.zhgh.activity.models.ActivityUserScope;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.*;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.util.Daos;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Lang;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@IocBean
@At("/platform/sys/homeActivity")
@Ok("json:full")
public class SysHomeActivityController {
@Inject
private Dao dao;
@Inject
private SysHomeActivityService sysHomeActivityService;
@At("")
@Ok("beetl:/platform/sys/homeActivity/index.html")
@RequiresPermissions("sys.homeActivity")
public void index() {
}
@At
@RequiresPermissions("sys.homeActivity")
public Object pageData(SysHomeActivityPageForm pageForm) {
Cnd cnd = Cnd.NEW();
cnd.and(Cnd.likeEX("`name`",pageForm.getName()));
cnd.desc("sortNo");
Pagination pagination = sysHomeActivityService.listPage(pageForm.getPageNumber(), pageForm.getPageSize(), cnd);
return Result.success(pagination);
}
@At
@RequiresPermissions("sys.homeActivity")
public Object enable(@Valid String id) {
sysHomeActivityService.update(Chain.make("enable", 1), Cnd.where("id", "=", id));
return Result.success();
}
@At
@RequiresPermissions("sys.homeActivity")
public Object disable(@Valid String id) {
sysHomeActivityService.update(Chain.make("enable", 0), Cnd.where("id", "=", id));
return Result.success();
}
@At
@RequiresPermissions("sys.homeActivity")
public Object topUp(@Valid String id){
Sys_home_activity sysHomeActivity = new Sys_home_activity();
sysHomeActivity.setId(id);
sysHomeActivity.setTop(true);
sysHomeActivityService.updateIgnoreNull(sysHomeActivity);
return Result.success();
}
@At
@RequiresPermissions("sys.homeActivity")
public Object cancelTopUp(@Valid String id){
Sys_home_activity sysHomeActivity = new Sys_home_activity();
sysHomeActivity.setId(id);
sysHomeActivity.setTop(false);
sysHomeActivityService.updateIgnoreNull(sysHomeActivity);
return Result.success();
}
@At
@RequiresAuthentication
public Result listHomeActivity() {
FieldFilter fieldFilter = FieldFilter.locked(Sys_home_activity.class, "classPath");
List<Sys_home_activity> list = Daos.ext(dao,fieldFilter) .query(Sys_home_activity.class, Cnd.where("enable", "=", 1).desc("top"));
String userId = ShiroUtil.getUserId();
List<Sys_home_activity> allowActivityList = new ArrayList<>();
// 今天的时间
Date today = DateUtil.date();
for (Sys_home_activity activity : list) {
// 该活动的时间范围
Date startDate = activity.getStartDate();
Date endDate = activity.getEndDate();
// 判断当前时间是否在活动范围内不在就过滤掉
if (!DateUtil.isIn(today, startDate, endDate)) {
continue;
}
Integer allowUserGroupId = activity.getAllowUserGroupId();
String allowUserSql = activity.getAllowUserSql();
activity.setAllowUserSql(null);
if (allowUserGroupId == null && StrUtil.isBlank(allowUserSql)) {
allowActivityList.add(activity);
continue;
}
if (allowUserGroupId != null) {
int count = dao.count(ActivityUserScope.class, Cnd.where("groupId", "=", allowUserGroupId).and("userId", "=", userId));
if (count > 0) {
allowActivityList.add(activity);
continue;
}
}
if (StrUtil.isNotBlank(allowUserSql)){
Sql sql = Sqls.create(allowUserSql).setParam("userId", userId);
NutMap nutMap = (NutMap) Daos.query(dao, sql.toString(), Sqls.callback.map());
if (Lang.isNotEmpty(nutMap) && StrUtil.isNotBlank(nutMap.getString("userId"))) {
allowActivityList.add(activity);
}
}
}
return Result.success(allowActivityList);
}
}
@@ -0,0 +1,401 @@
package io.v.nutz.sys.controllers.platform.sys;
import cn.hutool.core.util.StrUtil;
import cn.wizzer.framework.base.Result;
import io.v.nutz.base.enums.Env;
import io.v.nutz.base.service.BaseService;
import io.v.nutz.sys.models.Sys_home_activity;
import io.v.nutz.sys.models.Sys_menu;
import io.v.nutz.sys.services.SysMenuService;
import io.v.nutz.sys.services.SysUserService;
import io.v.nutz.web.commons.base.Globals;
import io.v.nutz.web.commons.utils.ShiroUtil;
import io.v.nutz.zhgh.activity.models.ActivityUserScope;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.FieldFilter;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.util.Daos;
import org.nutz.integration.jedis.RedisService;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import javax.net.ssl.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Created by wizzer on 2016/6/23.
*/
@IocBean
@At("/platform/home")
public class SysHomeController {
@Inject
private SysMenuService sysMenuService;
@Inject
private SysUserService sysUserService;
@Inject
private BaseService baseService;
@Inject
private Dao dao;
@Inject
private RedisService redisService;
@At("")
@Ok("beetl:/platform/sys/home/index.html")
@RequiresAuthentication
public void home(HttpSession session, HttpServletRequest request) {
}
@At
@Ok("beetl:/platform/sys/left.html")
@RequiresAuthentication
public void left(@Param("url") String url, HttpServletRequest req) {
String path = "";
String perpath = "";
url = Strings.sNull(url).trim();
if (!Strings.isBlank(Globals.AppBase)) {
url = Strings.sBlank(url).substring(Globals.AppBase.length());
}
if (Strings.sBlank(url).indexOf("?") > 0)
url = url.substring(0, url.indexOf("?"));
Sys_menu menu = sysMenuService.getLeftMenu(url);
if (menu != null) {
if (menu.getPath().length() >= 8) {
path = menu.getPath().substring(0, 8);
perpath = menu.getPath().substring(0, 4);
}
req.setAttribute("mpath", menu.getPath());
}
req.setAttribute("path", path);
req.setAttribute("perpath", perpath);
}
@At
@Ok("beetl:/platform/sys/left.html")
@RequiresAuthentication
public void path(@Param("url") String url, HttpServletRequest req) {
url = Strings.sNull(url).trim();
if (Strings.sBlank(url).indexOf("//") > 0) {
String[] u = url.split("//");
String s = u[1].substring(u[1].indexOf("/"));
if (Strings.sBlank(s).indexOf("?") > 0)
s = s.substring(0, s.indexOf("?"));
if (!Strings.isBlank(Globals.AppBase)) {
s = s.substring(Globals.AppBase.length());
}
String[] urls = s.split("/");
List<String> list = new ArrayList<>();
if (urls.length > 5) {
list.add("/" + urls[1] + "/" + urls[2] + "/" + urls[3] + "/" + urls[4] + "/" + urls[5]);
list.add("/" + urls[1] + "/" + urls[2] + "/" + urls[3] + "/" + urls[4]);
list.add("/" + urls[1] + "/" + urls[2] + "/" + urls[3]);
list.add("/" + urls[1] + "/" + urls[2]);
list.add("/" + urls[1]);
} else if (urls.length == 5) {
list.add("/" + urls[1] + "/" + urls[2] + "/" + urls[3] + "/" + urls[4]);
list.add("/" + urls[1] + "/" + urls[2] + "/" + urls[3]);
list.add("/" + urls[1] + "/" + urls[2]);
list.add("/" + urls[1]);
} else if (urls.length == 4) {
list.add("/" + urls[1] + "/" + urls[2] + "/" + urls[3]);
list.add("/" + urls[1] + "/" + urls[2]);
list.add("/" + urls[1]);
} else if (urls.length == 3) {
list.add("/" + urls[1] + "/" + urls[2]);
list.add("/" + urls[1]);
} else if (urls.length == 2) {
list.add("/" + urls[1]);
} else list.add(url);
String path = "";
String perpath = "";
Sys_menu menu = sysMenuService.getLeftPathMenu(list);
if (menu != null) {
if (menu.getPath().length() >= 8) {
path = menu.getPath().substring(0, 8);
perpath = menu.getPath().substring(0, 4);
}
req.setAttribute("mpath", menu.getPath());
}
req.setAttribute("path", path);
req.setAttribute("perpath", perpath);
}
}
@At(value = {"/", "/index"}, top = true)
@Ok("re")
public String index(HttpServletRequest request) {
if (Globals.isEnv(Env.prod)) {
ArrayList<String> mobileAgentList = Lang.list("android", "iphone", "ipad");
String userAgent = request.getHeader("user-agent");
if (StrUtil.isBlank(userAgent)) {
return ">>:/error/500.html";
}
boolean isMobile = mobileAgentList.stream().anyMatch(v -> userAgent.toLowerCase().contains(v.toLowerCase()));
if (isMobile) {
return ">>:/mobile/index";
} else {
return ">>:/platform/home";
}
}
return ">>:/sysadmin";
}
@At
@Ok("json:full")
@RequiresAuthentication
public Object clearCache() {
sysUserService.deleteCacheAndUpdate(ShiroUtil.getUserId());
return Result.success();
}
/**
* 首页日历展示的信息
*
* @return {@link Result}
*/
@At
@Ok("json:full")
@RequiresAuthentication
public Result activityInfo() {
Sql sql = Sqls.create("""
SELECT
t.id,
t.`name`,
t.applyStartTime,
t.applyEndTime,
t.startTime,
t.endTime,
t.address,
t.type,
t.signUpMethod,
t.projectTypeCode
FROM
`activity_tissue` t
INNER JOIN activity_user_scope aus ON aus.groupId = t.groupId
AND aus.userId = @userId AND t.isDisabled is TRUE AND t.state=3
""");
sql.setParam("userId", ShiroUtil.getUserId());
return Result.success(baseService.listMap(sql));
}
@At
@Ok("json:full")
@RequiresAuthentication
public Result listHomeActivity() {
FieldFilter fieldFilter = FieldFilter.locked(Sys_home_activity.class, "classPath");
List<Sys_home_activity> list = Daos.ext(dao, fieldFilter).query(Sys_home_activity.class, Cnd.where("enable", "=", 1).desc("top"));
String userId = ShiroUtil.getUserId();
List<Sys_home_activity> allowActivityList = new ArrayList<>();
for (Sys_home_activity activity : list) {
Integer allowUserGroupId = activity.getAllowUserGroupId();
String allowUserSql = activity.getAllowUserSql();
activity.setAllowUserSql(null);
if (allowUserGroupId == null && StrUtil.isBlank(allowUserSql)) {
allowActivityList.add(activity);
continue;
}
if (allowUserGroupId != null) {
int count = dao.count(ActivityUserScope.class, Cnd.where("groupId", "=", allowUserGroupId).and("userId", "=", userId));
if (count > 0) {
allowActivityList.add(activity);
continue;
}
}
if (StrUtil.isNotBlank(allowUserSql)) {
Sql sql = Sqls.create(allowUserSql).setParam("userId", userId);
NutMap nutMap = (NutMap) Daos.query(dao, sql.toString(), Sqls.callback.map());
if (Lang.isNotEmpty(nutMap)) {
allowActivityList.add(activity);
}
}
}
return Result.success(allowActivityList);
}
@At("/403")
@Ok("re")
public Object error403(HttpServletRequest req) {
if (Strings.sNull(req.getAttribute("original_request_uri")).startsWith("/platform") && io.v.nutz.web.commons.utils.ShiroUtil.isAuthenticated()) {
return "beetl:/platform/sys/403.html";
} else {
return ">>:/error/403.html";
}
}
@At("/404")
@Ok("re")
public Object error404(HttpServletRequest req) {
if (Strings.sNull(req.getAttribute("original_request_uri")).startsWith("/platform") && io.v.nutz.web.commons.utils.ShiroUtil.isAuthenticated()) {
return "beetl:/platform/sys/404.html";
} else {
return ">>:/error/404.html";
}
}
@At("/500")
@Ok("re")
public Object error500(HttpServletRequest req) {
if (Strings.sNull(req.getAttribute("original_request_uri")).startsWith("/platform") && io.v.nutz.web.commons.utils.ShiroUtil.isAuthenticated()) {
return "beetl:/platform/sys/500.html";
} else {
return ">>:/error/500.html";
}
}
@At("/lockedAccountError")
@Ok("re")
public Object lockedAccountError() {
return ">>:/error/lockedAccountError.html";
}
@At("/UnknownAccountError")
@Ok("re")
public Object UnknownAccountError() {
return ">>:/error/UnknownAccountError.html";
}
@At("/AuthenticationError")
@Ok("re")
public Object AuthenticationError() {
return ">>:/error/AuthenticationError.html";
}
/**
* 工会网站新闻
*
* @return
*/
@At
@RequiresAuthentication
@Ok("json")
public Result getNews() {
try {
String gonghuiNews = redisService.get("gonghui_news");
if(Strings.isNotBlank(gonghuiNews)){
List<HashMap> news = Json.fromJsonAsList(HashMap.class, gonghuiNews);
return Result.success(news);
}
SSLContextTrustAnyHostname.trustAllHosts();
String url = "https://gh.hmc.edu.cn/";
Document document = null;
document = Jsoup.connect(url).get();
// 通知公告
Elements notice = document.select("div.center_left");
// 新闻快讯
Elements newsFlash = document.select("td[valign=top][style=padding-left:10px; padding-right:10px;]");
// 服务之窗
Elements windowServer = document.select("div.center_center");
// 通知公告
List<Map<String, Object>> noticeList = notice.stream().map(homeElement -> {
//获取板块名称
String name = homeElement.selectFirst("td.lanmuname").text();
if (name.equals("通知公告")) {
Elements liElements = homeElement.select("table[width=100%][border=0][cellspacing=0][cellpadding=0][style=margin-bottom:10px;]");
List<NutMap> notices = liElements.stream().map(liElement -> {
NutMap row = NutMap.NEW();
String href = liElement.selectFirst("a.list").attr("href");
String time1 = liElement.selectFirst("div.riqinian").text();
String time2 = liElement.selectFirst("div.riqiri").text();
String title = liElement.selectFirst("a.list").text();
row.put("href", href);
row.put("time", time1 + "-" + time2);
row.put("text", title);
return row;
}).collect(Collectors.toList());
return Map.of("label", name, "value", notices);
}
return null;
}).collect(Collectors.toList());
// 新闻快讯
List<Map<String, Object>> newsFlashList = newsFlash.stream().map(homeElement -> {
//获取板块名称
String name = homeElement.selectFirst("td.lanmuname").text();
if (name.equals("新闻快讯")) {
Elements liElements = homeElement.select("td[valign=top][style=padding:10px;15px;10px;0px;]")
.select("table[width=100%][border=0][cellspacing=0][cellpadding=0]");
List<NutMap> notices = liElements.stream().map(liElement -> {
NutMap row = NutMap.NEW();
String href = liElement.selectFirst("a.list").attr("href");
String time = liElement.selectFirst("td.list").text();
String title = liElement.selectFirst("a.list").text();
row.put("href", href);
row.put("time", time);
row.put("text", title);
return row;
}).collect(Collectors.toList());
return Map.of("label", name, "value", notices);
}
return null;
}).collect(Collectors.toList());
// 服务之窗
List<Map<String, Object>> windowServerList = windowServer.stream().map(homeElement -> {
//获取板块名称
String name = homeElement.selectFirst("td.lanmuname").text();
if (name.equals("服务之窗")) {
Elements liElements = homeElement.select("table[width=100%][border=0][cellspacing=0][cellpadding=0][style=margin-bottom:8px;]");
List<NutMap> notices = liElements.stream().map(liElement -> {
NutMap row = NutMap.NEW();
String href = liElement.selectFirst("a.list").attr("href");
String time = liElement.selectFirst("td[height=15][width=40]").text().replaceAll("\\.", "-");
String title = liElement.selectFirst("a.list").text();
row.put("href", href);
row.put("time", time);
row.put("text", title);
return row;
}).collect(Collectors.toList());
return Map.of("label", name, "value", notices);
}
return null;
}).collect(Collectors.toList());
if (Lang.isNotEmpty(newsFlashList)) {
noticeList.addAll(newsFlashList);
}
if (Lang.isNotEmpty(windowServerList)) {
noticeList.addAll(windowServerList);
}
redisService.setex("gonghui_news", 60 * 60 * 24, Json.toJson(noticeList));
return Result.success(noticeList);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
@@ -0,0 +1,93 @@
package io.v.nutz.sys.controllers.platform.sys;
import cn.wizzer.framework.base.Result;
import io.v.nutz.web.commons.utils.ShiroUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.util.Daos;
import org.nutz.dao.util.cri.Static;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import java.util.List;
/**
* 任务待办
*/
@IocBean
@At("/platform/sys/localProcess")
@Slf4j
public class SysLocalProcessController {
@Inject
private Dao dao;
/**
* 查询待办
* @param mode 1待处理 2已处理 3我发起的
* @return
*/
@At
@RequiresAuthentication
@Ok("json:full")
public Result todoList(Integer mode) {
if (mode == 1 || mode == 2) {
Sql sql = Sqls.create("""
SELECT
t.taskNodeName,
t.createdByUserName,
t.formUrl,
t.formUrlView,
t.createdOn,
t2.processName,
t2.nodeName
FROM
sys_local_process_instance_task t
LEFT JOIN sys_local_process_instance t2 ON t2.processUniqueId = t.processUniqueId
$condition
""");
Cnd cnd = Cnd.NEW();
cnd.and(new Static("JSON_CONTAINS( t.assignments, '\"" + ShiroUtil.getPrincipalProperty("loginname") + "\"')"));
cnd.and("t.status", "=", mode);
cnd.and("t.taskDeleteFlag", "=", 0);
cnd.desc("t2.processInitiationTime");
sql.setCondition(cnd);
List<NutMap> list = (List<NutMap>) Daos.query(dao, sql.toString(), Sqls.callback.maps());
return Result.success(list);
} else if (mode == 3) {
Sql sql = Sqls.create("""
SELECT
t.id,
t.processUniqueId,
t.processName,
t.nodeName,
t.pcUrl,
t.mobileUrl,
t.pcUrl as formUrl,
t.processInstanceStatus,
t.processInitiationTime as createdOn,
u.username as createdByUserName
FROM
sys_local_process_instance t
LEFT JOIN sys_user u ON u.id = t.processInitiatorId
WHERE
t.processInitiatorId = @id
AND t.processDeleteFlag = 0
AND t.delFlag = 0
ORDER BY t.processInitiationTime DESC
""");
sql.setParam("id", ShiroUtil.getUserId());
List<NutMap> list = (List<NutMap>) Daos.query(dao, sql.toString(), Sqls.callback.maps());
return Result.success(list);
}
return null;
}
}

Some files were not shown because too many files have changed in this diff Show More