21 changed files with 1477 additions and 2 deletions
Binary file not shown.
Binary file not shown.
@ -1,3 +1,6 @@
|
||||
# open-JSD-8170 |
||||
# open-JSD-8170 用户同步 |
||||
|
||||
JSD-8170 开源任务材料 |
||||
JSD-8170 开源任务材料\ |
||||
免责说明:该源码为第三方爱好者提供,不保证源码和方案的可靠性,也不提供任何形式的源码教学指导和协助!\ |
||||
仅作为开发者学习参考使用!禁止用于任何商业用途!\ |
||||
为保护开发者隐私,开发者信息已隐去!若原开发者希望公开自己的信息,可联系hugh处理。 |
@ -0,0 +1,21 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?> |
||||
<plugin> |
||||
<id>com.fr.plugin.wechat.sync</id> |
||||
<name><![CDATA[企业微信同步角色]]></name> |
||||
<active>yes</active> |
||||
<version>1.2</version> |
||||
<env-version>10.0</env-version> |
||||
<jartime>2018-07-31</jartime> |
||||
<vendor>fr.open</vendor> |
||||
<description><![CDATA[企业微信同步角色]]></description> |
||||
<change-notes><![CDATA[ |
||||
|
||||
]]></change-notes> |
||||
<extra-core> |
||||
<DBAccessProvider class="com.fr.plugin.wechat.sync.SyncDBAccessProvider"/> |
||||
</extra-core> |
||||
<extra-decision> |
||||
<GlobalRequestFilterProvider class="com.fr.plugin.wechat.sync.SyncFilter"/> |
||||
</extra-decision> |
||||
<function-recorder class="com.fr.plugin.wechat.sync.SyncFilter"/> |
||||
</plugin> |
@ -0,0 +1,310 @@
|
||||
package com.fr.plugin.wechat.sync; |
||||
|
||||
import com.fr.json.JSONObject; |
||||
import com.fr.log.FineLoggerFactory; |
||||
import com.fr.third.org.apache.http.HttpResponse; |
||||
import com.fr.third.org.apache.http.HttpStatus; |
||||
import com.fr.third.org.apache.http.client.HttpClient; |
||||
import com.fr.third.org.apache.http.client.methods.HttpPost; |
||||
import com.fr.third.org.apache.http.config.Registry; |
||||
import com.fr.third.org.apache.http.config.RegistryBuilder; |
||||
import com.fr.third.org.apache.http.conn.socket.ConnectionSocketFactory; |
||||
import com.fr.third.org.apache.http.conn.socket.PlainConnectionSocketFactory; |
||||
import com.fr.third.org.apache.http.conn.ssl.SSLConnectionSocketFactory; |
||||
import com.fr.third.org.apache.http.entity.StringEntity; |
||||
import com.fr.third.org.apache.http.impl.client.HttpClients; |
||||
import com.fr.third.org.apache.http.impl.conn.PoolingHttpClientConnectionManager; |
||||
import com.fr.third.org.apache.http.util.EntityUtils; |
||||
|
||||
import javax.net.ssl.*; |
||||
import java.io.*; |
||||
import java.net.HttpURLConnection; |
||||
import java.net.URL; |
||||
import java.net.URLEncoder; |
||||
import java.security.cert.CertificateException; |
||||
import java.util.Iterator; |
||||
import java.util.Map; |
||||
import java.util.stream.Collectors; |
||||
|
||||
/** |
||||
* @author fr.open |
||||
* @date 2021/7/29 |
||||
*/ |
||||
public class HttpUtil { |
||||
|
||||
private static HostnameVerifier hv = new HostnameVerifier() { |
||||
@Override |
||||
public boolean verify(String urlHostName, SSLSession session) { |
||||
System.out.println("Warning: URL Host: " + urlHostName + " vs. " |
||||
+ session.getPeerHost()); |
||||
return true; |
||||
} |
||||
}; |
||||
|
||||
/** |
||||
* 发送get请求 |
||||
* |
||||
* @param url |
||||
* @param param |
||||
* @param header |
||||
* @return |
||||
* @throws IOException |
||||
*/ |
||||
public static String sendGet(String url, Map<String, String> param, Map<String, String> header) { |
||||
String result = ""; |
||||
BufferedReader in = null; |
||||
String urlNameString = url; |
||||
try { |
||||
if (param != null) { |
||||
urlNameString += "?"; |
||||
urlNameString += param.entrySet() |
||||
.stream() |
||||
.map(entry -> entry.getKey() + "=" + entry.getValue()) |
||||
.collect(Collectors.joining("&")); |
||||
} |
||||
|
||||
URL realUrl = new URL(urlNameString); |
||||
// 打开和URL之间的连接
|
||||
HttpURLConnection connection; |
||||
if (url.startsWith("https")) { |
||||
trustAllHttpsCertificates(); |
||||
HttpsURLConnection.setDefaultHostnameVerifier(hv); |
||||
connection = (HttpURLConnection) realUrl.openConnection(); |
||||
} else { |
||||
connection = (HttpURLConnection) realUrl.openConnection(); |
||||
} |
||||
//设置超时时间
|
||||
connection.setDoInput(true); |
||||
connection.setRequestMethod("GET"); |
||||
connection.setConnectTimeout(5000); |
||||
connection.setReadTimeout(15000); |
||||
// 设置通用的请求属性
|
||||
if (header != null) { |
||||
Iterator<Map.Entry<String, String>> it = header.entrySet().iterator(); |
||||
while (it.hasNext()) { |
||||
Map.Entry<String, String> entry = it.next(); |
||||
System.out.println(entry.getKey() + ":::" + entry.getValue()); |
||||
connection.setRequestProperty(entry.getKey(), entry.getValue()); |
||||
} |
||||
} |
||||
connection.setRequestProperty("accept", "*/*"); |
||||
connection.setRequestProperty("connection", "Keep-Alive"); |
||||
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); |
||||
// 建立实际的连接
|
||||
connection.connect(); |
||||
// 定义 BufferedReader输入流来读取URL的响应,设置utf8防止中文乱码
|
||||
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8")); |
||||
String line; |
||||
while ((line = in.readLine()) != null) { |
||||
result += line; |
||||
} |
||||
if (in != null) { |
||||
in.close(); |
||||
} |
||||
} catch (Exception e) { |
||||
FineLoggerFactory.getLogger().error(e, "get url error ,url is:{},error is {}", urlNameString, e.getMessage()); |
||||
} |
||||
return result; |
||||
} |
||||
|
||||
public static String sendPost(String url, Map<String, Object> header, JSONObject body) { |
||||
PrintWriter out = null; |
||||
BufferedReader in = null; |
||||
String result = null; |
||||
String res = null; |
||||
try { |
||||
String urlNameString = url; |
||||
|
||||
URL realUrl = new URL(urlNameString); |
||||
// 打开和URL之间的连接
|
||||
HttpURLConnection conn; |
||||
if (url.startsWith("https")) { |
||||
trustAllHttpsCertificates(); |
||||
HttpsURLConnection.setDefaultHostnameVerifier(hv); |
||||
conn = (HttpURLConnection) realUrl.openConnection(); |
||||
} else { |
||||
conn = (HttpURLConnection) realUrl.openConnection(); |
||||
} |
||||
// 设置通用的请求属性
|
||||
conn.setRequestProperty("accept", "*/*"); |
||||
conn.setRequestProperty("connection", "Keep-Alive"); |
||||
// conn.setRequestProperty("user-agent",
|
||||
// "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
|
||||
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); |
||||
if (header != null) { |
||||
header.forEach((k, v) -> { |
||||
conn.setRequestProperty(k, String.valueOf(v)); |
||||
}); |
||||
} |
||||
// 发送POST请求必须设置如下两行
|
||||
conn.setDoOutput(true); |
||||
conn.setDoInput(true); |
||||
//获取请求头
|
||||
|
||||
// 获取URLConnection对象对应的输出流
|
||||
out = new PrintWriter(conn.getOutputStream()); |
||||
// 发送请求参数
|
||||
if (body != null) { |
||||
FineLoggerFactory.getLogger().info("content data: {}", body.toString()); |
||||
FineLoggerFactory.getLogger().info("content cover data: {}", new String(body.toString().getBytes("UTF-8"), "UTF-8")); |
||||
out.print(new String(body.toString().getBytes("UTF-8"), "UTF-8")); |
||||
} |
||||
// flush输出流的缓冲
|
||||
out.flush(); |
||||
// 定义BufferedReader输入流来读取URL的响应
|
||||
in = new BufferedReader( |
||||
new InputStreamReader(conn.getInputStream())); |
||||
String line; |
||||
while ((line = in.readLine()) != null) { |
||||
result += line; |
||||
} |
||||
res = result; |
||||
if (res.startsWith("null")) { |
||||
res = res.replace("null", ""); |
||||
} |
||||
} catch (Exception e) { |
||||
FineLoggerFactory.getLogger().error(e.getMessage(), e); |
||||
} |
||||
//使用finally块来关闭输出流、输入流
|
||||
finally { |
||||
try { |
||||
if (out != null) { |
||||
out.close(); |
||||
} |
||||
if (in != null) { |
||||
in.close(); |
||||
} |
||||
} catch (IOException e) { |
||||
FineLoggerFactory.getLogger().error(e.getMessage(), e); |
||||
} |
||||
} |
||||
return res; |
||||
} |
||||
|
||||
|
||||
public static String doPost(String url, Map<String, Object> header, JSONObject json) { |
||||
HttpClient client = HttpClients.createDefault(); |
||||
if (url.startsWith("https")) { |
||||
SSLContext sslcontext = createIgnoreVerifySSL(); |
||||
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() |
||||
.register("http", PlainConnectionSocketFactory.INSTANCE) |
||||
.register("https", new SSLConnectionSocketFactory(sslcontext)) |
||||
.build(); |
||||
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); |
||||
HttpClients.custom().setConnectionManager(connManager); |
||||
client = HttpClients.custom().setConnectionManager(connManager).build(); |
||||
} |
||||
HttpPost post = new HttpPost(url); |
||||
post.setHeader("accept", "*/*"); |
||||
post.setHeader("connection", "Keep-Alive"); |
||||
post.setHeader("Content-Type", "application/json"); |
||||
if (header != null) { |
||||
header.forEach((k, v) -> { |
||||
post.setHeader(k, String.valueOf(v)); |
||||
}); |
||||
} |
||||
try { |
||||
StringEntity s = new StringEntity(json.toString(),"UTF-8"); |
||||
s.setContentEncoding("UTF-8"); |
||||
s.setContentType("application/json; charset=UTF-8");//发送json数据需要设置contentType
|
||||
post.setEntity(s); |
||||
HttpResponse res = client.execute(post); |
||||
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { |
||||
String result = EntityUtils.toString(res.getEntity());// 返回json格式:
|
||||
return result; |
||||
} |
||||
} catch (Exception e) { |
||||
FineLoggerFactory.getLogger().error(e.getMessage(),e); |
||||
} |
||||
return null; |
||||
} |
||||
|
||||
private static void trustAllHttpsCertificates() throws Exception { |
||||
TrustManager[] trustAllCerts = new TrustManager[1]; |
||||
TrustManager tm = new miTM(); |
||||
trustAllCerts[0] = tm; |
||||
SSLContext sc = SSLContext.getInstance("SSL", "SunJSSE"); |
||||
sc.init(null, trustAllCerts, null); |
||||
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); |
||||
} |
||||
|
||||
|
||||
/** |
||||
* encode url by UTF-8 |
||||
* |
||||
* @param url url before encoding |
||||
* @return url after encoding |
||||
*/ |
||||
public static String encodeUrl(String url) { |
||||
String eurl = url; |
||||
try { |
||||
eurl = URLEncoder.encode(url, "UTF-8"); |
||||
} catch (UnsupportedEncodingException e) { |
||||
} |
||||
return eurl; |
||||
} |
||||
|
||||
private static class miTM implements TrustManager, |
||||
X509TrustManager { |
||||
@Override |
||||
public java.security.cert.X509Certificate[] getAcceptedIssuers() { |
||||
return null; |
||||
} |
||||
|
||||
public boolean isServerTrusted( |
||||
java.security.cert.X509Certificate[] certs) { |
||||
return true; |
||||
} |
||||
|
||||
public boolean isClientTrusted( |
||||
java.security.cert.X509Certificate[] certs) { |
||||
return true; |
||||
} |
||||
|
||||
@Override |
||||
public void checkServerTrusted( |
||||
java.security.cert.X509Certificate[] certs, String authType) |
||||
throws CertificateException { |
||||
return; |
||||
} |
||||
|
||||
@Override |
||||
public void checkClientTrusted( |
||||
java.security.cert.X509Certificate[] certs, String authType) |
||||
throws CertificateException { |
||||
return; |
||||
} |
||||
} |
||||
|
||||
public static SSLContext createIgnoreVerifySSL() { |
||||
try { |
||||
SSLContext sc = SSLContext.getInstance("SSLv3"); |
||||
|
||||
// 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
|
||||
X509TrustManager trustManager = new X509TrustManager() { |
||||
@Override |
||||
public void checkClientTrusted( |
||||
java.security.cert.X509Certificate[] paramArrayOfX509Certificate, |
||||
String paramString) throws CertificateException { |
||||
} |
||||
|
||||
@Override |
||||
public void checkServerTrusted( |
||||
java.security.cert.X509Certificate[] paramArrayOfX509Certificate, |
||||
String paramString) throws CertificateException { |
||||
} |
||||
|
||||
@Override |
||||
public java.security.cert.X509Certificate[] getAcceptedIssuers() { |
||||
return null; |
||||
} |
||||
}; |
||||
|
||||
sc.init(null, new TrustManager[]{trustManager}, null); |
||||
return sc; |
||||
} catch (Exception e) { |
||||
FineLoggerFactory.getLogger().error(e.getMessage(), e); |
||||
} |
||||
return null; |
||||
} |
||||
} |
@ -0,0 +1,11 @@
|
||||
package com.fr.plugin.wechat.sync; |
||||
|
||||
/** |
||||
* @Author fr.open |
||||
* @Date 2021/3/1 |
||||
* @Description |
||||
**/ |
||||
public class PluginConstants { |
||||
|
||||
public static final String PLUGIN_ID = "com.fr.plugin.wechat.sync"; |
||||
} |
@ -0,0 +1,43 @@
|
||||
package com.fr.plugin.wechat.sync; |
||||
|
||||
import com.fr.db.fun.impl.AbstractDBAccessProvider; |
||||
import com.fr.plugin.wechat.sync.dao.TagRoleDao; |
||||
import com.fr.plugin.wechat.sync.entity.TagRoleEntity; |
||||
import com.fr.stable.db.accessor.DBAccessor; |
||||
import com.fr.stable.db.dao.BaseDAO; |
||||
import com.fr.stable.db.dao.DAOProvider; |
||||
|
||||
/** |
||||
* @Author fr.open |
||||
* @Date 2021/7/29 |
||||
**/ |
||||
public class SyncDBAccessProvider extends AbstractDBAccessProvider { |
||||
|
||||
private static DBAccessor dbAccessor = null; |
||||
|
||||
public static DBAccessor getDbAccessor() { |
||||
return dbAccessor; |
||||
} |
||||
|
||||
@Override |
||||
public DAOProvider[] registerDAO() { |
||||
return new DAOProvider[]{ |
||||
new DAOProvider() { |
||||
@Override |
||||
public Class getEntityClass() { |
||||
return TagRoleEntity.class; |
||||
} |
||||
|
||||
@Override |
||||
public Class<? extends BaseDAO> getDAOClass() { |
||||
return TagRoleDao.class; |
||||
} |
||||
} |
||||
}; |
||||
} |
||||
|
||||
@Override |
||||
public void onDBAvailable(DBAccessor dbAccessor) { |
||||
SyncDBAccessProvider.dbAccessor = dbAccessor; |
||||
} |
||||
} |
@ -0,0 +1,76 @@
|
||||
package com.fr.plugin.wechat.sync; |
||||
|
||||
import com.fr.base.PropertiesUtils; |
||||
import com.fr.decision.fun.impl.AbstractGlobalRequestFilterProvider; |
||||
import com.fr.intelli.record.Focus; |
||||
import com.fr.intelli.record.Original; |
||||
import com.fr.log.FineLoggerFactory; |
||||
import com.fr.plugin.context.PluginContexts; |
||||
import com.fr.plugin.transform.FunctionRecorder; |
||||
import com.fr.plugin.wechat.sync.schedule.SyncThread; |
||||
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 java.util.HashMap; |
||||
import java.util.Map; |
||||
|
||||
/** |
||||
* @Author fr.open |
||||
* @Date 2021/7/29 |
||||
* @Description |
||||
**/ |
||||
@FunctionRecorder |
||||
@Authorize(callSignKey = PluginConstants.PLUGIN_ID) |
||||
public class SyncFilter extends AbstractGlobalRequestFilterProvider { |
||||
@Override |
||||
public String filterName() { |
||||
return "sync"; |
||||
} |
||||
|
||||
@Override |
||||
@Focus(id = PluginConstants.PLUGIN_ID, text = "微信同步", source = Original.PLUGIN) |
||||
public String[] urlPatterns() { |
||||
if (PluginContexts.currentContext().isAvailable()) { |
||||
initSchedule(); |
||||
} |
||||
return new String[]{"/syncWechat"}; |
||||
} |
||||
|
||||
|
||||
public static void initSchedule() { |
||||
JobKey jobKey = new JobKey("syncWechat", "syncGroup"); |
||||
try { |
||||
if (QuartzContext.getInstance().getScheduler().checkExists(jobKey)) { |
||||
ScheduleJobManager.getInstance().removeJob(jobKey.getName(), jobKey.getGroup()); |
||||
} |
||||
} catch (SchedulerException e) { |
||||
FineLoggerFactory.getLogger().error(e.getMessage(), e); |
||||
} |
||||
|
||||
addSchedule(jobKey); |
||||
} |
||||
|
||||
private static void addSchedule(JobKey jobKey) { |
||||
Map<String, Object> param = new HashMap(); |
||||
TriggerBuilder triggerBuilder = TriggerBuilder.newTrigger(); |
||||
triggerBuilder.forJob(jobKey.getName(), jobKey.getGroup()).withIdentity(jobKey.getName(), jobKey.getGroup()).startNow(); |
||||
String cron = PropertiesUtils.getProperties("wechat").getProperty("cron"); |
||||
if (StringUtils.isBlank(cron)) { |
||||
FineLoggerFactory.getLogger().error("cron is null schedule start failed"); |
||||
return; |
||||
} |
||||
CronScheduleBuilder schedule = CronScheduleBuilder.cronSchedule(cron); |
||||
triggerBuilder.withSchedule(schedule); |
||||
try { |
||||
ScheduleJobManager.getInstance().addJob(jobKey.getName(), jobKey.getGroup(), "sync job", SyncThread.class, triggerBuilder.build(), param); |
||||
} catch (Exception e) { |
||||
FineLoggerFactory.getLogger().error(e.getMessage(), e); |
||||
} |
||||
} |
||||
} |
@ -0,0 +1,20 @@
|
||||
package com.fr.plugin.wechat.sync.dao; |
||||
|
||||
import com.fr.plugin.wechat.sync.entity.TagRoleEntity; |
||||
import com.fr.stable.db.dao.BaseDAO; |
||||
import com.fr.stable.db.session.DAOSession; |
||||
|
||||
/** |
||||
* @Author fr.open |
||||
* @Date 2021/7/29 |
||||
* @Description |
||||
**/ |
||||
public class TagRoleDao extends BaseDAO<TagRoleEntity> { |
||||
public TagRoleDao(DAOSession daoSession) { |
||||
super(daoSession); |
||||
} |
||||
@Override |
||||
protected Class<TagRoleEntity> getEntityClass() { |
||||
return TagRoleEntity.class; |
||||
} |
||||
} |
@ -0,0 +1,75 @@
|
||||
package com.fr.plugin.wechat.sync.dao; |
||||
|
||||
import com.fr.log.FineLoggerFactory; |
||||
import com.fr.plugin.wechat.sync.SyncDBAccessProvider; |
||||
import com.fr.plugin.wechat.sync.entity.TagRoleEntity; |
||||
import com.fr.stable.db.action.DBAction; |
||||
import com.fr.stable.db.dao.DAOContext; |
||||
import com.fr.stable.query.QueryFactory; |
||||
import com.fr.stable.query.restriction.RestrictionFactory; |
||||
|
||||
import java.util.HashMap; |
||||
import java.util.List; |
||||
import java.util.Map; |
||||
import java.util.UUID; |
||||
import java.util.stream.Collectors; |
||||
|
||||
/** |
||||
* @Author fr.open |
||||
* @Date 2021/7/29 |
||||
* @Description |
||||
**/ |
||||
public class TagRoleService { |
||||
|
||||
public static TagRoleEntity create(TagRoleEntity entity) { |
||||
try { |
||||
return SyncDBAccessProvider.getDbAccessor().runDMLAction(new DBAction<TagRoleEntity>() { |
||||
|
||||
@Override |
||||
public TagRoleEntity run(DAOContext daoContext) throws Exception { |
||||
entity.setId(UUID.randomUUID().toString()); |
||||
daoContext.getDAO(TagRoleDao.class).add(entity); |
||||
return entity; |
||||
} |
||||
}); |
||||
} catch (Exception e) { |
||||
FineLoggerFactory.getLogger().error(e.getMessage(), e); |
||||
} |
||||
return entity; |
||||
} |
||||
|
||||
public static TagRoleEntity delete(String tagId) { |
||||
try { |
||||
return SyncDBAccessProvider.getDbAccessor().runDMLAction(new DBAction<TagRoleEntity>() { |
||||
|
||||
@Override |
||||
public TagRoleEntity run(DAOContext daoContext) throws Exception { |
||||
TagRoleDao dao = daoContext.getDAO(TagRoleDao.class); |
||||
TagRoleEntity entity = dao.findOne(QueryFactory.create().addRestriction(RestrictionFactory.eq("tagId", tagId))); |
||||
dao.remove(entity.getId()); |
||||
return entity; |
||||
} |
||||
}); |
||||
} catch (Exception e) { |
||||
FineLoggerFactory.getLogger().error(e.getMessage(), e); |
||||
} |
||||
return null; |
||||
} |
||||
|
||||
public static Map<String ,String> getLinkMap() { |
||||
Map<String ,String> map = new HashMap<>(); |
||||
try { |
||||
List<TagRoleEntity> tagRoleEntities = SyncDBAccessProvider.getDbAccessor().runDMLAction(new DBAction<List<TagRoleEntity>>() { |
||||
@Override |
||||
public List<TagRoleEntity> run(DAOContext daoContext) throws Exception { |
||||
TagRoleDao dao = daoContext.getDAO(TagRoleDao.class); |
||||
return dao.find(QueryFactory.create()); |
||||
} |
||||
}); |
||||
return tagRoleEntities.stream().collect(Collectors.toMap(e->e.getTagId(),e->e.getRoleId(),(k1,k2)->k2)); |
||||
} catch (Exception e) { |
||||
FineLoggerFactory.getLogger().error(e.getMessage(), e); |
||||
} |
||||
return map; |
||||
} |
||||
} |
@ -0,0 +1,47 @@
|
||||
package com.fr.plugin.wechat.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/7/29 |
||||
* @Description |
||||
**/ |
||||
|
||||
@Entity |
||||
@Table(name = "plugin_tag_role") |
||||
public class TagRoleEntity extends BaseEntity { |
||||
|
||||
@Column(name = "tagId") |
||||
private String tagId; |
||||
|
||||
@Column(name = "roleId") |
||||
private String roleId; |
||||
|
||||
public TagRoleEntity() { |
||||
} |
||||
|
||||
public TagRoleEntity(String tagId, String roleId) { |
||||
this.tagId = tagId; |
||||
this.roleId = roleId; |
||||
} |
||||
|
||||
public String getTagId() { |
||||
return tagId; |
||||
} |
||||
|
||||
public void setTagId(String tagId) { |
||||
this.tagId = tagId; |
||||
} |
||||
|
||||
public String getRoleId() { |
||||
return roleId; |
||||
} |
||||
|
||||
public void setRoleId(String roleId) { |
||||
this.roleId = roleId; |
||||
} |
||||
} |
@ -0,0 +1,209 @@
|
||||
package com.fr.plugin.wechat.sync.schedule; |
||||
|
||||
import com.fr.base.TableData; |
||||
import com.fr.cluster.core.ClusterNode; |
||||
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.service.user.UserMiddleRoleService; |
||||
import com.fr.file.TableDataConfig; |
||||
import com.fr.general.PropertiesUtils; |
||||
import com.fr.general.data.DataModel; |
||||
import com.fr.json.JSONArray; |
||||
import com.fr.json.JSONObject; |
||||
import com.fr.log.FineLoggerFactory; |
||||
import com.fr.plugin.wechat.sync.HttpUtil; |
||||
import com.fr.plugin.wechat.sync.dao.TagRoleService; |
||||
import com.fr.plugin.wechat.sync.entity.TagRoleEntity; |
||||
import com.fr.scheduler.job.FineScheduleJob; |
||||
import com.fr.script.Calculator; |
||||
import com.fr.stable.StringUtils; |
||||
import com.fr.stable.query.QueryFactory; |
||||
import com.fr.third.org.apache.http.entity.StringEntity; |
||||
import com.fr.third.v2.org.quartz.JobExecutionContext; |
||||
|
||||
import java.util.HashSet; |
||||
import java.util.List; |
||||
import java.util.Map; |
||||
import java.util.Set; |
||||
import java.util.stream.Collectors; |
||||
|
||||
/** |
||||
* @Author fr.open |
||||
* @Date 2021/7/29 |
||||
* @Description |
||||
**/ |
||||
public class SyncThread extends FineScheduleJob { |
||||
|
||||
private static final String tagList = "https://qyapi.weixin.qq.com/cgi-bin/tag/list?access_token="; |
||||
|
||||
private static final String TOKEN_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ID&corpsecret=SECRET"; |
||||
|
||||
private static final String DELETE_TAG_URL = "https://qyapi.weixin.qq.com/cgi-bin/tag/delete?access_token=ACCESS_TOKEN&tagid=TAGID"; |
||||
|
||||
private static final String TAG_LIST = "https://qyapi.weixin.qq.com/cgi-bin/tag/get?access_token=ACCESS_TOKEN&tagid=TAGID"; |
||||
|
||||
private static final String DELETE_USER_LIST = "https://qyapi.weixin.qq.com/cgi-bin/tag/deltagusers?access_token=ACCESS_TOKEN"; |
||||
|
||||
private static final String ADD_USER_LIST = "https://qyapi.weixin.qq.com/cgi-bin/tag/addtagusers?access_token=ACCESS_TOKEN"; |
||||
|
||||
private static final String ADD_TAG_URL = "https://qyapi.weixin.qq.com/cgi-bin/tag/create?access_token=ACCESS_TOKEN"; |
||||
|
||||
private DataModel dataModel; |
||||
|
||||
public SyncThread() { |
||||
String name = PropertiesUtils.getProperties("wechat").getProperty("name"); |
||||
FineLoggerFactory.getLogger().info("get table data config is {}", name); |
||||
TableData tableData = TableDataConfig.getInstance().getTableData(name); |
||||
dataModel = tableData.createDataModel(Calculator.createCalculator()); |
||||
} |
||||
|
||||
@Override |
||||
public void run(JobExecutionContext jobExecutionContext, ClusterNode clusterNode) throws Exception { |
||||
FineLoggerFactory.getLogger().info("start sync wechat users"); |
||||
String secret = PropertiesUtils.getProperties("wechat").getProperty("secret"); |
||||
String apid = PropertiesUtils.getProperties("wechat").getProperty("apid"); |
||||
String token = getToken(apid, secret); |
||||
if (StringUtils.isBlank(token)) { |
||||
return; |
||||
} |
||||
List<CustomRole> customRoles = AuthorityContext.getInstance().getCustomRoleController().find(QueryFactory.create()); |
||||
customRoles = customRoles.stream().filter(e -> !"superusers".equals(e.getName())).collect(Collectors.toList()); |
||||
FineLoggerFactory.getLogger().info("get role size is {}", customRoles.size()); |
||||
Map<String, CustomRole> map = customRoles.stream().collect(Collectors.toMap(e -> e.getId(), e -> e, (k1, k2) -> k2)); |
||||
Map<String, String> link = TagRoleService.getLinkMap(); |
||||
JSONArray tagList = getTagList(token); |
||||
Set<String> exist = new HashSet<>(); |
||||
for (int i = 0; i < tagList.size(); i++) { |
||||
JSONObject object = tagList.getJSONObject(i); |
||||
String tagid = object.getString("tagid"); |
||||
String name = object.getString("tagname"); |
||||
//不存在的tag不进行处理
|
||||
String roleId = link.get(tagid); |
||||
if (StringUtils.isBlank(roleId)) { |
||||
continue; |
||||
} |
||||
//如果
|
||||
CustomRole role = map.get(roleId); |
||||
if (role == null) { |
||||
//删除当前标签
|
||||
FineLoggerFactory.getLogger().info("delete tag is {}", name); |
||||
deleteTag(token, tagid); |
||||
TagRoleService.delete(tagid); |
||||
continue; |
||||
} |
||||
exist.add(roleId); |
||||
//获取当前角色下的用户
|
||||
Set<String> users = getUsers(roleId); |
||||
//获取当前标签下的用户
|
||||
Set<String> tagUserList = getTagUser(token, tagid); |
||||
//待删除tag的用户
|
||||
Set<String> deleteUsers = tagUserList.stream().filter(e -> !users.contains(e)).collect(Collectors.toSet()); |
||||
FineLoggerFactory.getLogger().info("delete users {} to tag:{}",deleteUsers,name); |
||||
deleteUser(token, tagid, deleteUsers); |
||||
//待添加的用户
|
||||
Set<String> addUsers = users.stream().filter(e -> !tagUserList.contains(e)).collect(Collectors.toSet()); |
||||
FineLoggerFactory.getLogger().info("add users {} to tag:{}",addUsers,name); |
||||
addUser(token, tagid, addUsers); |
||||
} |
||||
//角色中不存在的需要添加标签
|
||||
List<String> addTags = map.keySet().stream().filter(e -> !exist.contains(e)).collect(Collectors.toList()); |
||||
for (String role : addTags) { |
||||
CustomRole customRole = map.get(role); |
||||
String tagid = addTag(token, customRole.getName()); |
||||
TagRoleService.create(new TagRoleEntity(tagid, role)); |
||||
addUser(token, tagid, getUsers(role)); |
||||
} |
||||
|
||||
} |
||||
|
||||
private String addTag(String token, String name) { |
||||
JSONObject object = JSONObject.create().put("tagname", name); |
||||
StringEntity s = new StringEntity(object.toString(), "UTF-8"); |
||||
s.setContentEncoding("UTF-8"); |
||||
String res = HttpUtil.sendPost(ADD_TAG_URL.replace("ACCESS_TOKEN", token), null, object); |
||||
FineLoggerFactory.getLogger().info("add tag res is {}", res); |
||||
JSONObject resObj = new JSONObject(res); |
||||
return resObj.getString("tagid"); |
||||
} |
||||
|
||||
|
||||
private Set<String> getUsers(String roleId) throws Exception { |
||||
Set<String> ids = UserMiddleRoleService.getInstance().getAllUserIdsByCustomRole(roleId); |
||||
List<User> all = AuthorityContext.getInstance().getUserController().find(QueryFactory.create()); |
||||
Set<String> names = all.stream().filter(e -> ids.contains(e.getId())).map(e -> e.getUserName()).collect(Collectors.toSet()); |
||||
Set<String> userids = new HashSet<>(); |
||||
try { |
||||
for (int i = 0; i < dataModel.getRowCount(); i++) { |
||||
Object valueAt = dataModel.getValueAt(i, 4); |
||||
if (valueAt != null && names.contains(valueAt.toString())) { |
||||
Object id = dataModel.getValueAt(i, 6); |
||||
if(id != null && StringUtils.isNotBlank(id.toString())){ |
||||
userids.add(String.valueOf(id)); |
||||
} |
||||
} |
||||
} |
||||
} catch (Exception e) { |
||||
} |
||||
FineLoggerFactory.getLogger().info("get users ids {} by usernames {}",userids,names); |
||||
return userids; |
||||
} |
||||
|
||||
private void addUser(String token, String tagid, Set<String> addUsers) { |
||||
if (addUsers == null || addUsers.isEmpty()) { |
||||
return; |
||||
} |
||||
JSONObject object = JSONObject.create().put("tagid", Integer.valueOf(tagid)); |
||||
object.put("userlist", addUsers); |
||||
String res = HttpUtil.sendPost(ADD_USER_LIST.replace("ACCESS_TOKEN", token), null, object); |
||||
FineLoggerFactory.getLogger().info("add tag user res is {}", res); |
||||
} |
||||
|
||||
private void deleteUser(String token, String tagid, Set<String> deleteUsers) { |
||||
if (deleteUsers == null || deleteUsers.isEmpty()) { |
||||
return; |
||||
} |
||||
JSONObject object = JSONObject.create().put("tagid", Integer.valueOf(tagid)); |
||||
object.put("userlist", deleteUsers); |
||||
String res = HttpUtil.sendPost(DELETE_USER_LIST.replace("ACCESS_TOKEN", token), null, object); |
||||
FineLoggerFactory.getLogger().info("delete tag user res is {}", res); |
||||
} |
||||
|
||||
private Set<String> getTagUser(String token, String tagid) { |
||||
String res = HttpUtil.sendGet(TAG_LIST.replace("ACCESS_TOKEN", token).replace("TAGID", tagid), null, null); |
||||
FineLoggerFactory.getLogger().info("get tag user res is {}", res); |
||||
JSONObject object = new JSONObject(res); |
||||
JSONArray userlist = object.getJsonArray("userlist"); |
||||
Set<String> list = new HashSet<>(); |
||||
for (int i = 0; i < userlist.size(); i++) { |
||||
JSONObject jsonObject = userlist.getJSONObject(i); |
||||
list.add(jsonObject.getString("userid")); |
||||
} |
||||
return list; |
||||
} |
||||
|
||||
/** |
||||
* 删除tag |
||||
* |
||||
* @param token |
||||
* @param tagid |
||||
*/ |
||||
private void deleteTag(String token, String tagid) { |
||||
String res = HttpUtil.sendGet(DELETE_TAG_URL.replace("ACCESS_TOKEN", token).replace("TAGID", tagid), null, null); |
||||
FineLoggerFactory.getLogger().info("delete tag res is {}", res); |
||||
} |
||||
|
||||
private String getToken(String apid, String secret) { |
||||
String res = HttpUtil.sendGet(TOKEN_URL.replace("ID", apid).replace("SECRET", secret), null, null); |
||||
FineLoggerFactory.getLogger().info("get Token res is {}", res); |
||||
JSONObject object = new JSONObject(res); |
||||
return object.getString("access_token"); |
||||
} |
||||
|
||||
private JSONArray getTagList(String token) { |
||||
String res = HttpUtil.sendGet(tagList + token, null, null); |
||||
FineLoggerFactory.getLogger().info("get Tag res is {}", res); |
||||
JSONObject object = new JSONObject(res); |
||||
return object.getJsonArray("taglist"); |
||||
} |
||||
} |
@ -0,0 +1,6 @@
|
||||
apid=xxxx |
||||
secret=xxxx |
||||
##定时器参数,此配置为默认每小时执行一次 |
||||
cron=0 0/1 * * * ? * |
||||
##数据集名称 |
||||
name=xxxx |
@ -0,0 +1,16 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?> |
||||
<plugin> |
||||
<id>com.fr.plugin.patrol.sync</id> |
||||
<name><![CDATA[门户同步角色]]></name> |
||||
<active>yes</active> |
||||
<version>1.4</version> |
||||
<env-version>10.0</env-version> |
||||
<jartime>2018-07-31</jartime> |
||||
<vendor>fr.open</vendor> |
||||
<description><![CDATA[门户同步角色]]></description> |
||||
<change-notes><![CDATA[]]></change-notes> |
||||
<extra-decision> |
||||
<GlobalRequestFilterProvider class="com.fr.plugin.patrol.sync.SyncFilter"/> |
||||
</extra-decision> |
||||
<function-recorder class="com.fr.plugin.patrol.sync.SyncFilter"/> |
||||
</plugin> |
@ -0,0 +1,310 @@
|
||||
package com.fr.plugin.patrol.sync; |
||||
|
||||
import com.fr.json.JSONObject; |
||||
import com.fr.log.FineLoggerFactory; |
||||
import com.fr.third.org.apache.http.HttpResponse; |
||||
import com.fr.third.org.apache.http.HttpStatus; |
||||
import com.fr.third.org.apache.http.client.HttpClient; |
||||
import com.fr.third.org.apache.http.client.methods.HttpPost; |
||||
import com.fr.third.org.apache.http.config.Registry; |
||||
import com.fr.third.org.apache.http.config.RegistryBuilder; |
||||
import com.fr.third.org.apache.http.conn.socket.ConnectionSocketFactory; |
||||
import com.fr.third.org.apache.http.conn.socket.PlainConnectionSocketFactory; |
||||
import com.fr.third.org.apache.http.conn.ssl.SSLConnectionSocketFactory; |
||||
import com.fr.third.org.apache.http.entity.StringEntity; |
||||
import com.fr.third.org.apache.http.impl.client.HttpClients; |
||||
import com.fr.third.org.apache.http.impl.conn.PoolingHttpClientConnectionManager; |
||||
import com.fr.third.org.apache.http.util.EntityUtils; |
||||
|
||||
import javax.net.ssl.*; |
||||
import java.io.*; |
||||
import java.net.HttpURLConnection; |
||||
import java.net.URL; |
||||
import java.net.URLEncoder; |
||||
import java.security.cert.CertificateException; |
||||
import java.util.Iterator; |
||||
import java.util.Map; |
||||
import java.util.stream.Collectors; |
||||
|
||||
/** |
||||
* @author fr.open |
||||
* @date 2021/7/29 |
||||
*/ |
||||
public class HttpUtil { |
||||
|
||||
private static HostnameVerifier hv = new HostnameVerifier() { |
||||
@Override |
||||
public boolean verify(String urlHostName, SSLSession session) { |
||||
System.out.println("Warning: URL Host: " + urlHostName + " vs. " |
||||
+ session.getPeerHost()); |
||||
return true; |
||||
} |
||||
}; |
||||
|
||||
/** |
||||
* 发送get请求 |
||||
* |
||||
* @param url |
||||
* @param param |
||||
* @param header |
||||
* @return |
||||
* @throws IOException |
||||
*/ |
||||
public static String sendGet(String url, Map<String, String> param, Map<String, String> header) { |
||||
String result = ""; |
||||
BufferedReader in = null; |
||||
String urlNameString = url; |
||||
try { |
||||
if (param != null) { |
||||
urlNameString += "?"; |
||||
urlNameString += param.entrySet() |
||||
.stream() |
||||
.map(entry -> entry.getKey() + "=" + entry.getValue()) |
||||
.collect(Collectors.joining("&")); |
||||
} |
||||
|
||||
URL realUrl = new URL(urlNameString); |
||||
// 打开和URL之间的连接
|
||||
HttpURLConnection connection; |
||||
if (url.startsWith("https")) { |
||||
trustAllHttpsCertificates(); |
||||
HttpsURLConnection.setDefaultHostnameVerifier(hv); |
||||
connection = (HttpURLConnection) realUrl.openConnection(); |
||||
} else { |
||||
connection = (HttpURLConnection) realUrl.openConnection(); |
||||
} |
||||
//设置超时时间
|
||||
connection.setDoInput(true); |
||||
connection.setRequestMethod("GET"); |
||||
connection.setConnectTimeout(5000); |
||||
connection.setReadTimeout(15000); |
||||
// 设置通用的请求属性
|
||||
if (header != null) { |
||||
Iterator<Map.Entry<String, String>> it = header.entrySet().iterator(); |
||||
while (it.hasNext()) { |
||||
Map.Entry<String, String> entry = it.next(); |
||||
System.out.println(entry.getKey() + ":::" + entry.getValue()); |
||||
connection.setRequestProperty(entry.getKey(), entry.getValue()); |
||||
} |
||||
} |
||||
connection.setRequestProperty("accept", "*/*"); |
||||
connection.setRequestProperty("connection", "Keep-Alive"); |
||||
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); |
||||
// 建立实际的连接
|
||||
connection.connect(); |
||||
// 定义 BufferedReader输入流来读取URL的响应,设置utf8防止中文乱码
|
||||
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8")); |
||||
String line; |
||||
while ((line = in.readLine()) != null) { |
||||
result += line; |
||||
} |
||||
if (in != null) { |
||||
in.close(); |
||||
} |
||||
} catch (Exception e) { |
||||
FineLoggerFactory.getLogger().error(e, "get url error ,url is:{},error is {}", urlNameString, e.getMessage()); |
||||
} |
||||
return result; |
||||
} |
||||
|
||||
public static String sendPost(String url, Map<String, Object> header, JSONObject body) { |
||||
PrintWriter out = null; |
||||
BufferedReader in = null; |
||||
String result = null; |
||||
String res = null; |
||||
try { |
||||
String urlNameString = url; |
||||
|
||||
URL realUrl = new URL(urlNameString); |
||||
// 打开和URL之间的连接
|
||||
HttpURLConnection conn; |
||||
if (url.startsWith("https")) { |
||||
trustAllHttpsCertificates(); |
||||
HttpsURLConnection.setDefaultHostnameVerifier(hv); |
||||
conn = (HttpURLConnection) realUrl.openConnection(); |
||||
} else { |
||||
conn = (HttpURLConnection) realUrl.openConnection(); |
||||
} |
||||
// 设置通用的请求属性
|
||||
conn.setRequestProperty("accept", "*/*"); |
||||
conn.setRequestProperty("connection", "Keep-Alive"); |
||||
// conn.setRequestProperty("user-agent",
|
||||
// "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
|
||||
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); |
||||
if (header != null) { |
||||
header.forEach((k, v) -> { |
||||
conn.setRequestProperty(k, String.valueOf(v)); |
||||
}); |
||||
} |
||||
// 发送POST请求必须设置如下两行
|
||||
conn.setDoOutput(true); |
||||
conn.setDoInput(true); |
||||
//获取请求头
|
||||
|
||||
// 获取URLConnection对象对应的输出流
|
||||
out = new PrintWriter(conn.getOutputStream()); |
||||
// 发送请求参数
|
||||
if (body != null) { |
||||
FineLoggerFactory.getLogger().info("content data: {}", body.toString()); |
||||
FineLoggerFactory.getLogger().info("content cover data: {}", new String(body.toString().getBytes("UTF-8"), "UTF-8")); |
||||
out.print(new String(body.toString().getBytes("UTF-8"), "UTF-8")); |
||||
} |
||||
// flush输出流的缓冲
|
||||
out.flush(); |
||||
// 定义BufferedReader输入流来读取URL的响应
|
||||
in = new BufferedReader( |
||||
new InputStreamReader(conn.getInputStream())); |
||||
String line; |
||||
while ((line = in.readLine()) != null) { |
||||
result += line; |
||||
} |
||||
res = result; |
||||
if (res.startsWith("null")) { |
||||
res = res.replace("null", ""); |
||||
} |
||||
} catch (Exception e) { |
||||
FineLoggerFactory.getLogger().error(e.getMessage(), e); |
||||
} |
||||
//使用finally块来关闭输出流、输入流
|
||||
finally { |
||||
try { |
||||
if (out != null) { |
||||
out.close(); |
||||
} |
||||
if (in != null) { |
||||
in.close(); |
||||
} |
||||
} catch (IOException e) { |
||||
FineLoggerFactory.getLogger().error(e.getMessage(), e); |
||||
} |
||||
} |
||||
return res; |
||||
} |
||||
|
||||
|
||||
public static String doPost(String url, Map<String, Object> header, JSONObject json) { |
||||
HttpClient client = HttpClients.createDefault(); |
||||
if (url.startsWith("https")) { |
||||
SSLContext sslcontext = createIgnoreVerifySSL(); |
||||
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() |
||||
.register("http", PlainConnectionSocketFactory.INSTANCE) |
||||
.register("https", new SSLConnectionSocketFactory(sslcontext)) |
||||
.build(); |
||||
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); |
||||
HttpClients.custom().setConnectionManager(connManager); |
||||
client = HttpClients.custom().setConnectionManager(connManager).build(); |
||||
} |
||||
HttpPost post = new HttpPost(url); |
||||
post.setHeader("accept", "*/*"); |
||||
post.setHeader("connection", "Keep-Alive"); |
||||
post.setHeader("Content-Type", "application/json"); |
||||
if (header != null) { |
||||
header.forEach((k, v) -> { |
||||
post.setHeader(k, String.valueOf(v)); |
||||
}); |
||||
} |
||||
try { |
||||
StringEntity s = new StringEntity(json.toString(),"UTF-8"); |
||||
s.setContentEncoding("UTF-8"); |
||||
s.setContentType("application/json; charset=UTF-8");//发送json数据需要设置contentType
|
||||
post.setEntity(s); |
||||
HttpResponse res = client.execute(post); |
||||
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { |
||||
String result = EntityUtils.toString(res.getEntity());// 返回json格式:
|
||||
return result; |
||||
} |
||||
} catch (Exception e) { |
||||
FineLoggerFactory.getLogger().error(e.getMessage(),e); |
||||
} |
||||
return null; |
||||
} |
||||
|
||||
private static void trustAllHttpsCertificates() throws Exception { |
||||
TrustManager[] trustAllCerts = new TrustManager[1]; |
||||
TrustManager tm = new miTM(); |
||||
trustAllCerts[0] = tm; |
||||
SSLContext sc = SSLContext.getInstance("SSL", "SunJSSE"); |
||||
sc.init(null, trustAllCerts, null); |
||||
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); |
||||
} |
||||
|
||||
|
||||
/** |
||||
* encode url by UTF-8 |
||||
* |
||||
* @param url url before encoding |
||||
* @return url after encoding |
||||
*/ |
||||
public static String encodeUrl(String url) { |
||||
String eurl = url; |
||||
try { |
||||
eurl = URLEncoder.encode(url, "UTF-8"); |
||||
} catch (UnsupportedEncodingException e) { |
||||
} |
||||
return eurl; |
||||
} |
||||
|
||||
private static class miTM implements TrustManager, |
||||
X509TrustManager { |
||||
@Override |
||||
public java.security.cert.X509Certificate[] getAcceptedIssuers() { |
||||
return null; |
||||
} |
||||
|
||||
public boolean isServerTrusted( |
||||
java.security.cert.X509Certificate[] certs) { |
||||
return true; |
||||
} |
||||
|
||||
public boolean isClientTrusted( |
||||
java.security.cert.X509Certificate[] certs) { |
||||
return true; |
||||
} |
||||
|
||||
@Override |
||||
public void checkServerTrusted( |
||||
java.security.cert.X509Certificate[] certs, String authType) |
||||
throws CertificateException { |
||||
return; |
||||
} |
||||
|
||||
@Override |
||||
public void checkClientTrusted( |
||||
java.security.cert.X509Certificate[] certs, String authType) |
||||
throws CertificateException { |
||||
return; |
||||
} |
||||
} |
||||
|
||||
public static SSLContext createIgnoreVerifySSL() { |
||||
try { |
||||
SSLContext sc = SSLContext.getInstance("SSLv3"); |
||||
|
||||
// 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
|
||||
X509TrustManager trustManager = new X509TrustManager() { |
||||
@Override |
||||
public void checkClientTrusted( |
||||
java.security.cert.X509Certificate[] paramArrayOfX509Certificate, |
||||
String paramString) throws CertificateException { |
||||
} |
||||
|
||||
@Override |
||||
public void checkServerTrusted( |
||||
java.security.cert.X509Certificate[] paramArrayOfX509Certificate, |
||||
String paramString) throws CertificateException { |
||||
} |
||||
|
||||
@Override |
||||
public java.security.cert.X509Certificate[] getAcceptedIssuers() { |
||||
return null; |
||||
} |
||||
}; |
||||
|
||||
sc.init(null, new TrustManager[]{trustManager}, null); |
||||
return sc; |
||||
} catch (Exception e) { |
||||
FineLoggerFactory.getLogger().error(e.getMessage(), e); |
||||
} |
||||
return null; |
||||
} |
||||
} |
@ -0,0 +1,11 @@
|
||||
package com.fr.plugin.patrol.sync; |
||||
|
||||
/** |
||||
* @Author fr.open |
||||
* @Date 2021/3/1 |
||||
* @Description |
||||
**/ |
||||
public class PluginConstants { |
||||
|
||||
public static final String PLUGIN_ID = "com.fr.plugin.patrol.sync"; |
||||
} |
@ -0,0 +1,74 @@
|
||||
package com.fr.plugin.patrol.sync; |
||||
|
||||
import com.fr.base.PropertiesUtils; |
||||
import com.fr.decision.fun.impl.AbstractGlobalRequestFilterProvider; |
||||
import com.fr.intelli.record.Focus; |
||||
import com.fr.intelli.record.Original; |
||||
import com.fr.log.FineLoggerFactory; |
||||
import com.fr.plugin.context.PluginContexts; |
||||
import com.fr.plugin.patrol.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 java.util.HashMap; |
||||
import java.util.Map; |
||||
|
||||
/** |
||||
* @Author fr.open |
||||
* @Date 2021/7/29 |
||||
* @Description |
||||
**/ |
||||
@FunctionRecorder |
||||
@Authorize(callSignKey = PluginConstants.PLUGIN_ID) |
||||
public class SyncFilter extends AbstractGlobalRequestFilterProvider { |
||||
@Override |
||||
public String filterName() { |
||||
return "syncPatrol"; |
||||
} |
||||
|
||||
@Override |
||||
@Focus(id = PluginConstants.PLUGIN_ID, text = "门户角色同步", source = Original.PLUGIN) |
||||
public String[] urlPatterns() { |
||||
if (PluginContexts.currentContext().isAvailable()) { |
||||
initSchedule(); |
||||
} |
||||
return new String[]{"/syncPatrol"}; |
||||
} |
||||
|
||||
public static void initSchedule() { |
||||
JobKey jobKey = new JobKey("syncPatrol", "syncGroup"); |
||||
try { |
||||
if (QuartzContext.getInstance().getScheduler().checkExists(jobKey)) { |
||||
ScheduleJobManager.getInstance().removeJob(jobKey.getName(), jobKey.getGroup()); |
||||
} |
||||
} catch (SchedulerException e) { |
||||
FineLoggerFactory.getLogger().error(e.getMessage(), e); |
||||
} |
||||
addSchedule(jobKey); |
||||
} |
||||
|
||||
private static void addSchedule(JobKey jobKey) { |
||||
Map<String, Object> param = new HashMap(); |
||||
TriggerBuilder triggerBuilder = TriggerBuilder.newTrigger(); |
||||
triggerBuilder.forJob(jobKey.getName(), jobKey.getGroup()).withIdentity(jobKey.getName(), jobKey.getGroup()).startNow(); |
||||
String cron = PropertiesUtils.getProperties("patrol").getProperty("cron"); |
||||
if (StringUtils.isBlank(cron)) { |
||||
FineLoggerFactory.getLogger().error("cron is null schedule start failed"); |
||||
return; |
||||
} |
||||
CronScheduleBuilder schedule = CronScheduleBuilder.cronSchedule(cron); |
||||
triggerBuilder.withSchedule(schedule); |
||||
try { |
||||
ScheduleJobManager.getInstance().addJob(jobKey.getName(), jobKey.getGroup(), "sync job", SyncThread.class, triggerBuilder.build(), param); |
||||
} catch (Exception e) { |
||||
FineLoggerFactory.getLogger().error(e.getMessage(), e); |
||||
} |
||||
} |
||||
} |
@ -0,0 +1,188 @@
|
||||
package com.fr.plugin.patrol.sync.schedule; |
||||
|
||||
import com.fr.base.TableData; |
||||
import com.fr.cluster.core.ClusterNode; |
||||
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.service.user.UserMiddleRoleService; |
||||
import com.fr.file.TableDataConfig; |
||||
import com.fr.general.PropertiesUtils; |
||||
import com.fr.general.data.DataModel; |
||||
import com.fr.json.JSONArray; |
||||
import com.fr.json.JSONObject; |
||||
import com.fr.log.FineLoggerFactory; |
||||
import com.fr.plugin.patrol.sync.HttpUtil; |
||||
import com.fr.scheduler.job.FineScheduleJob; |
||||
import com.fr.script.Calculator; |
||||
import com.fr.stable.query.QueryFactory; |
||||
import com.fr.third.v2.org.quartz.JobExecutionContext; |
||||
|
||||
import java.util.*; |
||||
import java.util.stream.Collectors; |
||||
|
||||
/** |
||||
* @Author fr.open |
||||
* @Date 2021/7/29 |
||||
* @Description |
||||
**/ |
||||
public class SyncThread extends FineScheduleJob { |
||||
|
||||
private DataModel dataModel; |
||||
|
||||
private String addRole; |
||||
|
||||
private String getUser; |
||||
|
||||
private String addUser; |
||||
|
||||
private String deleteUser; |
||||
|
||||
private String createId; |
||||
|
||||
private String findRole; |
||||
|
||||
private String editRole; |
||||
|
||||
|
||||
public SyncThread() { |
||||
String name = PropertiesUtils.getProperties("patrol").getProperty("name"); |
||||
FineLoggerFactory.getLogger().info("get table data config is {}", name); |
||||
|
||||
addRole = PropertiesUtils.getProperties("patrol").getProperty("addRole"); |
||||
FineLoggerFactory.getLogger().info("get addRole config is {}", addRole); |
||||
|
||||
getUser = PropertiesUtils.getProperties("patrol").getProperty("getUser"); |
||||
FineLoggerFactory.getLogger().info("get getUser config is {}", getUser); |
||||
|
||||
addUser = PropertiesUtils.getProperties("patrol").getProperty("addUser"); |
||||
FineLoggerFactory.getLogger().info("get addUser config is {}", addUser); |
||||
|
||||
deleteUser = PropertiesUtils.getProperties("patrol").getProperty("deleteUser"); |
||||
FineLoggerFactory.getLogger().info("get deleteUser config is {}", deleteUser); |
||||
|
||||
createId = PropertiesUtils.getProperties("patrol").getProperty("createId"); |
||||
FineLoggerFactory.getLogger().info("get createId config is {}", createId); |
||||
|
||||
findRole = PropertiesUtils.getProperties("patrol").getProperty("findRole"); |
||||
FineLoggerFactory.getLogger().info("get findRole config is {}", findRole); |
||||
|
||||
editRole = PropertiesUtils.getProperties("patrol").getProperty("editRole"); |
||||
FineLoggerFactory.getLogger().info("get editRole config is {}", editRole); |
||||
TableData tableData = TableDataConfig.getInstance().getTableData(name); |
||||
dataModel = tableData.createDataModel(Calculator.createCalculator()); |
||||
} |
||||
|
||||
@Override |
||||
public void run(JobExecutionContext jobExecutionContext, ClusterNode clusterNode) throws Exception { |
||||
List<CustomRole> customRoles = AuthorityContext.getInstance().getCustomRoleController().find(QueryFactory.create()); |
||||
customRoles = customRoles.stream().filter(e -> !"superusers".equals(e.getName())).collect(Collectors.toList()); |
||||
FineLoggerFactory.getLogger().info("get role size is {}", customRoles); |
||||
Map<String, String> roleMap = getRoleMap(); |
||||
for (CustomRole role : customRoles) { |
||||
String roleCode = role.getId().replace("-", ""); |
||||
if (roleMap.containsKey(roleCode)) { |
||||
//角色名称不同则更新角色名称
|
||||
if (!role.getName().equals(roleMap.get(roleCode))) { |
||||
editRole(roleCode, role.getName()); |
||||
} |
||||
} else { |
||||
//首先新建角色
|
||||
roleCode = addRole(role); |
||||
} |
||||
//系统下的角色用户
|
||||
Map<String, String> users = getUsers(role.getId()); |
||||
//门户角色下用户
|
||||
Set<String> roleUsers = getRoleUser(roleCode); |
||||
|
||||
Set<String> delete = roleUsers.stream().filter(e -> !users.keySet().contains(e)).collect(Collectors.toSet()); |
||||
deleteRoleUser(roleCode, delete); |
||||
|
||||
Set<String> add = users.keySet().stream().filter(e -> !delete.contains(e)).collect(Collectors.toSet()); |
||||
addRoleUser(roleCode, add); |
||||
|
||||
} |
||||
} |
||||
|
||||
private void editRole(String code, String name) { |
||||
String res = HttpUtil.sendPost(editRole, null, new JSONObject().put("roleId", code).put("roleName", name).put("createId", createId)); |
||||
FineLoggerFactory.getLogger().info("edit role res is {}", res); |
||||
} |
||||
|
||||
private Map<String, String> getRoleMap() { |
||||
String res = HttpUtil.sendPost(findRole, null, new JSONObject().put("createId", createId)); |
||||
FineLoggerFactory.getLogger().info("get role res is {}", res); |
||||
JSONObject object = new JSONObject(res); |
||||
Map<String, String> map = new HashMap<>(); |
||||
JSONArray date = object.getJSONArray("data"); |
||||
for (int i = 0; i < date.size(); i++) { |
||||
JSONObject entries = date.getJSONObject(i); |
||||
map.put(entries.getString("roleId"), entries.getString("roleName")); |
||||
} |
||||
return map; |
||||
} |
||||
|
||||
private void addRoleUser(String roleCode, Set<String> add) { |
||||
if (add == null || add.isEmpty()) { |
||||
return; |
||||
} |
||||
Iterator<String> it = add.iterator(); |
||||
while (it.hasNext()) { |
||||
String next = it.next(); |
||||
String res = HttpUtil.sendPost(addUser, null, new JSONObject().put("roleId", roleCode).put("authorizationUser", next).put("createId", createId)); |
||||
FineLoggerFactory.getLogger().info("delete role users res is {}", res); |
||||
} |
||||
} |
||||
|
||||
private void deleteRoleUser(String roleCode, Set<String> delete) { |
||||
if (delete == null || delete.isEmpty()) { |
||||
return; |
||||
} |
||||
Iterator<String> it = delete.iterator(); |
||||
while (it.hasNext()) { |
||||
String next = it.next(); |
||||
String res = HttpUtil.sendPost(deleteUser, null, new JSONObject().put("roleId", roleCode).put("authorizationUser", next).put("createId", createId)); |
||||
FineLoggerFactory.getLogger().info("delete role users res is {}", res); |
||||
} |
||||
} |
||||
|
||||
private Set<String> getRoleUser(String roleCode) { |
||||
String res = HttpUtil.sendPost(getUser, null, new JSONObject().put("roleId", roleCode).put("createId", createId)); |
||||
FineLoggerFactory.getLogger().info("get role users res is {}", res); |
||||
JSONObject object = new JSONObject(res); |
||||
JSONArray date = object.getJSONObject("data").getJSONArray("userAuth"); |
||||
Set<String> users = new HashSet<>(); |
||||
for (int i = 0; i < date.size(); i++) { |
||||
JSONObject entries = date.getJSONObject(i); |
||||
users.add(entries.getString("userCode")); |
||||
} |
||||
return users; |
||||
} |
||||
|
||||
private String addRole(CustomRole role) { |
||||
String code = role.getId().replaceAll("-", ""); |
||||
JSONObject object = new JSONObject().put("roleId", code).put("roleName", role.getName()).put("createId", createId); |
||||
String res = HttpUtil.sendPost(addRole, null, object); |
||||
FineLoggerFactory.getLogger().info("add role res is {}", res); |
||||
return code; |
||||
} |
||||
|
||||
|
||||
private Map<String, String> getUsers(String roleId) throws Exception { |
||||
Set<String> ids = UserMiddleRoleService.getInstance().getAllUserIdsByCustomRole(roleId); |
||||
List<User> all = AuthorityContext.getInstance().getUserController().find(QueryFactory.create()); |
||||
Set<String> usersMap = all.stream().filter(e -> ids.contains(e.getId())).map(e -> e.getUserName()).collect(Collectors.toSet()); |
||||
Map<String, String> result = new HashMap<>(); |
||||
try { |
||||
for (int i = 0; i < dataModel.getRowCount(); i++) { |
||||
Object valueAt = dataModel.getValueAt(i, 4); |
||||
if (valueAt != null && usersMap.contains(valueAt.toString())) { |
||||
result.put(String.valueOf(dataModel.getValueAt(i, 7)), valueAt.toString()); |
||||
} |
||||
} |
||||
} catch (Exception e) { |
||||
|
||||
} |
||||
return result; |
||||
} |
||||
} |
@ -0,0 +1,37 @@
|
||||
package com.fr.plugin.patrol.sync.schedule; |
||||
|
||||
/** |
||||
* @Author fr.open |
||||
* @Date 2021/7/29 |
||||
* @Description |
||||
**/ |
||||
public class UserInfo { |
||||
|
||||
private String name; |
||||
|
||||
private String id; |
||||
|
||||
public UserInfo() { |
||||
} |
||||
|
||||
public UserInfo(String name, String id) { |
||||
this.name = name; |
||||
this.id = id; |
||||
} |
||||
|
||||
public String getName() { |
||||
return name; |
||||
} |
||||
|
||||
public void setName(String name) { |
||||
this.name = name; |
||||
} |
||||
|
||||
public String getId() { |
||||
return id; |
||||
} |
||||
|
||||
public void setId(String id) { |
||||
this.id = id; |
||||
} |
||||
} |
@ -0,0 +1,18 @@
|
||||
##定时器参数,此配置为默认每小时执行一次 |
||||
cron=0 0/1 * * * ? * |
||||
##增加角色 |
||||
addRole=http://ip:port/api/FndRole/add |
||||
##获取角色下用户 |
||||
getUser=http://ip:port/api/FndRole/getUserList |
||||
##向角色添加用户 |
||||
addUser=http://ip:port/api/FndRole/addUser |
||||
##向角色删除角色 |
||||
deleteUser=http://ip:port/api/FndRole/deleteUser |
||||
##更新角色 |
||||
editRole=http://ip:port/api/FndRole/roleModify |
||||
##获取角色 |
||||
findRole=http://ip:port/api/FndRole/getRoleList |
||||
##授权系统 |
||||
createId=001xxx |
||||
##数据集名称 |
||||
name=xxxx |
Binary file not shown.
Loading…
Reference in new issue