Browse Source

提交开源任务材料

10.0
LAPTOP-SB56SG4Q\86185 3 years ago
parent
commit
bf846aa45e
  1. 5
      README.md
  2. 39
      plugin.xml
  3. 9
      src/main/java/com/fr/plugin/xxxx/xxxx/menu/Constants.java
  4. 18
      src/main/java/com/fr/plugin/xxxx/xxxx/menu/CustomLogInOutEventProvider.java
  5. 228
      src/main/java/com/fr/plugin/xxxx/xxxx/menu/GlobalFilter.java
  6. 21
      src/main/java/com/fr/plugin/xxxx/xxxx/menu/PluginLifecycleMonitor.java
  7. 84
      src/main/java/com/fr/plugin/xxxx/xxxx/menu/ResponseWrapperImpl.java
  8. 34
      src/main/java/com/fr/plugin/xxxx/xxxx/menu/bean/Token.java
  9. 158
      src/main/java/com/fr/plugin/xxxx/xxxx/menu/log/MyLogCacheMetric.java
  10. 480
      src/main/java/com/fr/plugin/xxxx/xxxx/menu/util/HttpUtil.java
  11. 68
      src/main/java/com/fr/plugin/xxxx/xxxx/menu/util/TokenFactory.java

5
README.md

@ -1,3 +1,6 @@
# open-JSD-8997
JSD-8997 根据参数或其他请求条件控制决策平台的报表目录展现
JSD-8997 根据参数或其他请求条件控制决策平台的报表目录展现\
免责说明:该源码为第三方爱好者提供,不保证源码和方案的可靠性,也不提供任何形式的源码教学指导和协助!\
仅作为开发者学习参考使用!禁止用于任何商业用途!\
为保护开发者隐私,开发者信息已隐去!若原开发者希望公开自己的信息,可联系hugh处理。

39
plugin.xml

@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<plugin>
<id>com.fr.plugin.xxxx.xxxx.menu</id>
<main-package>com.fr.plugin.xxxx.xxxx.menu</main-package>
<name><![CDATA[决策平台菜单过滤]]></name>
<active>yes</active>
<version>1.18</version>
<env-version>10.0</env-version>
<jartime>2018-07-31</jartime>
<vendor>fr.open</vendor>
<description><![CDATA[决策平台菜单过滤]]></description>
<change-notes><![CDATA[
[2021-11-10]【1.0】初始化插件。<br/>
[2021-11-13]【1.1】过滤逻辑修改。<br/>
[2021-11-13]【1.2】增加一个报表。<br/>
[2021-11-13]【1.3】增加登出调用。<br/>
[2021-11-15]【1.4】增加保存日志拦截。<br/>
[2021-11-18]【1.5】修改日志注入机制。<br/>
[2021-11-19]【1.6】增加导出日志注入。<br/>
[2021-11-21]【1.7】增加导出日志类型转换。<br/>
[2021-11-21]【1.8】增加导出日志result类型转换。<br/>
[2021-11-21]【1.9】打印导出日志。<br/>
[2021-11-23]【1.10】日志推送逻辑修改。<br/>
[2021-11-26]【1.11】增加特定报表隐藏。<br/>
[2021-11-29]【1.12】增加日志详细输出和隐藏根目录菜单。<br/>
[2021-11-29]【1.13】自定义报表和定制报表不隐藏。<br/>
[2021-11-29]【1.14】自定义报表和定制报表不隐藏。<br/>
[2021-11-30]【1.15】指定范围报表目录隐藏。<br/>
[2021-11-30]【1.16】问题修改。<br/>
[2021-11-30]【1.17】问题修改。<br/>
[2021-11-30]【1.18】问题修改。<br/>
]]></change-notes>
<lifecycle-monitor class="com.fr.plugin.xxxx.xxxx.menu.PluginLifecycleMonitor"/>
<extra-decision>
<LogInOutEventProvider class="com.fr.plugin.xxxx.xxxx.menu.CustomLogInOutEventProvider"/>
<GlobalRequestFilterProvider class="com.fr.plugin.xxxx.xxxx.menu.GlobalFilter"/>
</extra-decision>
<function-recorder class="com.fr.plugin.xxxx.xxxx.menu.GlobalFilter"/>
</plugin>

9
src/main/java/com/fr/plugin/xxxx/xxxx/menu/Constants.java

@ -0,0 +1,9 @@
package com.fr.plugin.xxxx.xxxx.menu;
/**
* @author fr.open
* @date 2020/5/14
*/
public class Constants {
public static final String PLUGIN_ID = "com.fr.plugin.xxxx.xxxx.menu";
}

18
src/main/java/com/fr/plugin/xxxx/xxxx/menu/CustomLogInOutEventProvider.java

@ -0,0 +1,18 @@
package com.fr.plugin.xxxx.xxxx.menu;
import com.fr.decision.fun.impl.AbstractLogInOutEventProvider;
import com.fr.decision.webservice.login.LogInOutResultInfo;
import com.fr.general.PropertiesUtils;
/**
* @Author fr.open
* @Date 2020/11/13
* @Description
**/
public class CustomLogInOutEventProvider extends AbstractLogInOutEventProvider {
@Override
public String logoutAction(LogInOutResultInfo result) {
return PropertiesUtils.getProperties("sso").getProperty("logout");
}
}

228
src/main/java/com/fr/plugin/xxxx/xxxx/menu/GlobalFilter.java

@ -0,0 +1,228 @@
package com.fr.plugin.xxxx.xxxx.menu;
import com.fr.base.PropertiesUtils;
import com.fr.decision.fun.impl.AbstractGlobalRequestFilterProvider;
import com.fr.decision.webservice.v10.config.ConfigService;
import com.fr.intelli.record.Focus;
import com.fr.intelli.record.MetricRegistry;
import com.fr.intelli.record.Original;
import com.fr.json.JSONArray;
import com.fr.json.JSONObject;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.context.PluginContexts;
import com.fr.plugin.xxxx.xxxx.menu.log.MyLogCacheMetric;
import com.fr.plugin.xxxx.xxxx.menu.util.HttpUtil;
import com.fr.plugin.xxxx.xxxx.menu.util.TokenFactory;
import com.fr.plugin.transform.FunctionRecorder;
import com.fr.record.analyzer.EnableMetrics;
import com.fr.stable.StringUtils;
import com.fr.stable.fun.Authorize;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
/**
* @Author fr.open
* @Date 2021/10/29
* @Description
**/
@FunctionRecorder
@Authorize(callSignKey = Constants.PLUGIN_ID)
@EnableMetrics
public class GlobalFilter extends AbstractGlobalRequestFilterProvider {
private static final String MENU_URI = "/rest/openapi/security/v3/system/service-capability";
private static final Map<String, String> REAL_MAP;
private MyLogCacheMetric cacheMetric = new MyLogCacheMetric();
static {
REAL_MAP = new HashMap<>();
REAL_MAP.put("AXXX", "capacity|asset");
REAL_MAP.put("XXXX", "capacity|asset");
REAL_MAP.put("XXXX", "capacity|asset");
REAL_MAP.put("XXXX", "capacity|asset");
REAL_MAP.put("XXXX", "capacity|asset");
REAL_MAP.put("XXXX", "capacity|asset");
REAL_MAP.put("XXXX", "capacity|asset");
REAL_MAP.put("XXXX", "capacity|asset");
REAL_MAP.put("XXXX", "capacity|asset");
REAL_MAP.put("XXXX", "capacity,asset");
REAL_MAP.put("XXXX", "capacity|asset");
}
private static final String[] menu = new String[]{"XXXX","XXXX","XXXX","XXXX","XXXX","XXXX"};
@Override
public void init(FilterConfig filterConfig) {
super.init(filterConfig);
MetricRegistry.register(cacheMetric);
}
@Override
public String filterName() {
return "global";
}
@Override
@Focus(id = Constants.PLUGIN_ID, text = "XXXX权限过滤", source = Original.PLUGIN)
public String[] urlPatterns() {
if (PluginContexts.currentContext().isAvailable()) {
String servletPathName = "decision";
try {
servletPathName = ConfigService.getInstance().getBasicParam().getServletPathName();
} catch (Exception e) {
FineLoggerFactory.getLogger().error(e.getMessage(), e);
}
return new String[]{
"/" + servletPathName + "/v10/view/entry/tree",
};
} else {
return new String[0];
}
}
@Override
public void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain filterChain) {
try {
ResponseWrapperImpl responseWrapper = new ResponseWrapperImpl(res);
filterChain.doFilter(req, responseWrapper);
byte[] dataStream = responseWrapper.getDataStream();
//JSONObject object = new JSONObject(readJsonFile("/Users/hujian/Desktop/1.json"));
JSONObject object = new JSONObject(new String(dataStream));
JSONArray array = new JSONArray();
JSONArray resArray = new JSONArray();
JSONObject map = getMenuAuth();
Set<String> set = new HashSet();
Set<String> level1 = new HashSet<>();
Map<String, Integer> children = new HashMap<>();
for (int i = 0; i < object.getJSONArray("data").size(); i++) {
JSONObject data = object.getJSONArray("data").getJSONObject(i);
String text = data.getString("text");
if (StringUtils.equals("decision-directory-root", data.getString("pId"))
&& Stream.of(menu).anyMatch(text::equals)
) {
level1.add(data.getString("id"));
children.put(data.getString("id"),0);
}
if (StringUtils.equals(text, "自定义报表") || StringUtils.equals(text, "定制报表")) {
set.add(data.getString("id"));
}
if (!REAL_MAP.containsKey(text)) {
array.add(data);
continue;
}
if (checkAuth(REAL_MAP.get(text), map)) {
array.add(data);
}
}
FineLoggerFactory.getLogger().info("level1 menu is {}",level1);
FineLoggerFactory.getLogger().info("get filter size is {}", set);
for (int i = 0; i < array.size(); i++) {
JSONObject data = array.getJSONObject(i);
//只处理俩个特定的一级节点
if (set.contains(data.getString("pId"))) {
//只有包含这俩的不处理,其他不展示
if ((data.getString("text").endsWith("流程图") || data.getString("text").endsWith("列表"))) {
resArray.add(data);
}
} else {
//非特定的不做处理
resArray.add(data);
}
}
Map<String, JSONObject> dataMap = new HashMap<>();
for (int i = 0; i < resArray.size(); i++) {
JSONObject data = resArray.getJSONObject(i);
//只处理俩个特定的一级节点
if (level1.contains(data.getString("pId"))) {
Integer count = children.get(data.getString("pId"));
count = count == null?0:count;
children.put(data.getString("pId"),count+1);
}
dataMap.put(data.getString("id"),data);
}
FineLoggerFactory.getLogger().info("children res {}",children);
children.forEach((k,v) -> {
if(v == 0){
JSONObject remove = dataMap.remove(k);
FineLoggerFactory.getLogger().info("remove menu is {}",remove.getString("text"));
}
});
FineLoggerFactory.getLogger().info("check auth menu result is {}", dataMap.values());
object.put("data", new JSONArray(dataMap.values()));
res.getOutputStream().write(object.toString().getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
FineLoggerFactory.getLogger().error(e.getMessage(), e);
} catch (ServletException e) {
FineLoggerFactory.getLogger().error(e.getMessage(), e);
}
}
private boolean checkAuth(String text, JSONObject map) {
if (text.contains("|")) {
Boolean[] flag = new Boolean[]{false};
Stream.of(text.split("\\|")).forEach(e -> flag[0] = flag[0] || map.getBoolean(e));
return flag[0];
} else if (text.contains(",")) {
Boolean[] flag = new Boolean[]{true};
Stream.of(text.split(",")).forEach(e -> flag[0] = flag[0] && map.getBoolean(e));
return flag[0];
}
return map.getBoolean(text);
}
private JSONObject getMenuAuth() {
String tokenUrl = PropertiesUtils.getProperties("conf").getProperty("tokenUrl");
String userid = PropertiesUtils.getProperties("conf").getProperty("userid");
String value = PropertiesUtils.getProperties("conf").getProperty("value");
String prefix = PropertiesUtils.getProperties("conf").getProperty("prefix");
String token = TokenFactory.getToken(tokenUrl, userid, value);
FineLoggerFactory.getLogger().info("get token is {}", token);
Map<String, Object> headerMap = new HashMap();
headerMap.put("openid", token);
String res = HttpUtil.sendGet(prefix + MENU_URI, null, headerMap, null);
FineLoggerFactory.getLogger().info("get menu auth res is {}", res);
JSONObject object = new JSONObject(res);
return object.getJSONObject("data");
}
public static String readJsonFile(String fileName) {
String jsonStr = "";
try {
File jsonFile = new File(fileName);
FileReader fileReader = new FileReader(jsonFile);
Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
fileReader.close();
reader.close();
jsonStr = sb.toString();
return jsonStr;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/*public static void main(String[] args) {
new GlobalFilter().doFilter(null,null,null);
}*/
}

21
src/main/java/com/fr/plugin/xxxx/xxxx/menu/PluginLifecycleMonitor.java

@ -0,0 +1,21 @@
package com.fr.plugin.xxxx.xxxx.menu;
import com.fr.plugin.context.PluginContext;
import com.fr.plugin.observer.inner.AbstractPluginLifecycleMonitor;
/**
* @Author fr.open
* @Date 2020/9/15
* @Description
**/
public class PluginLifecycleMonitor extends AbstractPluginLifecycleMonitor {
@Override
public void afterRun(PluginContext pluginContext) {
//MetricRegistry.register(new MyLogCacheMetric());
}
@Override
public void beforeStop(PluginContext pluginContext) {
}
}

84
src/main/java/com/fr/plugin/xxxx/xxxx/menu/ResponseWrapperImpl.java

@ -0,0 +1,84 @@
package com.fr.plugin.xxxx.xxxx.menu;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* @author fr.open
* @Date 2021/8/1
*/
public class ResponseWrapperImpl extends HttpServletResponseWrapper {
ByteArrayOutputStream output;
FilterServletOutputStream filterOutput;
public ResponseWrapperImpl(HttpServletResponse response) {
super(response);
output = new ByteArrayOutputStream();
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
if (filterOutput == null) {
filterOutput = new FilterServletOutputStream(output);
}
return filterOutput;
}
public void setContent(ByteArrayOutputStream output){
this.output = output;
this.filterOutput = null;
}
public void clear(){
output = new ByteArrayOutputStream();
filterOutput = new FilterServletOutputStream(output);
}
public ByteArrayOutputStream getOut(){
return output;
}
public byte[] getDataStream() {
return output.toByteArray();
}
class FilterServletOutputStream extends ServletOutputStream {
DataOutputStream output;
public FilterServletOutputStream(OutputStream output) {
this.output = new DataOutputStream(output);
}
@Override
public void write(int arg0) throws IOException {
output.write(arg0);
}
@Override
public void write(byte[] arg0, int arg1, int arg2) throws IOException {
output.write(arg0, arg1, arg2);
}
@Override
public void write(byte[] arg0) throws IOException {
output.write(arg0);
System.out.printf("");
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setWriteListener(WriteListener writeListener) {
}
}
}

34
src/main/java/com/fr/plugin/xxxx/xxxx/menu/bean/Token.java

@ -0,0 +1,34 @@
package com.fr.plugin.xxxx.xxxx.menu.bean;
/**
* @Author fr.open
* @Date 2021/11/11
* @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;
}
}

158
src/main/java/com/fr/plugin/xxxx/xxxx/menu/log/MyLogCacheMetric.java

@ -0,0 +1,158 @@
package com.fr.plugin.xxxx.xxxx.menu.log;
import com.fr.base.PropertiesUtils;
import com.fr.decision.log.ExecuteMessage;
import com.fr.decision.record.OperateMessage;
import com.fr.intelli.record.scene.impl.LogCacheMetric;
import com.fr.json.JSONObject;
import com.fr.locale.InterProvider;
import com.fr.locale.InterProviderFactory;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.holger.hwny.menu.util.HttpUtil;
import com.fr.plugin.holger.hwny.menu.util.TokenFactory;
import com.fr.stable.StringUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
/**
* @Author fr.open
* @Date 2021/11/14
* @Description
**/
public class MyLogCacheMetric extends LogCacheMetric {
private static final String[] ARRAY = new String[]{"page","view","write","form","write_plus","page_plus"};
private static final String LOG_API = "/rest/openapi/security/v3/log/op-logs";
private static final String system = "op-report-system";
private static final Map<Integer,String> exportType;
static {
exportType = new HashMap<>();
exportType.put(0,"分页预览");
exportType.put(1,"在线分析");
exportType.put(2,"填报预览");
exportType.put(3,"决策报表预览");
exportType.put(4,"行式引擎");
exportType.put(5,"在线编辑");
exportType.put(7,"新引擎预览");
exportType.put(10,"Excel 分页导出");
exportType.put(11,"Excel 原样导出");
exportType.put(12,"Excel 整页导出");
exportType.put(13,"Excel 分页分 sheet 导出");
exportType.put(14,"PDF 导出");
exportType.put(15,"Word 导出");
exportType.put(16,"SVG 导出");
exportType.put(17,"CSV 导出");
exportType.put(18,"文本导出");
exportType.put(19,"JPG 图片导出");
exportType.put(20,"PNG 图片导出");
exportType.put(21,"GIF 图片导出");
exportType.put(22,"BMP 图片导出");
exportType.put(23,"WBMP 图片导出");
exportType.put(24,"内置数据集导出模板");
exportType.put(25,"HTML 导出");
exportType.put(26,"填报 HTML 导出");
exportType.put(27,"BI 导出 Excel");
exportType.put(30,"Flash 打印");
exportType.put(31,"PDF 打印");
exportType.put(32,"Applet 打印");
exportType.put(33,"零客户端打印");
exportType.put(34,"本地软件打印");
}
@Override
public void submit(Object o) {
super.submit(o);
if (o instanceof OperateMessage) {
OperateMessage message = (OperateMessage) o;
sendMessage(coverJSONByMessage(message));
}
if (o instanceof ExecuteMessage) {
ExecuteMessage message = (ExecuteMessage) o;
sendMessage(coverJSONByExportMessage(message));
}
}
private JSONObject coverJSONByExportMessage(ExecuteMessage message) {
FineLoggerFactory.getLogger().info("export message is {}",JSONObject.mapFrom(message));
JSONObject object = new JSONObject();
object.put("userName", message.getUsername());
object.put("templateId", system);
String type = exportType.get(message.getType());
String detail = String.format("报表%s执行%s操作", message.getTemplate(), type);
object.put("detail", detail);
FineLoggerFactory.getLogger().info("get export detail is {}",detail);
if(Stream.of(ARRAY).anyMatch(type::contains)){
object.put("result", message.getComplete() == 1 ? "SUCCESSFUL" : "FAILURE");
}else {
object.put("result","SUCCESSFUL");
}
object.put("terminal", message.getIp());
return object;
}
private void sendMessage(JSONObject object) {
String tokenUrl = PropertiesUtils.getProperties("conf").getProperty("tokenUrl");
String userid = PropertiesUtils.getProperties("conf").getProperty("userid");
String value = PropertiesUtils.getProperties("conf").getProperty("value");
String prefix = PropertiesUtils.getProperties("conf").getProperty("prefix");
String token = TokenFactory.getToken(tokenUrl, userid, value);
FineLoggerFactory.getLogger().info("get token is {}", token);
Map<String, Object> headerMap = new HashMap();
headerMap.put("openid", token);
FineLoggerFactory.getLogger().info("url {} send data is {}", prefix + LOG_API, object);
String res = HttpUtil.doJSONPost(prefix + LOG_API, headerMap, object, null, null);
FineLoggerFactory.getLogger().info("save log res is {}", res);
}
@Override
public void submit(List<Object> list) {
super.submit(list);
if (list != null && !list.isEmpty()) {
for (int i = 0; i < list.size(); i++) {
Object o = list.get(i);
if (o instanceof OperateMessage) {
OperateMessage message = (OperateMessage) o;
sendMessage(coverJSONByMessage(message));
}
if (o instanceof ExecuteMessage) {
ExecuteMessage message = (ExecuteMessage) o;
sendMessage(coverJSONByExportMessage(message));
}
}
}
}
private JSONObject coverJSONByMessage(OperateMessage message) {
JSONObject object = new JSONObject();
object.put("userName", message.getUsername());
object.put("templateId", system);
object.put("result", message.getStatus() > 0 ? "SUCCESSFUL" : "FAILURE");
InterProvider provider = InterProviderFactory.getProvider();
String detail = String.format("%s模块%s设置项%s执行%s操作", provider.getLocText(message.getType()),
provider.getLocText(message.getItem()),
StringUtils.isBlank(message.getResource())?"":provider.getLocText(message.getResource()),
provider.getLocText(message.getOperate())
);
FineLoggerFactory.getLogger().info("get detail is {}",detail);
object.put("detail", detail);
object.put("terminal", message.getIp());
return object;
}
/* public static void main(String[] args) {
ExecuteMessage message = new ExecuteMessage();
message.setComplete(0);
message.setType(11);
MyLogCacheMetric myLogCacheMetric = new MyLogCacheMetric();
System.out.println(myLogCacheMetric.coverJSONByExportMessage(message));
}*/
}

480
src/main/java/com/fr/plugin/xxxx/xxxx/menu/util/HttpUtil.java

@ -0,0 +1,480 @@
package com.fr.plugin.xxxx.xxxx.menu.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 2021/11/11
* @Description
**/
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();
}
}

68
src/main/java/com/fr/plugin/xxxx/xxxx/menu/util/TokenFactory.java

@ -0,0 +1,68 @@
package com.fr.plugin.xxxx.xxxx.menu.util;
import com.fr.json.JSONObject;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.holger.hwny.menu.bean.Token;
import com.fr.stable.StringUtils;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
/**
* @Author fr.open
* @Date 2021/11/11
* @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…
Cancel
Save