22 changed files with 1663 additions and 1 deletions
Binary file not shown.
@ -1,3 +1,6 @@
|
||||
# open-JSD-7868 |
||||
|
||||
JSD-7868 开源任务代码 |
||||
JSD-7868 开源任务代码\ |
||||
免责说明:该源码为第三方爱好者提供,不保证源码和方案的可靠性,也不提供任何形式的源码教学指导和协助!\ |
||||
仅作为开发者学习参考使用!禁止用于任何商业用途!\ |
||||
为保护开发者隐私,开发者信息已隐去!若原开发者希望公开自己的信息,可联系hugh处理。 |
@ -0,0 +1,7 @@
|
||||
#\u6570\u636Eurl |
||||
url=https://xxxxx/report/v1/report-data |
||||
method=POST |
||||
tokenUrl=https://xxxxx/sm/session |
||||
userid=xxxxx |
||||
value=xxxxx |
||||
prefix=https://xxxxx |
@ -0,0 +1,30 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?><plugin> |
||||
<id>com.fr.plugin.xxxxx.factory</id> |
||||
<name><![CDATA[数据工厂取数]]></name> |
||||
<active>yes</active> |
||||
<version>1.32</version> |
||||
<env-version>10.0</env-version> |
||||
<jartime>2018-07-31</jartime> |
||||
<vendor>fr.open</vendor> |
||||
<description><![CDATA[数据工厂取数]]></description> |
||||
<change-notes><![CDATA[ |
||||
<!--[2016-11-01]改进API接口,更加好的支持多多种类型的导出。<br/>--> |
||||
]]></change-notes> |
||||
<extra-core> |
||||
<TableDataLoader class="com.fr.plugin.xxxxx.factory.loader.DataFactoryLoader"/> |
||||
<TableDataLoader class="com.fr.plugin.xxxxx.factory.loader.PageDataFactoryLoader"/> |
||||
<TableDataResolver class="com.fr.plugin.xxxxx.factory.resolver.JsonPathResolver"/> |
||||
<TableDataResolver class="com.fr.plugin.xxxxx.factory.resolver.OpenApiResolver"/> |
||||
<TableDataResolver class="com.fr.plugin.xxxxx.factory.resolver.OpenApiFind"/> |
||||
<TableDataResolver class="com.fr.plugin.xxxxx.factory.resolver.GroupResolver"/> |
||||
<DBAccessProvider class="com.fr.plugin.xxxxx.factory.EncodeDBAccessProvider"/> |
||||
</extra-core> |
||||
<extra-decision> |
||||
<HttpHandlerProvider class="com.fr.plugin.xxxxx.factory.SsoRequestHandlerBridge"/> |
||||
<URLAliasProvider class="com.fr.plugin.xxxxx.factory.SsoRequestURLAliasBridge" /> |
||||
</extra-decision> |
||||
<function-recorder class="com.fr.plugin.xxxxx.factory.loader.DataFactoryLoader"/> |
||||
<dependence> |
||||
<Item key="com.tptj.plugin.hg.tabledata.factory.v10" type="plugin"/> |
||||
</dependence> |
||||
</plugin> |
@ -0,0 +1,43 @@
|
||||
package com.fr.plugin.xxxxx.factory; |
||||
|
||||
import com.fr.db.fun.impl.AbstractDBAccessProvider; |
||||
import com.fr.plugin.xxxxx.factory.dao.EncodeDao; |
||||
import com.fr.plugin.xxxxx.factory.entity.XxxxxEncodeEntity; |
||||
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 2020/5/24 |
||||
**/ |
||||
public class EncodeDBAccessProvider 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 XxxxxEncodeEntity.class; |
||||
} |
||||
|
||||
@Override |
||||
public Class<? extends BaseDAO> getDAOClass() { |
||||
return EncodeDao.class; |
||||
} |
||||
} |
||||
}; |
||||
} |
||||
|
||||
@Override |
||||
public void onDBAvailable(DBAccessor dbAccessor) { |
||||
EncodeDBAccessProvider.dbAccessor = dbAccessor; |
||||
} |
||||
} |
@ -0,0 +1,18 @@
|
||||
package com.fr.plugin.xxxxx.factory; |
||||
|
||||
import com.fr.decision.fun.HttpHandler; |
||||
import com.fr.decision.fun.impl.AbstractHttpHandlerProvider; |
||||
import com.fr.plugin.xxxxx.factory.handler.EncodeHttpHandler; |
||||
|
||||
/** |
||||
* @author fr.open |
||||
* @since 2020/08/28 |
||||
*/ |
||||
public class SsoRequestHandlerBridge extends AbstractHttpHandlerProvider { |
||||
@Override |
||||
public HttpHandler[] registerHandlers() { |
||||
return new HttpHandler[]{ |
||||
new EncodeHttpHandler(), |
||||
}; |
||||
} |
||||
} |
@ -0,0 +1,18 @@
|
||||
package com.fr.plugin.xxxxx.factory; |
||||
|
||||
import com.fr.decision.fun.impl.AbstractURLAliasProvider; |
||||
import com.fr.decision.webservice.url.alias.URLAlias; |
||||
import com.fr.decision.webservice.url.alias.URLAliasFactory; |
||||
|
||||
/** |
||||
* @author fr.open |
||||
* @since 2020/08/28 |
||||
*/ |
||||
public class SsoRequestURLAliasBridge extends AbstractURLAliasProvider { |
||||
@Override |
||||
public URLAlias[] registerAlias() { |
||||
return new URLAlias[]{ |
||||
URLAliasFactory.createPluginAlias("/encode", "/encode", false), |
||||
}; |
||||
} |
||||
} |
@ -0,0 +1,21 @@
|
||||
package com.fr.plugin.xxxxx.factory.dao; |
||||
|
||||
import com.fr.plugin.xxxxx.factory.entity.XxxxxEncodeEntity; |
||||
import com.fr.stable.db.dao.BaseDAO; |
||||
import com.fr.stable.db.session.DAOSession; |
||||
|
||||
/** |
||||
* @Author fr.open |
||||
* @Date 2021/5/5 |
||||
* @Description |
||||
**/ |
||||
public class EncodeDao extends BaseDAO<XxxxxEncodeEntity> { |
||||
public EncodeDao(DAOSession daoSession) { |
||||
super(daoSession); |
||||
} |
||||
|
||||
@Override |
||||
protected Class<XxxxxEncodeEntity> getEntityClass() { |
||||
return XxxxxEncodeEntity.class; |
||||
} |
||||
} |
@ -0,0 +1,34 @@
|
||||
package com.fr.plugin.xxxxx.factory.entity; |
||||
|
||||
/** |
||||
* @Author fr.open |
||||
* @Date 2020/11/13 |
||||
* @Description |
||||
**/ |
||||
public class Token { |
||||
|
||||
private String token; |
||||
|
||||
private Long timeout; |
||||
|
||||
public Token(String token, long timeout) { |
||||
this.timeout = timeout; |
||||
this.token = token; |
||||
} |
||||
|
||||
public String getToken() { |
||||
return token; |
||||
} |
||||
|
||||
public void setToken(String token) { |
||||
this.token = token; |
||||
} |
||||
|
||||
public Long getTimeout() { |
||||
return timeout; |
||||
} |
||||
|
||||
public void setTimeout(Long timeout) { |
||||
this.timeout = timeout; |
||||
} |
||||
} |
@ -0,0 +1,39 @@
|
||||
package com.fr.plugin.xxxxx.factory.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/5 |
||||
* @Description |
||||
**/ |
||||
@Entity |
||||
@Table(name = "plugin_xxxxx_encode") |
||||
public class XxxxxEncodeEntity extends BaseEntity { |
||||
|
||||
private static final long serialVersionUID = 8781741191091741666L; |
||||
|
||||
@Column(name = "prop", length = 500) |
||||
private String prop; |
||||
@Column(name = "encode", length = 500) |
||||
private String encode; |
||||
|
||||
public String getProp() { |
||||
return prop; |
||||
} |
||||
|
||||
public void setProp(String prop) { |
||||
this.prop = prop; |
||||
} |
||||
|
||||
public String getEncode() { |
||||
return encode; |
||||
} |
||||
|
||||
public void setEncode(String encode) { |
||||
this.encode = encode; |
||||
} |
||||
} |
@ -0,0 +1,43 @@
|
||||
package com.fr.plugin.xxxxx.factory.handler; |
||||
|
||||
import com.fr.decision.fun.impl.BaseHttpHandler; |
||||
import com.fr.json.JSONObject; |
||||
import com.fr.plugin.xxxxx.factory.util.GCMUtils; |
||||
import com.fr.third.springframework.web.bind.annotation.RequestMethod; |
||||
import com.fr.web.utils.WebUtils; |
||||
|
||||
import javax.servlet.http.HttpServletRequest; |
||||
import javax.servlet.http.HttpServletResponse; |
||||
|
||||
/** |
||||
* @Author fr.open |
||||
* @Date 2021/5/5 |
||||
* @Description |
||||
**/ |
||||
public class EncodeHttpHandler extends BaseHttpHandler { |
||||
|
||||
@Override |
||||
public RequestMethod getMethod() { |
||||
return RequestMethod.GET; |
||||
} |
||||
|
||||
@Override |
||||
public String getPath() { |
||||
return "/encode"; |
||||
} |
||||
|
||||
@Override |
||||
public boolean isPublic() { |
||||
return false; |
||||
} |
||||
|
||||
@Override |
||||
public void handle(HttpServletRequest req, HttpServletResponse res) throws Exception { |
||||
res.setContentType("application/json;charset=UTF-8"); |
||||
String key = req.getParameter("encode"); |
||||
JSONObject object = new JSONObject(); |
||||
object.put("body", GCMUtils.encode(key)); |
||||
object.put("time", System.currentTimeMillis()); |
||||
WebUtils.printAsJSON(res, object); |
||||
} |
||||
} |
@ -0,0 +1,100 @@
|
||||
package com.fr.plugin.xxxxx.factory.loader; |
||||
|
||||
import com.fr.json.JSONObject; |
||||
import com.fr.log.FineLoggerFactory; |
||||
import com.fr.plugin.xxxxx.factory.util.DataUtil; |
||||
import com.fr.plugin.xxxxx.factory.util.HttpUtil; |
||||
import com.fr.plugin.xxxxx.factory.util.TokenFactory; |
||||
import com.fr.plugin.transform.FunctionRecorder; |
||||
import com.fr.script.Calculator; |
||||
import com.fr.stable.ParameterProvider; |
||||
import com.fr.stable.StringUtils; |
||||
import com.fr.third.org.apache.commons.lang3.time.StopWatch; |
||||
import com.tptj.plugin.hg.impl.AbstractLoader; |
||||
|
||||
import java.util.Map; |
||||
import java.util.concurrent.TimeUnit; |
||||
|
||||
/** |
||||
* @Author fr.open |
||||
* @Date 2020/12/4 |
||||
* @Description |
||||
**/ |
||||
@FunctionRecorder |
||||
public class DataFactoryLoader extends AbstractLoader { |
||||
@Override |
||||
public Object load(Calculator calculator, ParameterProvider[] parameterProviders, String others) { |
||||
StopWatch stopWatch = StopWatch.createStarted(); |
||||
JSONObject param = new JSONObject(others);//DataUtil.getJSON(others);
|
||||
if (param.isEmpty()) { |
||||
return null; |
||||
} |
||||
if (!param.has("method") || StringUtils.isBlank(param.getString("method"))) { |
||||
; |
||||
param.put("method", DataUtil.getProp("method")); |
||||
} |
||||
if (!param.has("tokenUrl") || StringUtils.isBlank(param.getString("tokenUrl"))) { |
||||
param.put("tokenUrl", DataUtil.getProp("tokenUrl")); |
||||
} else { |
||||
if (!param.getString("tokenUrl").startsWith("http")) { |
||||
param.put("tokenUrl", DataUtil.getProp("prefix") + param.getString("tokenUrl")); |
||||
} |
||||
} |
||||
if (!param.has("userid") || StringUtils.isBlank(param.getString("userid"))) { |
||||
param.put("userid", DataUtil.getProp("userid")); |
||||
} |
||||
if (!param.has("value") || StringUtils.isBlank(param.getString("value"))) { |
||||
param.put("value", DataUtil.getProp("value")); |
||||
} |
||||
if (!param.has("url") || StringUtils.isBlank(param.getString("url"))) { |
||||
param.put("url", DataUtil.getProp("url")); |
||||
} else { |
||||
if (!param.getString("url").startsWith("http")) { |
||||
param.put("url", DataUtil.getProp("prefix") + param.getString("url")); |
||||
} |
||||
} |
||||
String res = StringUtils.EMPTY; |
||||
String token = TokenFactory.getToken(param.getString("tokenUrl"), param.getString("userid"), param.getString("value")); |
||||
if (StringUtils.isBlank(token)) { |
||||
FineLoggerFactory.getLogger().error("get token is null"); |
||||
return null; |
||||
} |
||||
FineLoggerFactory.getLogger().info("get token is {} by url {}", token, param.getString("tokenUrl")); |
||||
Map<String, Object> headerMap = param.getJSONObject("header") == null ? null : DataUtil.parseHeader(param.getJSONObject("header")); |
||||
headerMap.put("openid", token); |
||||
FineLoggerFactory.getLogger().info("header is {}", headerMap); |
||||
Map<String, Object> paraMap = param.getJSONObject("para") == null ? null : DataUtil.parseHeader(param.getJSONObject("para")); |
||||
FineLoggerFactory.getLogger().info("para is {}", paraMap); |
||||
JSONObject body = param.getJSONObject("data") == null ? new JSONObject() : param.getJSONObject("data"); |
||||
FineLoggerFactory.getLogger().info("data is {}", body); |
||||
if (param.getString("method").equalsIgnoreCase("GET")) { |
||||
res = HttpUtil.sendGet(param.getString("url"), paraMap, headerMap, null); |
||||
} else if (param.getString("method").equalsIgnoreCase("POST")) { |
||||
res = HttpUtil.doJSONPost(param.getString("url"), headerMap, body, paraMap, null); |
||||
} |
||||
FineLoggerFactory.getLogger().info("the url {} response data is {}", param.getString("url"), res); |
||||
stopWatch.stop(); |
||||
FineLoggerFactory.getLogger().error("load openApi data cost {}", stopWatch.getTime(TimeUnit.SECONDS)); |
||||
return res; |
||||
} |
||||
|
||||
@Override |
||||
public String getName() { |
||||
return "openApi"; |
||||
} |
||||
|
||||
@Override |
||||
public String getDefaultConfig() { |
||||
return "{\n" + |
||||
" \"url\": \"\",\n" + |
||||
" \"data\": {\n" + |
||||
" },\n" + |
||||
" \"para\": {},\n" + |
||||
" \"header\": {},\n" + |
||||
" \"method\": \"POST\",\n" + |
||||
" \"tokenUrl\": \"https://xxxxx/sm/session\",\n" + |
||||
" \"userid\": \"\",\n" + |
||||
" \"value\": \"\"\n" + |
||||
"}"; |
||||
} |
||||
} |
@ -0,0 +1,123 @@
|
||||
package com.fr.plugin.xxxxx.factory.loader; |
||||
|
||||
import com.fr.json.JSONObject; |
||||
import com.fr.log.FineLoggerFactory; |
||||
import com.fr.plugin.xxxxx.factory.util.DataUtil; |
||||
import com.fr.plugin.xxxxx.factory.util.HttpUtil; |
||||
import com.fr.plugin.xxxxx.factory.util.TokenFactory; |
||||
import com.fr.script.Calculator; |
||||
import com.fr.stable.ParameterProvider; |
||||
import com.fr.stable.StringUtils; |
||||
import com.fr.third.org.apache.commons.lang3.time.StopWatch; |
||||
import com.tptj.plugin.hg.impl.AbstractLoader; |
||||
|
||||
import java.util.Map; |
||||
import java.util.concurrent.TimeUnit; |
||||
|
||||
/** |
||||
* @Author fr.open |
||||
* @Date 2020/12/4 |
||||
* @Description |
||||
**/ |
||||
public class PageDataFactoryLoader extends AbstractLoader { |
||||
|
||||
@Override |
||||
public Object load(Calculator calculator, ParameterProvider[] parameterProviders, String others) { |
||||
StopWatch stopWatch = StopWatch.createStarted(); |
||||
JSONObject param = new JSONObject(others);//DataUtil.getJSON(others);
|
||||
if(param.isEmpty()){ |
||||
return null; |
||||
} |
||||
if (!param.has("method") || StringUtils.isBlank(param.getString("method"))) { |
||||
; |
||||
param.put("method", DataUtil.getProp("method")); |
||||
} |
||||
if (!param.has("tokenUrl") || StringUtils.isBlank(param.getString("tokenUrl"))) { |
||||
param.put("tokenUrl", DataUtil.getProp("tokenUrl")); |
||||
} else { |
||||
if (!param.getString("tokenUrl").startsWith("http")) { |
||||
param.put("tokenUrl", DataUtil.getProp("prefix") + param.getString("tokenUrl")); |
||||
} |
||||
} |
||||
if (!param.has("userid") || StringUtils.isBlank(param.getString("userid"))) { |
||||
param.put("userid", DataUtil.getProp("userid")); |
||||
} |
||||
if (!param.has("value") || StringUtils.isBlank(param.getString("value"))) { |
||||
param.put("value", DataUtil.getProp("value")); |
||||
} |
||||
if (!param.has("url") || StringUtils.isBlank(param.getString("url"))) { |
||||
param.put("url", DataUtil.getProp("url")); |
||||
} else { |
||||
if (!param.getString("url").startsWith("http")) { |
||||
param.put("url", DataUtil.getProp("prefix") + param.getString("url")); |
||||
} |
||||
} |
||||
String res = StringUtils.EMPTY; |
||||
String token = TokenFactory.getToken(param.getString("tokenUrl"), param.getString("userid"), param.getString("value")); |
||||
if (StringUtils.isBlank(token)) { |
||||
FineLoggerFactory.getLogger().error("get token is null"); |
||||
return null; |
||||
} |
||||
FineLoggerFactory.getLogger().info("get token is {} by url {}", token, param.getString("tokenUrl")); |
||||
Map<String, Object> headerMap = param.getJSONObject("header") == null ? null : DataUtil.parseHeader(param.getJSONObject("header")); |
||||
headerMap.put("openid", token); |
||||
FineLoggerFactory.getLogger().info("header is {}", headerMap); |
||||
Map<String, Object> paraMap = param.getJSONObject("para") == null ? null : DataUtil.parseHeader(param.getJSONObject("para")); |
||||
FineLoggerFactory.getLogger().info("para is {}", paraMap); |
||||
JSONObject body = param.getJSONObject("data") == null ? new JSONObject() : param.getJSONObject("data"); |
||||
FineLoggerFactory.getLogger().info("data is {}", body); |
||||
if (param.getString("method").equalsIgnoreCase("GET")) { |
||||
res = HttpUtil.sendGet(param.getString("url"), paraMap, headerMap, null); |
||||
} else if (param.getString("method").equalsIgnoreCase("POST")) { |
||||
res = HttpUtil.doJSONPost(param.getString("url"), headerMap, body, paraMap, null); |
||||
} |
||||
JSONObject data = JSONObject.create(); |
||||
//获取分页
|
||||
if (StringUtils.isNotBlank(res)) { |
||||
JSONObject object = new JSONObject(res); |
||||
data = object; |
||||
while (object.has("hasNextPage") && object.getBoolean("hasNextPage")) { |
||||
int page = object.getInt("currentPage"); |
||||
FineLoggerFactory.getLogger().info("the url {} current page is {} has next page", param.getString("url"), ++page); |
||||
if (param.getString("method").equalsIgnoreCase("GET")) { |
||||
JSONObject p = param.getJSONObject("header").getJSONObject("params"); |
||||
p = p == null ? JSONObject.create() : p; |
||||
p.put("pageIndex", page); |
||||
headerMap.put("params", p.toString()); |
||||
res = HttpUtil.sendGet(param.getString("url"), paraMap, headerMap, null); |
||||
} else if (param.getString("method").equalsIgnoreCase("POST")) { |
||||
body.put("pageIndex", page); |
||||
res = HttpUtil.doJSONPost(param.getString("url"), headerMap, body, paraMap, null); |
||||
} |
||||
JSONObject temp = new JSONObject(res); |
||||
data.getJsonArray("data").addAll(temp.getJSONArray("data")); |
||||
object = temp; |
||||
} |
||||
} |
||||
FineLoggerFactory.getLogger().info("the url {} response data is {}", param.getString("url"), data); |
||||
stopWatch.stop(); |
||||
FineLoggerFactory.getLogger().error("load page openApi data cost {}",stopWatch.getTime(TimeUnit.SECONDS)); |
||||
return data; |
||||
} |
||||
|
||||
|
||||
@Override |
||||
public String getName() { |
||||
return "openApi分页"; |
||||
} |
||||
|
||||
@Override |
||||
public String getDefaultConfig() { |
||||
return "{\n" + |
||||
" \"url\": \"\",\n" + |
||||
" \"data\": {\n" + |
||||
" },\n" + |
||||
" \"para\": {},\n" + |
||||
" \"header\": {},\n" + |
||||
" \"method\": \"POST\",\n" + |
||||
" \"tokenUrl\": \"https://xxxxx/sm/session\",\n" + |
||||
" \"userid\": \"\",\n" + |
||||
" \"value\": \"\"\n" + |
||||
"}"; |
||||
} |
||||
} |
@ -0,0 +1,103 @@
|
||||
package com.fr.plugin.xxxxx.factory.resolver; |
||||
|
||||
import com.fr.json.JSONArray; |
||||
import com.fr.json.JSONObject; |
||||
import com.fr.plugin.xxxxx.factory.util.DataUtil; |
||||
import com.fr.stable.StringUtils; |
||||
import com.tptj.plugin.hg.impl.AbstractResolver; |
||||
import com.tptj.plugin.hg.stable.SimpleDataModel; |
||||
|
||||
import java.util.*; |
||||
import java.util.stream.Collectors; |
||||
|
||||
/** |
||||
* @Author fr.open |
||||
* @Date 2021/1/27 |
||||
* @Description |
||||
**/ |
||||
public class GroupResolver extends AbstractResolver { |
||||
@Override |
||||
public SimpleDataModel parse(Object data, String others) { |
||||
SimpleDataModel dataModel = new SimpleDataModel(); |
||||
List<Object[]> datas = new ArrayList<>(); |
||||
List<String> columns = new ArrayList<>(); |
||||
JSONObject config = new JSONObject(others); |
||||
if (!config.has("group") || StringUtils.isBlank(config.getString("group"))) { |
||||
return null; |
||||
} |
||||
if (!config.has("data") || StringUtils.isBlank(config.getString("data"))) { |
||||
return null; |
||||
} |
||||
String configGroup = config.getString("group"); |
||||
int index = configGroup.indexOf("=="); |
||||
String groupName = configGroup; |
||||
String groupData = null; |
||||
if(index != -1){ |
||||
groupName = configGroup.substring(0,index); |
||||
groupData = configGroup.substring(index+2); |
||||
} |
||||
String configData = config.getString("data"); |
||||
columns.add(groupName); |
||||
columns.add(configData); |
||||
JSONObject jsonData = new JSONObject(data.toString()); |
||||
if (!jsonData.has("data")) { |
||||
return null; |
||||
} |
||||
JSONArray array = jsonData.getJSONArray("data"); |
||||
Map<String, Set<Object>> map = new HashMap(); |
||||
for (int i = 0; i < array.size(); i++) { |
||||
JSONObject object = array.getJSONObject(i); |
||||
if (!object.has(groupName) || StringUtils.isBlank(object.getString(groupName))) { |
||||
continue; |
||||
} |
||||
if (!object.has(configData) || StringUtils.isBlank(object.getString(configData))) { |
||||
continue; |
||||
} |
||||
String group = object.getString(groupName); |
||||
if(StringUtils.isNotBlank(groupData) && !hasGroup(group,groupData)){ |
||||
continue; |
||||
} |
||||
String d = object.getString(configData); |
||||
Set<Object> list = new HashSet<>(); |
||||
if (map.containsKey(group)) { |
||||
list = map.get(group); |
||||
} |
||||
list.add(d); |
||||
map.put(group, list); |
||||
} |
||||
Iterator<String> iterator = map.keySet().iterator(); |
||||
while (iterator.hasNext()) { |
||||
String key = iterator.next(); |
||||
Set<Object> value = map.get(key); |
||||
Object[] row = new Object[]{key, value.stream().map(e -> e.toString()).collect(Collectors.joining(","))}; |
||||
datas.add(row); |
||||
} |
||||
dataModel.setCols(DataUtil.translate(columns,config.getBoolean("translate"))); |
||||
dataModel.setDatas(datas); |
||||
return dataModel; |
||||
} |
||||
|
||||
private boolean hasGroup(String group, String config) { |
||||
String[] arr = config.split(","); |
||||
for (String str : arr){ |
||||
if(StringUtils.equals(str,group)){ |
||||
return true; |
||||
} |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
@Override |
||||
public String getName() { |
||||
return "分组解析器"; |
||||
} |
||||
|
||||
@Override |
||||
public String getDefaultConfig() { |
||||
return "{\n" + |
||||
" \"group\":\"\",\n" + |
||||
" \"data\":\"\",\n" + |
||||
" \"translate\":\"false\",\n" + |
||||
"}"; |
||||
} |
||||
} |
@ -0,0 +1,85 @@
|
||||
package com.fr.plugin.xxxxx.factory.resolver; |
||||
|
||||
import com.fr.json.JSONObject; |
||||
import com.fr.plugin.xxxxx.factory.util.DataUtil; |
||||
import com.fr.stable.StringUtils; |
||||
import com.jayway.jsonpath.JsonPath; |
||||
import com.tptj.plugin.hg.impl.AbstractResolver; |
||||
import com.tptj.plugin.hg.stable.SimpleDataModel; |
||||
|
||||
import java.util.ArrayList; |
||||
import java.util.List; |
||||
import java.util.Map; |
||||
|
||||
/** |
||||
* @Author fr.open |
||||
* @Date 2020/11/26 |
||||
* @Description |
||||
**/ |
||||
public class JsonPathResolver extends AbstractResolver { |
||||
|
||||
@Override |
||||
public SimpleDataModel parse(Object data, String others) { |
||||
SimpleDataModel dataModel = new SimpleDataModel(); |
||||
String query = others; |
||||
JSONObject param = null; |
||||
if(others.startsWith("{")){ |
||||
param = new JSONObject(others); |
||||
query = param.getString("query"); |
||||
|
||||
} |
||||
Object res = JsonPath.read(data.toString(), query); |
||||
List<Object[]> datas = new ArrayList<>(); |
||||
List<String> columns = new ArrayList<>(); |
||||
if (res instanceof List) { |
||||
List<Map> list = (List<Map>) res; |
||||
for (Map map : list) { |
||||
if (map.keySet().size() > columns.size()) { |
||||
columns = new ArrayList(map.keySet()); |
||||
} |
||||
} |
||||
for (Map map : list) { |
||||
Object[] row = new Object[columns.size()]; |
||||
for (int i = 0; i < columns.size(); i++) { |
||||
row[i] = map.get(columns.get(i)); |
||||
} |
||||
datas.add(row); |
||||
} |
||||
|
||||
} else if (res instanceof Map) { |
||||
Map map = (Map) res; |
||||
columns = new ArrayList(map.keySet()); |
||||
Object[] row = new Object[columns.size()]; |
||||
for (int i = 0; i < columns.size(); i++) { |
||||
row[i] = map.get(columns.get(i)); |
||||
} |
||||
datas.add(row); |
||||
} else { |
||||
columns.add("data"); |
||||
datas.add(new Object[]{res}); |
||||
} |
||||
dataModel.setDatas(datas); |
||||
if(param != null){ |
||||
dataModel.setCols(DataUtil.translate(columns, param.getBoolean("translate"))); |
||||
return DataUtil.sort(dataModel,param == null? StringUtils.EMPTY:param.getString("sort")); |
||||
}else { |
||||
dataModel.setCols(columns); |
||||
} |
||||
return dataModel; |
||||
} |
||||
|
||||
@Override |
||||
public String getName() { |
||||
return "JPath解析"; |
||||
} |
||||
|
||||
@Override |
||||
public String getDefaultConfig() { |
||||
return "{\n" + |
||||
"\"query\":\"$\",\n" + |
||||
"\"sort\":\"\",\n" + |
||||
"\"translate\":\"false\",\n" + |
||||
"}"; |
||||
} |
||||
|
||||
} |
@ -0,0 +1,130 @@
|
||||
package com.fr.plugin.xxxxx.factory.resolver; |
||||
|
||||
import com.fr.json.JSONObject; |
||||
import com.fr.log.FineLoggerFactory; |
||||
import com.fr.plugin.xxxxx.factory.util.DataUtil; |
||||
import com.fr.stable.StringUtils; |
||||
import com.jayway.jsonpath.JsonPath; |
||||
import com.tptj.plugin.hg.impl.AbstractResolver; |
||||
import com.tptj.plugin.hg.stable.SimpleDataModel; |
||||
|
||||
import java.util.*; |
||||
|
||||
/** |
||||
* @Author fr.open |
||||
* @Date 2020/12/7 |
||||
* @Description |
||||
**/ |
||||
public class OpenApiFind extends AbstractResolver { |
||||
@Override |
||||
public SimpleDataModel parse(Object data, String others) { |
||||
SimpleDataModel dataModel = new SimpleDataModel(); |
||||
List<Object[]> datas = new ArrayList<>(); |
||||
List<String> columns = new ArrayList<>(); |
||||
JSONObject param = new JSONObject(others); |
||||
String id = StringUtils.EMPTY; |
||||
if (!param.has("data") || StringUtils.isBlank(param.getString("data"))) { |
||||
FineLoggerFactory.getLogger().error("data is not null"); |
||||
return null; |
||||
} |
||||
if (param.has("id") && StringUtils.isNotBlank(param.getString("id"))) { |
||||
id = param.getString("id"); |
||||
} |
||||
List res = JsonPath.read(data.toString(), param.getString("data")); |
||||
|
||||
if (res instanceof List) { |
||||
List<Map> list = (List<Map>) res; |
||||
if (columns.isEmpty()) { |
||||
for (Map map : list) { |
||||
if (map.keySet().size() > columns.size()) { |
||||
columns = new ArrayList(map.keySet()); |
||||
} |
||||
} |
||||
} |
||||
for (Map map : list) { |
||||
Object[] row = new Object[columns.size()]; |
||||
Iterator<String> it = columns.iterator(); |
||||
int i = 0; |
||||
while (it.hasNext()) { |
||||
row[i] = map.get(it.next()); |
||||
i++; |
||||
} |
||||
datas.add(row); |
||||
} |
||||
|
||||
} else if (res instanceof Map) { |
||||
Map map = (Map) res; |
||||
if (columns.isEmpty()) { |
||||
columns = new ArrayList(map.keySet()); |
||||
} |
||||
Object[] row = new Object[columns.size()]; |
||||
Iterator<String> it = columns.iterator(); |
||||
int i = 0; |
||||
while (it.hasNext()) { |
||||
row[i] = map.get(it.next()); |
||||
i++; |
||||
} |
||||
datas.add(row); |
||||
} else { |
||||
if (columns.isEmpty()) { |
||||
columns.add("data"); |
||||
} |
||||
datas.add(new Object[]{res}); |
||||
} |
||||
dataModel.setCols(DataUtil.translate(columns, param.getBoolean("translate"))); |
||||
|
||||
if (StringUtils.isBlank(id) || StringUtils.isBlank(param.getString("name")) || StringUtils.isBlank("parent")) { |
||||
dataModel.setDatas(datas); |
||||
} else { |
||||
if (columns.indexOf(param.getString("name")) == -1 || columns.indexOf(param.getString("parent")) == -1) { |
||||
dataModel.setDatas(datas); |
||||
} else { |
||||
List<Object[]> find = new ArrayList<>(); |
||||
int nameIndex = columns.indexOf(param.getString("name")); |
||||
int parentIndex = columns.indexOf(param.getString("parent")); |
||||
//生成map方便检索数据
|
||||
Map<String, Object[]> map = new HashMap<>(); |
||||
for (int i = 0; i < datas.size(); i++) { |
||||
Object[] row = datas.get(i); |
||||
map.put(row[nameIndex].toString(), row); |
||||
} |
||||
//String tmp = id;
|
||||
Set<String> ids = new HashSet<>(); |
||||
for (int i = 0; i < id.split(",").length; i++) { |
||||
String tmp = id.split(",")[i]; |
||||
while (map.containsKey(tmp)) { |
||||
if(!ids.contains(tmp)){ |
||||
Object[] row = map.get(tmp); |
||||
find.add(row); |
||||
ids.add(tmp); |
||||
tmp = row[parentIndex] == null?"":row[parentIndex].toString(); |
||||
}else { |
||||
tmp = StringUtils.EMPTY; |
||||
} |
||||
} |
||||
} |
||||
|
||||
dataModel.setDatas(find); |
||||
} |
||||
} |
||||
return DataUtil.sort(dataModel,param.getString("sort")); |
||||
} |
||||
|
||||
|
||||
@Override |
||||
public String getName() { |
||||
return "OpenApi树查找器"; |
||||
} |
||||
|
||||
@Override |
||||
public String getDefaultConfig() { |
||||
return "{\n" + |
||||
" \"data\":\"$.data\",\n" + |
||||
" \"id\":\"\",\n" + |
||||
" \"name\":\"dn\",\n" + |
||||
" \"parent\":\"parentDn\",\n" + |
||||
" \"sort\":\"\",\n" + |
||||
" \"translate\":\"false\",\n" + |
||||
"}"; |
||||
} |
||||
} |
@ -0,0 +1,99 @@
|
||||
package com.fr.plugin.xxxxx.factory.resolver; |
||||
|
||||
import com.fr.json.JSONObject; |
||||
import com.fr.log.FineLoggerFactory; |
||||
import com.fr.plugin.xxxxx.factory.util.DataUtil; |
||||
import com.fr.stable.StringUtils; |
||||
import com.jayway.jsonpath.JsonPath; |
||||
import com.tptj.plugin.hg.impl.AbstractResolver; |
||||
import com.tptj.plugin.hg.stable.SimpleDataModel; |
||||
|
||||
import java.util.ArrayList; |
||||
import java.util.Iterator; |
||||
import java.util.List; |
||||
import java.util.Map; |
||||
|
||||
/** |
||||
* @Author fr.open |
||||
* @Date 2020/12/7 |
||||
* @Description |
||||
**/ |
||||
public class OpenApiResolver extends AbstractResolver { |
||||
@Override |
||||
public SimpleDataModel parse(Object data, String others) { |
||||
SimpleDataModel dataModel = new SimpleDataModel(); |
||||
List<Object[]> datas = new ArrayList<>(); |
||||
List<String> columns = new ArrayList<>(); |
||||
JSONObject param = new JSONObject(others); |
||||
if (!param.has("data") || StringUtils.isBlank(param.getString("data"))) { |
||||
FineLoggerFactory.getLogger().error("data is not null"); |
||||
return null; |
||||
} |
||||
if (param.has("column") && StringUtils.isNotBlank(param.getString("column"))) { |
||||
Map map = JsonPath.read(data.toString(), param.getString("column")); |
||||
Iterator<String> it = map.keySet().iterator(); |
||||
while (it.hasNext()) { |
||||
columns.add(String.valueOf(map.get(it.next()))); |
||||
} |
||||
} |
||||
List res = JsonPath.read(data.toString(), param.getString("data")); |
||||
|
||||
if (res instanceof List) { |
||||
List<Map> list = (List<Map>) res; |
||||
if (columns.isEmpty()) { |
||||
for (Map map : list) { |
||||
if (map.keySet().size() > columns.size()) { |
||||
columns = new ArrayList(map.keySet()); |
||||
} |
||||
} |
||||
} |
||||
for (Map map : list) { |
||||
Object[] row = new Object[columns.size()]; |
||||
Iterator<String> it = map.keySet().iterator(); |
||||
int i = 0; |
||||
while (it.hasNext()) { |
||||
row[i] = map.get(it.next()); |
||||
i++; |
||||
} |
||||
datas.add(row); |
||||
} |
||||
|
||||
} else if (res instanceof Map) { |
||||
Map map = (Map) res; |
||||
if (columns.isEmpty()) { |
||||
columns = new ArrayList(map.keySet()); |
||||
} |
||||
Object[] row = new Object[columns.size()]; |
||||
Iterator<String> it = map.keySet().iterator(); |
||||
int i = 0; |
||||
while (it.hasNext()) { |
||||
row[i] = map.get(it.next()); |
||||
i++; |
||||
} |
||||
datas.add(row); |
||||
} else { |
||||
if (columns.isEmpty()) { |
||||
columns.add("data"); |
||||
} |
||||
datas.add(new Object[]{res}); |
||||
} |
||||
dataModel.setCols(DataUtil.translate(columns, param.getBoolean("translate"))); |
||||
dataModel.setDatas(datas); |
||||
return DataUtil.sort(dataModel,param.getString("sort")); |
||||
} |
||||
|
||||
|
||||
@Override |
||||
public String getName() { |
||||
return "OpenApi解析器"; |
||||
} |
||||
|
||||
@Override |
||||
public String getDefaultConfig() { |
||||
return "{\n" + |
||||
" \"column\":\"$[0]\",\n" + |
||||
" \"data\":\"$[1:]\",\n" + |
||||
" \"translate\":\"false\",\n" + |
||||
"}"; |
||||
} |
||||
} |
@ -0,0 +1,120 @@
|
||||
package com.fr.plugin.xxxxx.factory.util; |
||||
|
||||
import com.fr.general.PropertiesUtils; |
||||
import com.fr.io.utils.ResourceIOUtils; |
||||
import com.fr.json.JSONObject; |
||||
import com.fr.log.FineLoggerFactory; |
||||
import com.fr.plugin.xxxxx.factory.EncodeDBAccessProvider; |
||||
import com.fr.plugin.xxxxx.factory.dao.EncodeDao; |
||||
import com.fr.plugin.xxxxx.factory.entity.XxxxxEncodeEntity; |
||||
import com.fr.stable.StringUtils; |
||||
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 com.tptj.plugin.hg.stable.SimpleDataModel; |
||||
|
||||
import java.util.*; |
||||
|
||||
/** |
||||
* @Author fr.open |
||||
* @Date 2020/12/27 |
||||
* @Description |
||||
**/ |
||||
public class DataUtil { |
||||
|
||||
public static Map<String, Object> parseHeader(JSONObject object) { |
||||
Map<String, Object> map = new HashMap<>(16); |
||||
Iterator<String> it = object.keys(); |
||||
while (it.hasNext()) { |
||||
String key = it.next(); |
||||
if (object.get(key) != null) { |
||||
map.put(key, object.get(key).toString()); |
||||
} |
||||
} |
||||
return map; |
||||
} |
||||
|
||||
public static JSONObject getJSON(String param) { |
||||
try { |
||||
FineLoggerFactory.getLogger().info("parse json string is {}", param); |
||||
return new JSONObject(param); |
||||
} catch (Exception e) { |
||||
FineLoggerFactory.getLogger().error("json配置异常"); |
||||
} |
||||
return JSONObject.EMPTY; |
||||
} |
||||
|
||||
public static SimpleDataModel sort(SimpleDataModel dataModel, String sort) { |
||||
final Integer[] index = {dataModel.getCols().indexOf(sort)}; |
||||
if (index[0] == -1) { |
||||
return dataModel; |
||||
} |
||||
Collections.sort(dataModel.getDatas(), new Comparator<Object[]>() { |
||||
@Override |
||||
public int compare(Object[] o1, Object[] o2) { |
||||
char[] chars1 = (o1[index[0]] == null ? "" : String.valueOf(o1[index[0]])).toCharArray(); |
||||
char[] chars2 = (o2[index[0]] == null ? "" : String.valueOf(o2[index[0]])).toCharArray(); |
||||
int i = 0; |
||||
while (i < chars1.length && i < chars2.length) { |
||||
if (chars1[i] > chars2[i]) { |
||||
return 1; |
||||
} else if (chars1[i] < chars2[i]) { |
||||
return -1; |
||||
} else { |
||||
i++; |
||||
} |
||||
} |
||||
if (i == chars1.length) { //o1到头
|
||||
return -1; |
||||
} |
||||
if (i == chars2.length) { //o2到头
|
||||
return 1; |
||||
} |
||||
return 0; |
||||
} |
||||
}); |
||||
return dataModel; |
||||
} |
||||
|
||||
public static String getProp(String key) { |
||||
try { |
||||
XxxxxEncodeEntity encodeEntity = EncodeDBAccessProvider.getDbAccessor().runDMLAction(new DBAction<XxxxxEncodeEntity>() { |
||||
|
||||
@Override |
||||
public XxxxxEncodeEntity run(DAOContext daoContext) throws Exception { |
||||
return daoContext.getDAO(EncodeDao.class).findOne(QueryFactory.create().addRestriction(RestrictionFactory.eq("prop", key))); |
||||
} |
||||
}); |
||||
if (encodeEntity != null && StringUtils.isNotBlank(encodeEntity.getEncode())) { |
||||
return GCMUtils.decode(encodeEntity.getEncode()); |
||||
} |
||||
} catch (Exception e) { |
||||
FineLoggerFactory.getLogger().error(e.getMessage(), e); |
||||
} |
||||
return PropertiesUtils.getProperties("conf").getProperty(key); |
||||
} |
||||
|
||||
public static List<String> translate(List<String> columns, Boolean translate) { |
||||
if(translate == null || !translate){ |
||||
return columns; |
||||
} |
||||
byte[] bytes = ResourceIOUtils.readBytes("/resources/transfer.json"); |
||||
if (bytes == null) { |
||||
return columns; |
||||
} |
||||
try { |
||||
JSONObject object = new JSONObject(new String(bytes)); |
||||
for (int i = 0; i < columns.size(); i++) { |
||||
String col = columns.get(i); |
||||
if (object.has(col) && StringUtils.isNotBlank(object.getString(col))) { |
||||
columns.set(i, object.getString(col)); |
||||
} |
||||
} |
||||
|
||||
} catch (Exception e) { |
||||
FineLoggerFactory.getLogger().error(e.getMessage(), e); |
||||
} |
||||
return columns; |
||||
} |
||||
} |
@ -0,0 +1,92 @@
|
||||
package com.fr.plugin.xxxxx.factory.util; |
||||
|
||||
import com.fr.general.PropertiesUtils; |
||||
import com.fr.log.FineLoggerFactory; |
||||
import com.fr.stable.StringUtils; |
||||
import com.fr.third.org.apache.commons.codec.binary.Base64; |
||||
|
||||
import javax.crypto.*; |
||||
import javax.crypto.spec.GCMParameterSpec; |
||||
import javax.crypto.spec.SecretKeySpec; |
||||
import java.security.InvalidAlgorithmParameterException; |
||||
import java.security.InvalidKeyException; |
||||
import java.security.NoSuchAlgorithmException; |
||||
|
||||
/** |
||||
* @author ezreal |
||||
* @version 10.0 |
||||
* @date 2021/3/22 |
||||
*/ |
||||
public class GCMUtils { |
||||
|
||||
/*public static void main(String[] args) { |
||||
System.out.println(UUID.randomUUID().toString().replaceAll("-","")); |
||||
System.out.println(encode("fanruan@123","RoKH9Yd101zEfXIz8poYrw==")); |
||||
}*/ |
||||
|
||||
public static String encode(String txt, String keytext) { |
||||
try { |
||||
byte[] bytes = Base64.decodeBase64(keytext); |
||||
SecretKey key = new SecretKeySpec(bytes, "AES"); |
||||
Cipher cipher = Cipher.getInstance("AES/GCM/PKCS5Padding"); |
||||
cipher.init(Cipher.ENCRYPT_MODE, key); |
||||
byte[] iv = cipher.getIV(); |
||||
assert iv.length == 12; |
||||
byte[] encryptData = cipher.doFinal(txt.getBytes()); |
||||
assert encryptData.length == txt.getBytes().length + 16; |
||||
byte[] message = new byte[12 + txt.getBytes().length + 16]; |
||||
System.arraycopy(iv, 0, message, 0, 12); |
||||
System.arraycopy(encryptData, 0, message, 12, encryptData.length); |
||||
return Base64.encodeBase64String(message); |
||||
} catch (NoSuchAlgorithmException e) { |
||||
FineLoggerFactory.getLogger().error(e.getMessage()); |
||||
} catch (NoSuchPaddingException e) { |
||||
FineLoggerFactory.getLogger().error(e.getMessage()); |
||||
} catch (InvalidKeyException e) { |
||||
FineLoggerFactory.getLogger().error(e.getMessage()); |
||||
} catch (IllegalBlockSizeException e) { |
||||
FineLoggerFactory.getLogger().error(e.getMessage()); |
||||
} catch (BadPaddingException e) { |
||||
FineLoggerFactory.getLogger().error(e.getMessage()); |
||||
} |
||||
return StringUtils.EMPTY; |
||||
} |
||||
|
||||
public static String decode(String txt, String keytext) { |
||||
try { |
||||
byte[] bytes = Base64.decodeBase64(keytext); |
||||
SecretKey key = new SecretKeySpec(bytes, "AES"); |
||||
Cipher cipher = Cipher.getInstance("AES/GCM/PKCS5Padding"); |
||||
byte[] message = Base64.decodeBase64(txt); |
||||
if (message.length < 12 + 16) throw new IllegalArgumentException(); |
||||
GCMParameterSpec params = new GCMParameterSpec(128, message, 0, 12); |
||||
cipher.init(Cipher.DECRYPT_MODE, key, params); |
||||
byte[] decryptData = cipher.doFinal(message, 12, message.length - 12); |
||||
return new String(decryptData); |
||||
} catch (NoSuchAlgorithmException e) { |
||||
FineLoggerFactory.getLogger().error(e.getMessage()); |
||||
} catch (NoSuchPaddingException e) { |
||||
FineLoggerFactory.getLogger().error(e.getMessage()); |
||||
} catch (InvalidKeyException e) { |
||||
FineLoggerFactory.getLogger().error(e.getMessage()); |
||||
} catch (InvalidAlgorithmParameterException e) { |
||||
FineLoggerFactory.getLogger().error(e.getMessage()); |
||||
} catch (IllegalBlockSizeException e) { |
||||
FineLoggerFactory.getLogger().error(e.getMessage()); |
||||
} catch (BadPaddingException e) { |
||||
FineLoggerFactory.getLogger().error(e.getMessage()); |
||||
} |
||||
return StringUtils.EMPTY; |
||||
} |
||||
|
||||
public static String decode(String encode) { |
||||
String key = PropertiesUtils.getProperties("conf").getProperty("keytext"); |
||||
return decode(encode,key); |
||||
} |
||||
|
||||
public static String encode(String key) { |
||||
String keytext = PropertiesUtils.getProperties("conf").getProperty("keytext"); |
||||
return encode(key,keytext); |
||||
} |
||||
} |
||||
|
@ -0,0 +1,479 @@
|
||||
package com.fr.plugin.xxxxx.factory.util; |
||||
|
||||
import com.fr.json.JSONObject; |
||||
import com.fr.log.FineLoggerFactory; |
||||
import com.fr.stable.StringUtils; |
||||
import com.fr.third.org.apache.http.HttpResponse; |
||||
import com.fr.third.org.apache.http.HttpStatus; |
||||
import com.fr.third.org.apache.http.NameValuePair; |
||||
import com.fr.third.org.apache.http.client.HttpClient; |
||||
import com.fr.third.org.apache.http.client.entity.UrlEncodedFormEntity; |
||||
import com.fr.third.org.apache.http.client.methods.HttpPost; |
||||
import com.fr.third.org.apache.http.client.methods.HttpPut; |
||||
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.LayeredConnectionSocketFactory; |
||||
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.conn.ssl.SSLContexts; |
||||
import com.fr.third.org.apache.http.conn.ssl.TrustStrategy; |
||||
import com.fr.third.org.apache.http.entity.StringEntity; |
||||
import com.fr.third.org.apache.http.impl.client.CloseableHttpClient; |
||||
import com.fr.third.org.apache.http.impl.client.HttpClientBuilder; |
||||
import com.fr.third.org.apache.http.impl.conn.PoolingHttpClientConnectionManager; |
||||
import com.fr.third.org.apache.http.message.BasicNameValuePair; |
||||
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.KeyManagementException; |
||||
import java.security.KeyStore; |
||||
import java.security.KeyStoreException; |
||||
import java.security.NoSuchAlgorithmException; |
||||
import java.security.cert.CertificateException; |
||||
import java.util.ArrayList; |
||||
import java.util.Iterator; |
||||
import java.util.List; |
||||
import java.util.Map; |
||||
import java.util.stream.Collectors; |
||||
|
||||
/** |
||||
* @author fr.open |
||||
* @date 2019/4/2 |
||||
*/ |
||||
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, Object> param, Map<String, Object> header, String charset) { |
||||
String result = ""; |
||||
BufferedReader in = null; |
||||
String urlNameString = url; |
||||
try { |
||||
if (param != null && !param.isEmpty()) { |
||||
urlNameString += "?"; |
||||
urlNameString += param.entrySet() |
||||
.stream() |
||||
.map(entry -> entry.getKey() + "=" + entry.getValue().toString()) |
||||
.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, Object>> it = header.entrySet().iterator(); |
||||
while (it.hasNext()) { |
||||
Map.Entry<String, Object> entry = it.next(); |
||||
System.out.println(entry.getKey() + ":::" + entry.getValue()); |
||||
connection.setRequestProperty(entry.getKey(), entry.getValue().toString()); |
||||
} |
||||
} |
||||
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(); |
||||
if(connection.getResponseCode() == 200){ |
||||
// 定义 BufferedReader输入流来读取URL的响应,设置utf8防止中文乱码
|
||||
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), charset == null ? "utf-8" : charset)); |
||||
String line; |
||||
while ((line = in.readLine()) != null) { |
||||
result += line; |
||||
} |
||||
if (in != null) { |
||||
in.close(); |
||||
} |
||||
}else { |
||||
in = new BufferedReader(new InputStreamReader(connection.getErrorStream(), charset == null ? "utf-8" : charset)); |
||||
String line; |
||||
while ((line = in.readLine()) != null) { |
||||
result += line; |
||||
} |
||||
if (in != null) { |
||||
in.close(); |
||||
} |
||||
FineLoggerFactory.getLogger().error("Http post form code is {},message is {}",connection.getResponseCode(),result); |
||||
return StringUtils.EMPTY; |
||||
} |
||||
|
||||
} 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().error("content data: {}", body.toString()); |
||||
FineLoggerFactory.getLogger().error("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 doJSONPost(String url, Map<String, Object> header, JSONObject json, Map<String, Object> param, String chartset) { |
||||
HttpClient client = getHttpsClient(); |
||||
/*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(); |
||||
}*/ |
||||
if (param != null && !param.isEmpty()) { |
||||
url += "?"; |
||||
url += param.entrySet() |
||||
.stream() |
||||
.map(entry -> entry.getKey() + "=" + entry.getValue()) |
||||
.collect(Collectors.joining("&")); |
||||
} |
||||
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, v.toString()); |
||||
}); |
||||
} |
||||
try { |
||||
StringEntity s = new StringEntity(json.toString(), chartset == null ? "UTF-8" : chartset); |
||||
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; |
||||
} else { |
||||
FineLoggerFactory.getLogger().error("Http post form code is {},message is {}", res.getStatusLine().getStatusCode(), EntityUtils.toString(res.getEntity())); |
||||
} |
||||
} catch (Exception e) { |
||||
FineLoggerFactory.getLogger().error(e.getMessage(), e); |
||||
} |
||||
return null; |
||||
} |
||||
|
||||
public static String doJSONPut(String url, Map<String, Object> header, JSONObject json, Map<String, Object> param, String chartset) { |
||||
HttpClient client = getHttpsClient(); |
||||
/*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(); |
||||
}*/ |
||||
if (param != null && !param.isEmpty()) { |
||||
url += "?"; |
||||
url += param.entrySet() |
||||
.stream() |
||||
.map(entry -> entry.getKey() + "=" + entry.getValue()) |
||||
.collect(Collectors.joining("&")); |
||||
} |
||||
HttpPut post = new HttpPut(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, v.toString()); |
||||
}); |
||||
} |
||||
try { |
||||
StringEntity s = new StringEntity(json.toString(), chartset == null ? "UTF-8" : chartset); |
||||
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; |
||||
} else { |
||||
FineLoggerFactory.getLogger().error("Http post form code is {},message is {}", res.getStatusLine().getStatusCode(), EntityUtils.toString(res.getEntity())); |
||||
} |
||||
} catch (Exception e) { |
||||
FineLoggerFactory.getLogger().error(e.getMessage(), e); |
||||
} |
||||
return null; |
||||
} |
||||
|
||||
|
||||
public static String doFormPost(String url,Map<String, Object> header, Map<String, Object> map, String chartset) { |
||||
//声明返回结果
|
||||
String result = ""; |
||||
UrlEncodedFormEntity entity = null; |
||||
HttpResponse httpResponse = null; |
||||
HttpClient httpClient = null; |
||||
try { |
||||
// 创建连接
|
||||
httpClient = getHttpsClient(); |
||||
; |
||||
/*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); |
||||
httpClient = HttpClients.custom().setConnectionManager(connManager).build(); |
||||
}*/ |
||||
// 设置请求头和报文
|
||||
HttpPost httpPost = new HttpPost(url); |
||||
if (header != null) { |
||||
header.forEach((k, v) -> { |
||||
httpPost.setHeader(k, v.toString()); |
||||
}); |
||||
} |
||||
//设置参数
|
||||
List<NameValuePair> list = new ArrayList<NameValuePair>(); |
||||
Iterator iterator = map.entrySet().iterator(); |
||||
while (iterator.hasNext()) { |
||||
Map.Entry<String, String> elem = (Map.Entry<String, String>) iterator.next(); |
||||
list.add(new BasicNameValuePair(elem.getKey(), elem.getValue())); |
||||
} |
||||
entity = new UrlEncodedFormEntity(list, chartset == null ? "UTF-8" : chartset); |
||||
httpPost.setEntity(entity); |
||||
//执行发送,获取相应结果
|
||||
httpResponse = httpClient.execute(httpPost); |
||||
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { |
||||
result = EntityUtils.toString(httpResponse.getEntity()); |
||||
} else { |
||||
FineLoggerFactory.getLogger().error("Http post form code is {},message is {}", httpResponse.getStatusLine().getStatusCode(), EntityUtils.toString(httpResponse.getEntity())); |
||||
} |
||||
} catch (Exception e) { |
||||
FineLoggerFactory.getLogger().error(e.getMessage(), e); |
||||
} |
||||
return result; |
||||
|
||||
} |
||||
|
||||
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("TLSv1.2"); |
||||
|
||||
// 实现一个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; |
||||
} |
||||
|
||||
private static CloseableHttpClient getHttpsClient() { |
||||
RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.<ConnectionSocketFactory>create(); |
||||
ConnectionSocketFactory plainSF = new PlainConnectionSocketFactory(); |
||||
registryBuilder.register("http", plainSF); |
||||
// 指定信任密钥存储对象和连接套接字工厂
|
||||
try { |
||||
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); |
||||
// 信任任何链接
|
||||
TrustStrategy anyTrustStrategy = new TrustStrategy() { |
||||
|
||||
@Override |
||||
public boolean isTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException { |
||||
// TODO Auto-generated method stub
|
||||
return true; |
||||
} |
||||
}; |
||||
SSLContext sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, anyTrustStrategy).build(); |
||||
LayeredConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); |
||||
registryBuilder.register("https", sslSF); |
||||
} catch (KeyStoreException e) { |
||||
throw new RuntimeException(e); |
||||
} catch (KeyManagementException e) { |
||||
throw new RuntimeException(e); |
||||
} catch (NoSuchAlgorithmException e) { |
||||
throw new RuntimeException(e); |
||||
} |
||||
Registry<ConnectionSocketFactory> registry = registryBuilder.build(); |
||||
// 设置连接管理器
|
||||
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry); |
||||
// 构建客户端
|
||||
return HttpClientBuilder.create().setConnectionManager(connManager).build(); |
||||
|
||||
} |
||||
} |
@ -0,0 +1,68 @@
|
||||
package com.fr.plugin.xxxxx.factory.util; |
||||
|
||||
import com.fr.json.JSONObject; |
||||
import com.fr.log.FineLoggerFactory; |
||||
import com.fr.plugin.xxxxx.factory.entity.Token; |
||||
import com.fr.stable.StringUtils; |
||||
|
||||
import java.time.Instant; |
||||
import java.util.HashMap; |
||||
import java.util.Map; |
||||
|
||||
/** |
||||
* @Author fr.open |
||||
* @Date 2021/2/2 |
||||
* @Description |
||||
**/ |
||||
public class TokenFactory { |
||||
|
||||
private static Token token; |
||||
|
||||
private static TokenFactory instance; |
||||
|
||||
private TokenFactory() { |
||||
|
||||
} |
||||
|
||||
public static TokenFactory getInstance() { |
||||
if (instance == null) { |
||||
instance = new TokenFactory(); |
||||
} |
||||
return instance; |
||||
} |
||||
|
||||
public static String getToken(String tokenUrl, String userid, String value) { |
||||
String token = getTempToken(); |
||||
if (StringUtils.isNotBlank(token)) { |
||||
return token; |
||||
} |
||||
return refreshToken(tokenUrl, userid, value); |
||||
|
||||
} |
||||
|
||||
private static String getTempToken() { |
||||
if (token == null) { |
||||
return null; |
||||
} |
||||
if (token.getTimeout() < System.currentTimeMillis()) { |
||||
return null; |
||||
} |
||||
return token.getToken(); |
||||
} |
||||
|
||||
private static String refreshToken(String tokenUrl, String userid, String value) { |
||||
JSONObject object = JSONObject.create().put("userid", userid).put("value", value); |
||||
/*FineLoggerFactory.getLogger().info("get token param is {}", object);*/ |
||||
Map<String, Object> header = new HashMap<>(); |
||||
header.put("Accept", "application/json"); |
||||
header.put("Content-Type", "application/json;charset=UTF-8"); |
||||
String res = HttpUtil.doJSONPut(tokenUrl, header, object, null, null); |
||||
FineLoggerFactory.getLogger().info("get token res is {} by url {}", res, tokenUrl); |
||||
JSONObject resObj = new JSONObject(res); |
||||
if (resObj.containsKey("data") && StringUtils.isNotBlank("data")) { |
||||
token = new Token(resObj.getString("data"), Instant.now().plusSeconds(28 * 60).toEpochMilli()); |
||||
return resObj.getString("data"); |
||||
} |
||||
return StringUtils.EMPTY; |
||||
} |
||||
} |
Loading…
Reference in new issue