diff --git a/README.md b/README.md index d8e1df5..0056059 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,6 @@ # open-JSD-9503 -JSD-9503 用户权限同步 \ No newline at end of file +JSD-9503 用户权限同步\ +免责说明:该源码为第三方爱好者提供,不保证源码和方案的可靠性,也不提供任何形式的源码教学指导和协助!\ +仅作为开发者学习参考使用!禁止用于任何商业用途!\ +为保护开发者隐私,开发者信息已隐去!若原开发者希望公开自己的信息,可联系hugh处理。 \ No newline at end of file diff --git a/doc/JSD-9503配置使用文档.docx b/doc/JSD-9503配置使用文档.docx new file mode 100644 index 0000000..b24ec14 Binary files /dev/null and b/doc/JSD-9503配置使用文档.docx differ diff --git a/plugin.xml b/plugin.xml new file mode 100644 index 0000000..a66eee2 --- /dev/null +++ b/plugin.xml @@ -0,0 +1,23 @@ + + com.fr.plugin.xxxx.bi.sync + com.fr.plugin.xxxx.bi.sync + + yes + 1.3 + 10.0 + 2018-07-31 + fr.open + + + [2021-03-22]【1.1】修改sql。
+ [2021-03-22]【1.2】修改url格式。
+ [2021-03-23]【1.3】update修改、增加授权、日志区分、定时器重置、配置抽取。
+ ]]>
+ + + + + + +
\ No newline at end of file diff --git a/src/main/java/com/fr/plugin/xxxx/bi/sync/Constants.java b/src/main/java/com/fr/plugin/xxxx/bi/sync/Constants.java new file mode 100644 index 0000000..6265e3c --- /dev/null +++ b/src/main/java/com/fr/plugin/xxxx/bi/sync/Constants.java @@ -0,0 +1,12 @@ +package com.fr.plugin.xxxx.bi.sync; + +/** + * @author fr.open + * @date 2020/5/14 + */ +public class Constants { + public static final String PLUGIN_ID = "com.fr.plugin.xxxx.bi.sync"; + + public static final String PLUGIN_NAME= "bi用户权限同步"; + +} diff --git a/src/main/java/com/fr/plugin/xxxx/bi/sync/LRGT.java b/src/main/java/com/fr/plugin/xxxx/bi/sync/LRGT.java new file mode 100644 index 0000000..02818fa --- /dev/null +++ b/src/main/java/com/fr/plugin/xxxx/bi/sync/LRGT.java @@ -0,0 +1,27 @@ +package com.fr.plugin.xxxx.bi.sync; + +import com.fr.plugin.context.PluginContext; +import com.fr.plugin.xxxx.bi.sync.config.SyncConfig; +import com.fr.plugin.observer.inner.AbstractPluginLifecycleMonitor; + +/** + * @author fr.open + * @since 2022/01/13 + */ +public class LRGT extends AbstractPluginLifecycleMonitor { + @Override + public void afterRun(PluginContext pluginContext) { + SyncConfig.getInstance(); + } + + @Override + public void beforeStop(PluginContext pluginContext) { + } + @Override + public void beforeUninstall(PluginContext pluginContext) { + } + + @Override + public void afterInstall(PluginContext var1) { + } +} \ No newline at end of file diff --git a/src/main/java/com/fr/plugin/xxxx/bi/sync/LogUtils.java b/src/main/java/com/fr/plugin/xxxx/bi/sync/LogUtils.java new file mode 100644 index 0000000..5dd5202 --- /dev/null +++ b/src/main/java/com/fr/plugin/xxxx/bi/sync/LogUtils.java @@ -0,0 +1,121 @@ +package com.fr.plugin.xxxx.bi.sync; + +import com.fr.log.FineLoggerFactory; +import com.fr.log.FineLoggerProvider; +import com.fr.plugin.context.PluginContexts; +import com.fr.plugin.xxxx.bi.sync.config.SyncConfig; +import com.fr.stable.StringUtils; + +/** + * @author fr.open + * @since 2021/12/04 + */ +public final class LogUtils { + private static final String DEBUG_PREFIX = "[插件调试] "; + private static String LOG_PREFIX = Constants.PLUGIN_NAME; + private static final String PLUGIN_VERSION; + + private static final FineLoggerProvider LOGGER = FineLoggerFactory.getLogger(); + + static { + String version = PluginContexts.currentContext().getMarker().getVersion(); + if (StringUtils.isNotBlank(version)) { + PLUGIN_VERSION = "[v" + version + "] "; + } else { + PLUGIN_VERSION = "[unknown version] "; + } + + LOG_PREFIX = LOG_PREFIX + PLUGIN_VERSION; + } + + public static void setPrefix(String prefix) { + if (prefix != null) { + LOG_PREFIX = prefix; + } + } + + public static boolean isDebugEnabled() { + return LOGGER.isDebugEnabled(); + } + + public static void debug(String s) { + LOGGER.debug(LOG_PREFIX + s); + } + + public static void debug(String s, Object... objects) { + LOGGER.debug(LOG_PREFIX + s, objects); + } + + public static void debug(String s, Throwable throwable) { + LOGGER.debug(LOG_PREFIX + s, throwable); + } + + public static void debug4plugin(String s) { + if (SyncConfig.getInstance().getDebugSwitch()) { + LOGGER.error(DEBUG_PREFIX + LOG_PREFIX + s); + } else { + LOGGER.debug(LOG_PREFIX + s); + } + } + + public static void debug4plugin(String s, Object... objects) { + if (SyncConfig.getInstance().getDebugSwitch()) { + LOGGER.error(DEBUG_PREFIX + LOG_PREFIX + s, objects); + } else { + LOGGER.debug(LOG_PREFIX + s, objects); + } + } + + public static void debug4plugin(String s, Throwable throwable) { + if (SyncConfig.getInstance().getDebugSwitch()) { + LOGGER.error(DEBUG_PREFIX + LOG_PREFIX + s, throwable); + } else { + LOGGER.debug(LOG_PREFIX + s, throwable); + } + } + + + public static boolean isInfoEnabled() { + return LOGGER.isInfoEnabled(); + } + + public static void info(String s) { + LOGGER.info(LOG_PREFIX + s); + } + + public static void info(String s, Object... objects) { + LOGGER.info(LOG_PREFIX + s, objects); + } + + public static void warn(String s) { + LOGGER.warn(LOG_PREFIX + s); + } + + public static void warn(String s, Object... objects) { + LOGGER.warn(LOG_PREFIX + s, objects); + } + + public static void warn(String s, Throwable throwable) { + LOGGER.warn(LOG_PREFIX + s, throwable); + } + + public static void warn(Throwable throwable, String s, Object... objects) { + LOGGER.warn(throwable, LOG_PREFIX + s, objects); + } + + public static void error(String s) { + LOGGER.error(LOG_PREFIX + s); + } + + public static void error(String s, Object... objects) { + LOGGER.error(LOG_PREFIX + s, objects); + } + + public static void error(String s, Throwable throwable) { + LOGGER.error(LOG_PREFIX + s, throwable); + } + + public static void error(Throwable throwable, String s, Object... objects) { + LOGGER.error(throwable, LOG_PREFIX + s, objects); + } +} diff --git a/src/main/java/com/fr/plugin/xxxx/bi/sync/SyncFilter.java b/src/main/java/com/fr/plugin/xxxx/bi/sync/SyncFilter.java new file mode 100644 index 0000000..c943e6d --- /dev/null +++ b/src/main/java/com/fr/plugin/xxxx/bi/sync/SyncFilter.java @@ -0,0 +1,95 @@ +package com.fr.plugin.xxxx.bi.sync; + +import com.fr.decision.fun.impl.AbstractGlobalRequestFilterProvider; +import com.fr.json.JSONObject; +import com.fr.log.FineLoggerFactory; +import com.fr.plugin.context.PluginContexts; +import com.fr.plugin.xxxx.bi.sync.config.SyncConfig; +import com.fr.plugin.xxxx.bi.sync.schedule.SyncThread; +import com.fr.plugin.transform.FunctionRecorder; +import com.fr.scheduler.QuartzContext; +import com.fr.scheduler.ScheduleJobManager; +import com.fr.stable.StringUtils; +import com.fr.stable.fun.Authorize; +import com.fr.third.v2.org.quartz.CronScheduleBuilder; +import com.fr.third.v2.org.quartz.JobKey; +import com.fr.third.v2.org.quartz.SchedulerException; +import com.fr.third.v2.org.quartz.TriggerBuilder; +import com.fr.web.utils.WebUtils; + +import javax.servlet.FilterChain; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.HashMap; +import java.util.Map; + +/** + * @Author fr.open + * @Date 2020/9/10 + * @Description + **/ +@FunctionRecorder +@Authorize(groupSignKey = Constants.PLUGIN_ID) +public class SyncFilter extends AbstractGlobalRequestFilterProvider { + + @Override + public String filterName() { + return "bi-sync"; + } + + @Override + public String[] urlPatterns() { + initSchedule(); + return new String[]{"/decision/bi-sync/reset"}; + } + + @Override + public void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain filterChain) { + SyncConfig config = SyncConfig.getInstance(); + try { + if (!config.configed()) { + WebUtils.printAsJSON(res, JSONObject.create().put("mess", "config is not configed").put("state", 0)); + return; + } + initSchedule(); + WebUtils.printAsJSON(res, JSONObject.create().put("mess", "reset successful").put("state", 1)); + } catch (Exception e) { + LogUtils.error(e.getMessage(), e); + } + } + + + public static void initSchedule() { + JobKey jobKey = new JobKey("syncBIRole", "syncGroup"); + try { + if (QuartzContext.getInstance().getScheduler().checkExists(jobKey)) { + ScheduleJobManager.getInstance().removeJob(jobKey.getName(), jobKey.getGroup()); + } + } catch (SchedulerException e) { + FineLoggerFactory.getLogger().error(e.getMessage(), e); + } + if (PluginContexts.currentContext().isAvailable()) { + addSchedule(jobKey); + } else { + LogUtils.error("插件已经被禁用或过期"); + } + } + + private static void addSchedule(JobKey jobKey) { + Map param = new HashMap(); + SyncConfig config = SyncConfig.getInstance(); + TriggerBuilder triggerBuilder = TriggerBuilder.newTrigger(); + triggerBuilder.forJob(jobKey.getName(), jobKey.getGroup()).withIdentity(jobKey.getName(), jobKey.getGroup()).startNow(); + if (StringUtils.isBlank(config.getCron())) { + LogUtils.error("cron is null schedule start failed"); + return; + } + CronScheduleBuilder schedule = CronScheduleBuilder.cronSchedule(config.getCron()); + triggerBuilder.withSchedule(schedule); + try { + ScheduleJobManager.getInstance().addJob(jobKey.getName(), jobKey.getGroup(), "sync job", SyncThread.class, triggerBuilder.build(), param); + } catch (Exception e) { + LogUtils.error(e.getMessage(), e); + } + } +} diff --git a/src/main/java/com/fr/plugin/xxxx/bi/sync/config/SyncConfig.java b/src/main/java/com/fr/plugin/xxxx/bi/sync/config/SyncConfig.java new file mode 100644 index 0000000..2947c5f --- /dev/null +++ b/src/main/java/com/fr/plugin/xxxx/bi/sync/config/SyncConfig.java @@ -0,0 +1,73 @@ +package com.fr.plugin.xxxx.bi.sync.config; + +import com.fr.config.*; +import com.fr.config.holder.Conf; +import com.fr.config.holder.factory.Holders; +import com.fr.record.analyzer.EnableMetrics; +import com.fr.stable.StringUtils; + +/** + * @Author fr.open + * @Date 2022/3/23 + * @Description + **/ +@Visualization(category = "同步配置") +@EnableMetrics +public class SyncConfig extends DefaultConfiguration { + + private static volatile SyncConfig config = null; + + public static SyncConfig getInstance() { + if (config == null) { + config = ConfigContext.getConfigInstance(SyncConfig.class); + } + return config; + } + + @Identifier(value = "debugSwitch", name = "插件调试开关", description = "日志调试模式", status = Status.SHOW) + private Conf debugSwitch = Holders.simple(true); + + @Identifier(value = "connection", name = "数据连接", description = "同步数据库连接", status = Status.SHOW) + private Conf connection = Holders.simple(StringUtils.EMPTY); + + @Identifier(value = "cron", name = "定时器", description = "定时器", status = Status.SHOW) + private Conf cron = Holders.simple("0 0 0/1 * * ? *"); + + public Boolean getDebugSwitch() { + return this.debugSwitch.get(); + } + + public void setDebugSwitch(Boolean debugSwitch) { + this.debugSwitch.set(debugSwitch); + } + + public String getConnection() { + return connection.get(); + } + + public void setConnection(String connection) { + this.connection.set(connection); + } + + public String getCron() { + return cron.get(); + } + + public void setCron(String cron) { + this.cron.set(cron); + } + + @Override + public Object clone() throws CloneNotSupportedException { + SyncConfig cloned = (SyncConfig) super.clone(); + cloned.debugSwitch = (Conf) debugSwitch.clone(); + cloned.connection = (Conf) connection.clone(); + cloned.cron = (Conf) cron.clone(); + return cloned; + } + + + public boolean configed() { + return StringUtils.isNotBlank(getConnection()) && StringUtils.isNotBlank(getCron()); + } +} diff --git a/src/main/java/com/fr/plugin/xxxx/bi/sync/dao/RoleUrlDao.java b/src/main/java/com/fr/plugin/xxxx/bi/sync/dao/RoleUrlDao.java new file mode 100644 index 0000000..e6a54c3 --- /dev/null +++ b/src/main/java/com/fr/plugin/xxxx/bi/sync/dao/RoleUrlDao.java @@ -0,0 +1,21 @@ +package com.fr.plugin.xxxx.bi.sync.dao; + +import com.fr.plugin.xxxx.bi.sync.entity.RoleUrlEntity; +import com.fr.stable.db.dao.BaseDAO; +import com.fr.stable.db.session.DAOSession; + +/** + * @Author fr.open + * @Date 2021/5/13 + * @Description + **/ +public class RoleUrlDao extends BaseDAO { + public RoleUrlDao(DAOSession daoSession) { + super(daoSession); + } + + @Override + protected Class getEntityClass() { + return RoleUrlEntity.class; + } +} diff --git a/src/main/java/com/fr/plugin/xxxx/bi/sync/dao/UserRoleDao.java b/src/main/java/com/fr/plugin/xxxx/bi/sync/dao/UserRoleDao.java new file mode 100644 index 0000000..2eebe7d --- /dev/null +++ b/src/main/java/com/fr/plugin/xxxx/bi/sync/dao/UserRoleDao.java @@ -0,0 +1,21 @@ +package com.fr.plugin.xxxx.bi.sync.dao; + +import com.fr.plugin.xxxx.bi.sync.entity.UserRoleEntity; +import com.fr.stable.db.dao.BaseDAO; +import com.fr.stable.db.session.DAOSession; + +/** + * @Author fr.open + * @Date 2021/5/13 + * @Description + **/ +public class UserRoleDao extends BaseDAO { + public UserRoleDao(DAOSession daoSession) { + super(daoSession); + } + + @Override + protected Class getEntityClass() { + return UserRoleEntity.class; + } +} diff --git a/src/main/java/com/fr/plugin/xxxx/bi/sync/entity/RoleUrlEntity.java b/src/main/java/com/fr/plugin/xxxx/bi/sync/entity/RoleUrlEntity.java new file mode 100644 index 0000000..08ee584 --- /dev/null +++ b/src/main/java/com/fr/plugin/xxxx/bi/sync/entity/RoleUrlEntity.java @@ -0,0 +1,63 @@ +package com.fr.plugin.xxxx.bi.sync.entity; + +import com.fr.stable.db.entity.BaseEntity; +import com.fr.third.javax.persistence.Column; +import com.fr.third.javax.persistence.Entity; +import com.fr.third.javax.persistence.Table; + +/** + * @Author fr.open + * @Date 2021/5/13 + * @Description + **/ +@Entity +@Table(name = "fine_role_url_bi") +public class RoleUrlEntity extends BaseEntity { + + private static final long serialVersionUID = -6715601520739733691L; + + @Column(name = "url", length = 200) + private String url; + @Column(name = "roleId", length = 200) + private String roleId; + @Column(name = "roleName_EN", length = 200) + private String roleName_EN; + @Column(name = "roleName_CN", length = 200) + private String roleName_CN; + + public String getUrl() { + return this.url; + } + + public String getEntityId(){ + return this.url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getRoleId() { + return roleId; + } + + public void setRoleId(String roleId) { + this.roleId = roleId; + } + + public String getRoleName_EN() { + return roleName_EN; + } + + public void setRoleName_EN(String roleName_EN) { + this.roleName_EN = roleName_EN; + } + + public String getRoleName_CN() { + return roleName_CN; + } + + public void setRoleName_CN(String roleName_CN) { + this.roleName_CN = roleName_CN; + } +} diff --git a/src/main/java/com/fr/plugin/xxxx/bi/sync/entity/UserRoleEntity.java b/src/main/java/com/fr/plugin/xxxx/bi/sync/entity/UserRoleEntity.java new file mode 100644 index 0000000..4c3db1d --- /dev/null +++ b/src/main/java/com/fr/plugin/xxxx/bi/sync/entity/UserRoleEntity.java @@ -0,0 +1,69 @@ +package com.fr.plugin.xxxx.bi.sync.entity; + +import com.fr.stable.db.entity.BaseEntity; +import com.fr.third.javax.persistence.Column; +import com.fr.third.javax.persistence.Entity; +import com.fr.third.javax.persistence.Table; + +/** + * @Author fr.open + * @Date 2021/5/13 + * @Description + **/ +@Entity +@Table(name = "fine_role_user_bi") +public class UserRoleEntity extends BaseEntity { + + private static final long serialVersionUID = 3637766371586218549L; + + @Column(name = "userAccount", length = 50) + private String userAccount; + @Column(name = "userName", length = 50) + private String userName; + @Column(name = "roleId", length = 50) + private String roleId; + @Column(name = "roleName_EN", length = 200) + private String roleName_EN; + @Column(name = "roleName_CN", length = 200) + private String roleName_CN; + + public String getUserAccount() { + return userAccount; + } + + public void setUserAccount(String userAccount) { + this.userAccount = userAccount; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getRoleId() { + return roleId; + } + + public void setRoleId(String roleId) { + this.roleId = roleId; + } + + public String getRoleName_EN() { + return roleName_EN; + } + + public void setRoleName_EN(String roleName_EN) { + this.roleName_EN = roleName_EN; + } + + public String getRoleName_CN() { + return roleName_CN; + } + + public void setRoleName_CN(String roleName_CN) { + this.roleName_CN = roleName_CN; + } +} diff --git a/src/main/java/com/fr/plugin/xxxx/bi/sync/schedule/SyncThread.java b/src/main/java/com/fr/plugin/xxxx/bi/sync/schedule/SyncThread.java new file mode 100644 index 0000000..c8be00d --- /dev/null +++ b/src/main/java/com/fr/plugin/xxxx/bi/sync/schedule/SyncThread.java @@ -0,0 +1,237 @@ +package com.fr.plugin.xxxx.bi.sync.schedule; + +import com.fr.cluster.core.ClusterNode; +import com.fr.data.impl.Connection; +import com.fr.data.impl.DBTableData; +import com.fr.data.impl.MemCachedDBDataModel; +import com.fr.data.impl.NameDatabaseConnection; +import com.fr.decision.authority.AuthorityContext; +import com.fr.decision.authority.data.CustomRole; +import com.fr.decision.authority.data.User; +import com.fr.decision.webservice.bean.authority.PrivilegeBean; +import com.fr.decision.webservice.v10.authority.AuthorityService; +import com.fr.decision.webservice.v10.user.UserService; +import com.fr.file.DatasourceManager; +import com.fr.file.DatasourceManagerProvider; +import com.fr.general.PropertiesUtils; +import com.fr.json.JSONObject; +import com.fr.plugin.xxxx.bi.sync.LogUtils; +import com.fr.plugin.xxxx.bi.sync.config.SyncConfig; +import com.fr.plugin.xxxx.bi.sync.entity.RoleUrlEntity; +import com.fr.scheduler.job.FineScheduleJob; +import com.fr.stable.StringUtils; +import com.fr.stable.query.QueryFactory; +import com.fr.stable.query.restriction.RestrictionFactory; +import com.fr.third.guava.collect.Sets; +import com.fr.third.v2.org.quartz.JobExecutionContext; + +import java.io.UnsupportedEncodingException; +import java.lang.reflect.Method; +import java.net.URLDecoder; +import java.sql.Statement; +import java.util.*; +import java.util.stream.Collectors; + +/** + * @Author fr.open + * @Date 2021/5/31 + * @Description + **/ +public class SyncThread extends FineScheduleJob { + private static final String carrierType = "role"; + + private static final String externalType = "bitemp"; + + private static final JSONObject bean = new JSONObject("{\"id\":\"reportlets\",\"values\":[{\"privilegeType\":206,\"privilegeValue\":1},{\"privilegeType\":207,\"privilegeValue\":1}]}"); + + private static final JSONObject tempBean = new JSONObject("{\"id\":\"\",\"values\":[{\"privilegeType\":206,\"privilegeValue\":2},{\"privilegeType\":207,\"privilegeValue\":2}]}"); + + private static final JSONObject addTempBean = new JSONObject("{\"id\":\"\",\"values\":[{\"privilegeType\":205,\"privilegeValue\":2}]}"); + + @Override + public void run(JobExecutionContext jobExecutionContext, ClusterNode clusterNode) throws Exception { + SyncConfig config = SyncConfig.getInstance(); + List admins = UserService.getInstance().getAdminUserIdList(); + if (admins == null || admins.isEmpty()) { + LogUtils.error("super user is null!"); + return; + } + if (!config.configed()) { + LogUtils.error("config not configed!"); + } + String userId = admins.get(0); + Map roles = getRoles(); + Map> delete = getRoleList(-1); + LogUtils.debug4plugin("start sync delete auth"); + Iterator iterator = delete.keySet().iterator(); + List updateIds = new ArrayList<>(); + while (iterator.hasNext()) { + String key = iterator.next(); + List list = delete.get(key); + if (StringUtils.isBlank(roles.get(key)) || delete.get(key) == null || delete.get(key).isEmpty()) { + continue; + } + //先删除权限 + for (RoleUrlEntity temp : list) { + try { + String entityId = temp.getEntityId(); + PrivilegeBean privilegeBean = bean.mapTo(PrivilegeBean.class); + privilegeBean.setId(entityId); + LogUtils.debug4plugin("remove temp:{} by role", temp.getUrl(), temp); + PrivilegeBean addTempPrivilegeBean = addTempBean.mapTo(PrivilegeBean.class); + addTempPrivilegeBean.setId(entityId); + LogUtils.debug4plugin("add temp {} to auth with {}",entityId,addTempBean); + setAddTemp(userId, "super-user-custom-role", addTempPrivilegeBean); + LogUtils.debug4plugin("auth temp {} to role {} auth with {}",entityId,roles.get(key),bean); + auth(userId, roles.get(key), privilegeBean); + } catch (Exception e) { + LogUtils.error(e.getMessage(), e); + } + } + updateIds.addAll(list); + } + updateStatus(updateIds.stream().map(e -> e.getId()).collect(Collectors.toList())); + LogUtils.debug4plugin("sync finish delete size is {}", updateIds.size()); + LogUtils.debug4plugin("start sync add auth"); + Map> add = getRoleList(0); + Iterator it = add.keySet().iterator(); + List addIds = new ArrayList(); + while (it.hasNext()) { + String key = it.next(); + List list = add.get(key); + if (StringUtils.isBlank(roles.get(key)) || add.get(key) == null || add.get(key).isEmpty()) { + continue; + } + //先添加权限 + for (RoleUrlEntity temp : list) { + try { + String entityId = temp.getEntityId(); + PrivilegeBean addTempPrivilegeBean = addTempBean.mapTo(PrivilegeBean.class); + addTempPrivilegeBean.setId(entityId); + LogUtils.debug4plugin("add temp {} to auth with {}",entityId,addTempBean); + setAddTemp(userId, "super-user-custom-role", addTempPrivilegeBean); + PrivilegeBean privilegeBean = tempBean.mapTo(PrivilegeBean.class); + privilegeBean.setId(entityId); + LogUtils.debug4plugin("auth temp {} to role {} auth with {}",entityId,roles.get(key),tempBean); + auth(userId, roles.get(key), privilegeBean); + LogUtils.debug4plugin("add temp:{} to role", temp.getUrl(), temp); + } catch (Exception e) { + LogUtils.error(e.getMessage(), e); + } + } + addIds.addAll(list); + } + updateStatus(addIds.stream().map(e -> e.getId()).collect(Collectors.toList())); + LogUtils.debug4plugin("sync finish add size is {}", addIds.size()); + /*Map roles = getRoles(); + //removeAuth(new ArrayList(roles.values())); + Map> roleList = getRoleList(); + addAuth(roleList, roles);*/ + } + + public void test() { + try { + CustomRole customRoles = AuthorityContext.getInstance().getCustomRoleController().findOne(QueryFactory.create().addRestriction(RestrictionFactory.eq("name", "test1"))); + User user = UserService.getInstance().getUserByUserName("1"); + PrivilegeBean privilegeBean = tempBean.mapTo(PrivilegeBean.class); + privilegeBean.setId("reportlets"); + auth(user.getId(), customRoles.getId(), privilegeBean); + } catch (Exception e) { + e.printStackTrace(); + } + } + + private Map> getRoleList(Integer status) throws Exception { + String sql = "select roleName_CN,id,url_bi from fine_role_url_bi where status = " + status; + LogUtils.debug4plugin("query sql is [{}]", sql); + String connection = SyncConfig.getInstance().getConnection(); + LogUtils.debug4plugin("query connection is {}", connection); + MemCachedDBDataModel dbDataModel = (MemCachedDBDataModel) DBTableData + .createCacheableDBResultSet(new NameDatabaseConnection(connection), sql, -1); + int rowCount = dbDataModel.getRowCount(); + Map> map = new HashMap(); + for (int i = 0; i < rowCount; i++) { + List roles = map.get(dbDataModel.getValueAt(i, 0).toString()); + if (roles == null) { + roles = new ArrayList<>(); + } + RoleUrlEntity entity = new RoleUrlEntity(); + entity.setId(dbDataModel.getValueAt(i, 1).toString()); + entity.setUrl(dbDataModel.getValueAt(i, 2).toString()); + roles.add(entity); + map.put(dbDataModel.getValueAt(i, 0).toString(), roles); + } + return map; + } + + private void updateStatus(List id) { + if (id == null || id.isEmpty()) { + return; + } + java.sql.Connection jdbc = null; + Statement st = null; + try { + String sql = "update fine_role_url_bi set status = '1' where id in ('" + id.stream().collect(Collectors.joining("','")) + "')"; + DatasourceManagerProvider datasourceManagerProvider = DatasourceManager.getProviderInstance(); + Connection connection = datasourceManagerProvider.getConnection(PropertiesUtils.getProperties("conf").getProperty("connection")); + jdbc = connection.createConnection(); + jdbc.nativeSQL(sql); + st = jdbc.createStatement(); + st.execute(sql); + LogUtils.debug4plugin("update sql is [{}]", sql); + } catch (Exception e) { + LogUtils.error(e.getMessage(), e); + } finally { + try { + if (st != null) { + st.close(); + } + if (jdbc != null) { + jdbc.close(); + } + } catch (Exception e) { + LogUtils.error(e.getMessage(), e); + } + + } + } + + private String getViewlet(String temp) throws UnsupportedEncodingException { + String params = temp.substring(temp.indexOf("?") + 1); + for (int i = 0; i < params.split("&").length; i++) { + String param = params.split("&")[i]; + if (param.split("=")[0].equals("viewlet")) { + return URLDecoder.decode(URLDecoder.decode(param.split("=")[1], "UTF-8"), "UTF-8"); + } + } + return StringUtils.EMPTY; + } + + + private void auth(String user, String role, PrivilegeBean privilegeBean) throws Exception { + AuthorityService.getInstance().checkUserAssignAuthority(user, Sets.newHashSet(new String[]{privilegeBean.getId()}), privilegeBean.getAuthorityTypes(), externalType); + //Reflect.on("com.fr.decision.webservice.v10.authority.AuthorityService").call("updateAuthorityEntityByCarrier",user.getId(), carrierType, role, privilegeBean, externalType); + Class clazz = Class.forName("com.fr.decision.webservice.v10.authority.AuthorityService"); + Method method = clazz.getDeclaredMethod("updateAuthorityEntityByCarrier", String.class, String.class, String.class, PrivilegeBean.class, String.class); + method.invoke(AuthorityService.getInstance(), user, carrierType, role, privilegeBean, externalType); + //AuthorityService.getInstance().updateAuthorityEntityByCarrier(user.getId(), carrierType, role, privilegeBean, externalType); + } + + private void setAddTemp(String user, String role, PrivilegeBean privilegeBean) throws Exception { + AuthorityService.getInstance().checkUserAssignAuthority(user, Sets.newHashSet(new String[]{privilegeBean.getId()}), privilegeBean.getAuthorityTypes(), externalType); + //Reflect.on("com.fr.decision.webservice.v10.authority.AuthorityService").call("updateAuthorityEntityByCarrier",user.getId(), carrierType, role, privilegeBean, externalType); + Class clazz = Class.forName("com.fr.decision.webservice.v10.authority.AuthorityService"); + Method method = clazz.getDeclaredMethod("updateAuthorityEntityByCarrier", String.class, String.class, String.class, PrivilegeBean.class, String.class); + method.invoke(AuthorityService.getInstance(), user, carrierType, role, privilegeBean, externalType); + //AuthorityService.getInstance().updateAuthorityEntityByCarrier(user.getId(), carrierType, role, privilegeBean, externalType); + } + + private Map getRoles() throws Exception { + List customRoles = AuthorityContext.getInstance().getCustomRoleController().find(QueryFactory.create()); + if (customRoles == null || customRoles.isEmpty()) { + return new HashMap<>(); + } + return customRoles.stream().collect(Collectors.toMap(CustomRole::getName, CustomRole::getId, (k1, k2) -> k2)); + } + +} diff --git a/src/main/resources/conf.properties b/src/main/resources/conf.properties new file mode 100644 index 0000000..86ee747 --- /dev/null +++ b/src/main/resources/conf.properties @@ -0,0 +1,4 @@ +##\u6570\u636E\u8FDE\u63A5 +connection= +##cron +cron=0 0/5 * * * ? * \ No newline at end of file