优化netty通信兼容老的HTTP客户端配置
This commit is contained in:
parent
c3eeb50cc6
commit
8d86d19659
|
@ -1,37 +1,38 @@
|
|||
#===============================系统配置=====================================
|
||||
client.verison=3.2
|
||||
server.web.ip=localhost
|
||||
server.web.port=80
|
||||
#===============================netty配置=====================================
|
||||
#netty.model为netty模式开启 例:true false 注意:host.name必须包含netty
|
||||
netty.model=true
|
||||
netty.server.port=7070
|
||||
host.name=nettyClient-lf
|
||||
#================================ 邮件=======================================
|
||||
#smtp邮件IP 例:smtp.qq.com
|
||||
mail.smtp.ip=smtp.qq.com
|
||||
#smtp邮件端口 例:25
|
||||
mail.smtp.port=25
|
||||
#smtp邮件ssl连接开启 例:true false
|
||||
mail.smtp.ssl.enable=false
|
||||
#smtp邮件用户名
|
||||
mail.smtp.username=xxxxx@xx.com
|
||||
#smtp邮件用户密码
|
||||
mail.smtp.password=xxxxx
|
||||
#邮件模板路径
|
||||
mail.freemarker.template=/email_template/
|
||||
#==================向第三方应用推送任务执行结果(JSON)========================
|
||||
#第三方平台推送开关 true打开 false关闭
|
||||
task.push.switch=false
|
||||
#第三方平台推送URL
|
||||
task.push.url=localhost
|
||||
#==================Jenkins API配置========================
|
||||
#jenkins访问地址,示例: http://192.168.100.100:8080/jenkins/
|
||||
jenkins.url=http://localhost
|
||||
#jenkins用户名
|
||||
jenkins.username=test
|
||||
#jenkins密码
|
||||
jenkins.password=test1
|
||||
#==================Web Driver配置========================
|
||||
#是否高亮显示 true打开 false关闭
|
||||
#===============================系统配置=====================================
|
||||
client.verison=3.2
|
||||
client.name=测试客户端
|
||||
server.web.ip=localhost
|
||||
server.web.port=80
|
||||
#===============================netty配置=====================================
|
||||
#netty.model为netty模式开启 例:true false 注意:netty.host必须包含netty
|
||||
netty.model=true
|
||||
netty.server.port=7070
|
||||
netty.host=nettyClient-lf
|
||||
#================================ 邮件=======================================
|
||||
#smtp邮件IP 例:smtp.qq.com
|
||||
mail.smtp.ip=smtp.qq.com
|
||||
#smtp邮件端口 例:25
|
||||
mail.smtp.port=25
|
||||
#smtp邮件ssl连接开启 例:true false
|
||||
mail.smtp.ssl.enable=false
|
||||
#smtp邮件用户名
|
||||
mail.smtp.username=xxxxx@xx.com
|
||||
#smtp邮件用户密码
|
||||
mail.smtp.password=xxxxx
|
||||
#邮件模板路径
|
||||
mail.freemarker.template=/email_template/
|
||||
#==================向第三方应用推送任务执行结果(JSON)========================
|
||||
#第三方平台推送开关 true打开 false关闭
|
||||
task.push.switch=false
|
||||
#第三方平台推送URL
|
||||
task.push.url=localhost
|
||||
#==================Jenkins API配置========================
|
||||
#jenkins访问地址,示例: http://192.168.100.100:8080/jenkins/
|
||||
jenkins.url=http://localhost
|
||||
#jenkins用户名
|
||||
jenkins.username=test
|
||||
#jenkins密码
|
||||
jenkins.password=test1
|
||||
#==================Web Driver配置========================
|
||||
#是否高亮显示 true打开 false关闭
|
||||
webdriver.highlight=false
|
|
@ -1,422 +1,415 @@
|
|||
package luckyclient.driven;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.alibaba.fastjson.JSONException;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.alibaba.fastjson.TypeReference;
|
||||
import com.alibaba.fastjson.parser.Feature;
|
||||
import com.jayway.jsonpath.JsonPath;
|
||||
import com.jayway.jsonpath.PathNotFoundException;
|
||||
|
||||
import luckyclient.utils.Constants;
|
||||
import luckyclient.utils.LogUtil;
|
||||
|
||||
/**
|
||||
* 公用驱动
|
||||
* =================================================================
|
||||
* 这是一个受限制的自由软件!您不能在任何未经允许的前提下对程序代码进行修改和用于商业用途;也不允许对程序代码修改后以任何形式任何目的的再发布。
|
||||
* 为了尊重作者的劳动成果,LuckyFrame关键版权信息严禁篡改 有任何疑问欢迎联系作者讨论。 QQ:1573584944 Seagull
|
||||
* =================================================================
|
||||
* @author Seagull
|
||||
* @date 2019年1月15日
|
||||
*/
|
||||
public class SubString {
|
||||
/**
|
||||
* 截取指定字符串的中间字段
|
||||
*
|
||||
* @param str
|
||||
* @param startstr
|
||||
* @param endstr
|
||||
* @return
|
||||
*/
|
||||
public static String subCentreStr(String str, String startstr, String endstr) {
|
||||
try{
|
||||
int startnum=0;
|
||||
int endnum=str.length();
|
||||
if(!"".equals(startstr)){
|
||||
startnum=str.indexOf(startstr) + startstr.length();
|
||||
}
|
||||
if(!"".equals(endstr)){
|
||||
endnum=str.indexOf(endstr, str.indexOf(startstr) + startstr.length());
|
||||
}
|
||||
String getstr = str.substring(startnum,endnum);
|
||||
return getstr;
|
||||
}catch(Exception e){
|
||||
LogUtil.APP.error("subCentreStr截取字符串出现异常,请检查参数!",e);
|
||||
return "截取字符串出现异常,请检查参数!";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 截取字符串从指定字符开始
|
||||
*
|
||||
* @param str
|
||||
* @param startstr
|
||||
* @return
|
||||
*/
|
||||
public static String subStartStr(String str, String startstr) {
|
||||
try{
|
||||
String getstr = str.substring(str.indexOf(startstr) + startstr.length());
|
||||
return getstr;
|
||||
}catch(Exception e){
|
||||
LogUtil.APP.error("subStartStr截取字符串出现异常,请检查参数!",e);
|
||||
return "截取字符串出现异常,请检查参数!";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 截取字符串到指定字符结束
|
||||
*
|
||||
* @param str
|
||||
* @param startstr
|
||||
* @return
|
||||
*/
|
||||
public static String subEndStr(String str, String endstr) {
|
||||
try{
|
||||
String getstr = str.substring(0, str.indexOf(endstr));
|
||||
return getstr;
|
||||
}catch(Exception e){
|
||||
LogUtil.APP.error("subEndStr截取字符串出现异常,请检查参数!",e);
|
||||
return "截取字符串出现异常,请检查参数!";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过字符串位置截取指定字符串的中间字段
|
||||
*
|
||||
* @param str
|
||||
* @param startstr
|
||||
* @param endstr
|
||||
* @return
|
||||
*/
|
||||
public static String subCentreNum(String str, String startnum, String endnum) {
|
||||
String getstr = "";
|
||||
if("".equals(startnum)){
|
||||
startnum="0";
|
||||
}
|
||||
if("".equals(endnum)){
|
||||
endnum=String.valueOf(str.length());
|
||||
}
|
||||
try{
|
||||
if (isInteger(startnum) && isInteger(endnum)) {
|
||||
int start = Integer.valueOf(startnum);
|
||||
int end = Integer.valueOf(endnum);
|
||||
if (start > end) {
|
||||
getstr = "截取字符串开始位置数字不能大于结束位置数字";
|
||||
} else if (start < 0 || end < 0) {
|
||||
getstr = "截取字符串位置的数字不能小于0";
|
||||
} else if (start > str.length() || end > str.length()) {
|
||||
getstr = "截取字符串位置的数字不能大于字符串本身的长度【" + str.length() + "】";
|
||||
} else {
|
||||
getstr = str.substring(start, end);
|
||||
}
|
||||
} else {
|
||||
getstr = "指定的开始或是结束位置字符不是数字类型,请检查!";
|
||||
}
|
||||
|
||||
return getstr;
|
||||
}catch(Exception e){
|
||||
LogUtil.APP.error("subCentreNum截取字符串出现异常,请检查参数!",e);
|
||||
return "截取字符串出现异常,请检查参数!";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过字符串位置截取字符串从指定字符开始
|
||||
*
|
||||
* @param str
|
||||
* @param startstr
|
||||
* @return
|
||||
*/
|
||||
public static String subStartNum(String str, String startnum) {
|
||||
String getstr = "";
|
||||
try{
|
||||
if (isInteger(startnum)) {
|
||||
int start = Integer.valueOf(startnum);
|
||||
if (start < 0) {
|
||||
getstr = "截取字符串位置的数字不能小于0";
|
||||
} else if (start > str.length()) {
|
||||
getstr = "截取字符串位置的数字不能大于字符串本身的长度【" + str.length() + "】";
|
||||
} else {
|
||||
getstr = str.substring(start);
|
||||
}
|
||||
} else {
|
||||
getstr = "指定的开始位置字符不是数字类型,请检查!";
|
||||
}
|
||||
|
||||
return getstr;
|
||||
}catch(Exception e){
|
||||
LogUtil.APP.error("subStartNum截取字符串出现异常,请检查参数!",e);
|
||||
return "截取字符串出现异常,请检查参数!";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 截取字符串到指定字符结束
|
||||
*
|
||||
* @param str
|
||||
* @param startstr
|
||||
* @return
|
||||
*/
|
||||
public static String subEndNum(String str, String endnum) {
|
||||
String getstr = "";
|
||||
try{
|
||||
if (isInteger(endnum)) {
|
||||
int end = Integer.valueOf(endnum);
|
||||
if (end < 0) {
|
||||
getstr = "截取字符串位置的数字不能小于0";
|
||||
} else if (end > str.length()) {
|
||||
getstr = "截取字符串位置的数字不能大于字符串本身的长度【" + str.length() + "】";
|
||||
} else {
|
||||
getstr = str.substring(0, end);
|
||||
}
|
||||
} else {
|
||||
getstr = "指定的结束位置字符不是数字类型,请检查!";
|
||||
}
|
||||
|
||||
return getstr;
|
||||
}catch(Exception e){
|
||||
LogUtil.APP.error("subEndNum截取字符串出现异常,请检查参数!",e);
|
||||
return "截取字符串出现异常,请检查参数!";
|
||||
}
|
||||
}
|
||||
|
||||
public static String subStrRgex(String str, String rgex, String num) {
|
||||
List<String> list = new ArrayList<String>();
|
||||
try{
|
||||
// 匹配的模式
|
||||
Pattern pattern = Pattern.compile(rgex);
|
||||
Matcher m = pattern.matcher(str);
|
||||
while (m.find()) {
|
||||
// int i = 1;
|
||||
list.add(m.group());
|
||||
// i++;
|
||||
}
|
||||
|
||||
String getstr = "";
|
||||
if (isInteger(num)) {
|
||||
int index = Integer.valueOf(num);
|
||||
if (index < 0) {
|
||||
getstr = "截取字符串索引数字不能小于0";
|
||||
} else if (index > str.length()) {
|
||||
getstr = "截取字符串索引的数字不能大于字符串本身的长度【" + str.length() + "】";
|
||||
} else if (index > list.size()) {
|
||||
getstr = "未能在指定字符串中根据正则式找到匹配的字符串或是指定的索引数字大于能找到的匹配字符串索引量";
|
||||
} else {
|
||||
getstr = list.get(index - 1);
|
||||
}
|
||||
} else {
|
||||
getstr = "指定的索引位置字符不是数字类型,请检查!";
|
||||
}
|
||||
return getstr;
|
||||
}catch(Exception e){
|
||||
LogUtil.APP.error("subStrRgex截取字符串出现异常,请检查参数!",e);
|
||||
return "截取字符串出现异常,请检查参数!";
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isInteger(String str) {
|
||||
String patternStr="^[-\\+]?[\\d]*$";
|
||||
Pattern pattern = Pattern.compile(patternStr);
|
||||
return pattern.matcher(str).matches();
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化返回JSON中Value的值
|
||||
*/
|
||||
private static String JSONVALUE = "【获取JSON KEY中的Value异常】";
|
||||
|
||||
/**
|
||||
* 用于计数KEY的序号
|
||||
*/
|
||||
private static int COUNTER = 1;
|
||||
|
||||
/**
|
||||
* 遍历JSON对象
|
||||
*
|
||||
* @param json
|
||||
* @param key
|
||||
* @param keyindex
|
||||
* @return
|
||||
*/
|
||||
private static JSONObject parseJsonString(String json, String key, int keyindex) {
|
||||
LinkedHashMap<String, Object> jsonMap = JSON.parseObject(json,
|
||||
new TypeReference<LinkedHashMap<String, Object>>() {
|
||||
}, Feature.OrderedField);
|
||||
for (Map.Entry<String, Object> entry : jsonMap.entrySet()) {
|
||||
parseJsonMap(entry, key, keyindex);
|
||||
}
|
||||
return new JSONObject(jsonMap);
|
||||
}
|
||||
|
||||
/**
|
||||
* 遍历后JSON对象中的key以及value
|
||||
*
|
||||
* @param entry
|
||||
* @param key
|
||||
* @param keyindex
|
||||
* @return
|
||||
*/
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
private static Map.Entry<String, Object> parseJsonMap(Map.Entry<String, Object> entry, String key, int keyindex) {
|
||||
// 如果是单个map继续遍历
|
||||
if (entry.getValue() instanceof Map) {
|
||||
LinkedHashMap<String, Object> jsonMap = JSON.parseObject(entry.getValue().toString(),
|
||||
new TypeReference<LinkedHashMap<String, Object>>() {
|
||||
}, Feature.OrderedField);
|
||||
for (Map.Entry<String, Object> entry2 : jsonMap.entrySet()) {
|
||||
parseJsonMap(entry2, key, keyindex);
|
||||
}
|
||||
}
|
||||
// 如果是list就提取出来
|
||||
if (entry.getValue() instanceof List) {
|
||||
List list = (List) entry.getValue();
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
// 如果还有,循环提取
|
||||
//list.set(i, parseJsonString(list.get(i).toString(), key, keyindex));
|
||||
//如何还有,循环提取
|
||||
try{
|
||||
list.set(i, parseJsonString(list.get(i).toString(), key, keyindex));
|
||||
}catch(JSONException jsone){
|
||||
if(key.equals(entry.getKey())){
|
||||
if(keyindex==COUNTER){
|
||||
JSONVALUE = entry.getValue().toString();
|
||||
}
|
||||
COUNTER++;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// 获取key中的value
|
||||
if (key.equals(entry.getKey())) {
|
||||
if (keyindex == COUNTER) {
|
||||
JSONVALUE = entry.getValue().toString();
|
||||
}
|
||||
COUNTER++;
|
||||
}
|
||||
|
||||
return entry;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取JSON或是JSONArray对象指定序号Key中的Value
|
||||
*
|
||||
* @param json
|
||||
* @param key
|
||||
* @param indexstr
|
||||
* @return
|
||||
*/
|
||||
public static String getJsonValue(String json, String key, String indexstr) {
|
||||
json = json.trim();
|
||||
int index = 1;
|
||||
String result = JSONVALUE;
|
||||
if (isInteger(indexstr) && !"0".equals(indexstr)) {
|
||||
index = Integer.valueOf(indexstr);
|
||||
} else {
|
||||
result = JSONVALUE + "指定的key值序号不是大于0的整数(序号从1开始),请检查!";
|
||||
return result;
|
||||
}
|
||||
|
||||
if (json.startsWith("{") && json.endsWith("}")) {
|
||||
try {
|
||||
JSONObject jsonStr = JSONObject.parseObject(json, Feature.OrderedField);
|
||||
parseJsonString(jsonStr.toString(), key, index);
|
||||
result = JSONVALUE;
|
||||
} catch (Exception e) {
|
||||
result = JSONVALUE + "格式化成JSON异常,请检查参数:" + json;
|
||||
return result;
|
||||
}
|
||||
} else if (json.startsWith("[") && json.endsWith("]")) {
|
||||
try {
|
||||
// JSONArray jsonarr = JSONArray.parseArray(json);
|
||||
// 直接使用fastjson的接口实现有序解析
|
||||
JSONArray jsonarr = JSONArray.parseObject(json.getBytes("UTF-8"), JSONArray.class, Feature.OrderedField);
|
||||
for (int i = 0; i < jsonarr.size(); i++) {
|
||||
JSONObject jsonStr = jsonarr.getJSONObject(i);
|
||||
parseJsonString(jsonStr.toJSONString(), key, index);
|
||||
if (!JSONVALUE.startsWith("【获取JSON KEY中的Value异常】")) {
|
||||
result = JSONVALUE;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
result = JSONVALUE + "格式化成JSONArray异常,请检查参数:" + json;
|
||||
return result;
|
||||
}
|
||||
} else {
|
||||
result = JSONVALUE + "格式化成JSON或是JSONArray时出现异常,请检查参数:" + json;
|
||||
}
|
||||
|
||||
if (result.equals("【获取JSON KEY中的Value异常】")) {
|
||||
result = JSONVALUE + "没有找到对应的KEY值,请确认!";
|
||||
}
|
||||
|
||||
COUNTER = 1;
|
||||
JSONVALUE = "【获取JSON KEY中的Value异常】";
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过jsonPath表达式获取JSON字符串指定值
|
||||
* @param actionParams
|
||||
* @param testResult
|
||||
* @return
|
||||
* @author Seagull
|
||||
* @date 2019年8月28日
|
||||
*/
|
||||
public static String jsonPathGetParams(String expressionParams, String jsonString) {
|
||||
String type="String";
|
||||
String expression="";
|
||||
if(expressionParams.endsWith("]")&&expressionParams.contains("[")){
|
||||
try{
|
||||
type=expressionParams.substring(0,expressionParams.indexOf("["));
|
||||
expression=expressionParams.substring(expressionParams.indexOf("[")+1, expressionParams.lastIndexOf("]"));
|
||||
if("list".equals(type.toLowerCase())){
|
||||
//去除测试响应头域消息
|
||||
if(jsonString.startsWith(Constants.RESPONSE_HEAD)){
|
||||
jsonString = jsonString.substring(jsonString.indexOf(Constants.RESPONSE_END)+1);
|
||||
}
|
||||
|
||||
//去除测试响应头域消息
|
||||
if(jsonString.startsWith(Constants.RESPONSE_CODE)){
|
||||
jsonString = jsonString.substring(jsonString.indexOf(Constants.RESPONSE_END)+1);
|
||||
}
|
||||
|
||||
List<Object> list = JsonPath.parse(jsonString).read(expression);
|
||||
jsonString="";
|
||||
for(Object result:list){
|
||||
result = (String)jsonString+result+",";
|
||||
jsonString = (String)result;
|
||||
}
|
||||
}else{
|
||||
jsonString=JsonPath.parse(jsonString).read(expression);
|
||||
}
|
||||
}catch(PathNotFoundException pnfe){
|
||||
LogUtil.APP.error("通过jsonPath获取JSON字符串指定值出现异常,没有找到对应参数路径,请确认JSON字符串【{}】表达式是否正确【{}】!",jsonString,expression);
|
||||
}catch(Exception e){
|
||||
LogUtil.APP.error("通过jsonPath获取JSON字符串指定值出现异,请检查您的动作参数格式(String/List[表达式])或是被提取的json字符串是否正常!",expressionParams);
|
||||
}
|
||||
}else{
|
||||
LogUtil.APP.warn("获取JSON字符串指定jsonPath表达式【{}】异常,请检查您的动作参数格式(String/List[表达式])是否正常!",expressionParams);
|
||||
}
|
||||
LogUtil.APP.info("获取JSON字符串指定jsonPath表达式【{}】的值是:{}",expression,jsonString);
|
||||
return jsonString;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
String json = " "
|
||||
+ "{\"access_token\":\"d26b9148-20c9-4779-888c-0d9988cf3bf5\",\"token_type\":\"bearer\",\"expires_in\":599999,\"scope\":\"1/platformehicle/access_gateway/engine/forbid,1/platformehicle/access_gateway/engine/enable 1/platformehicle/access_gateway/system/diagnosis\"} ";
|
||||
String key = "access_token";
|
||||
String indexstr = "1";
|
||||
System.out.println(getJsonValue(json, key, indexstr));
|
||||
}
|
||||
}
|
||||
package luckyclient.driven;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.alibaba.fastjson.JSONException;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.alibaba.fastjson.TypeReference;
|
||||
import com.alibaba.fastjson.parser.Feature;
|
||||
import com.jayway.jsonpath.JsonPath;
|
||||
import com.jayway.jsonpath.PathNotFoundException;
|
||||
|
||||
import luckyclient.utils.Constants;
|
||||
import luckyclient.utils.LogUtil;
|
||||
|
||||
/**
|
||||
* 公用驱动
|
||||
* =================================================================
|
||||
* 这是一个受限制的自由软件!您不能在任何未经允许的前提下对程序代码进行修改和用于商业用途;也不允许对程序代码修改后以任何形式任何目的的再发布。
|
||||
* 为了尊重作者的劳动成果,LuckyFrame关键版权信息严禁篡改 有任何疑问欢迎联系作者讨论。 QQ:1573584944 Seagull
|
||||
* =================================================================
|
||||
* @author Seagull
|
||||
* @date 2019年1月15日
|
||||
*/
|
||||
public class SubString {
|
||||
/**
|
||||
* 截取指定字符串的中间字段
|
||||
*
|
||||
* @param str
|
||||
* @param startstr
|
||||
* @param endstr
|
||||
* @return
|
||||
*/
|
||||
public static String subCentreStr(String str, String startstr, String endstr) {
|
||||
try{
|
||||
int startnum=0;
|
||||
int endnum=str.length();
|
||||
if(!"".equals(startstr)){
|
||||
startnum=str.indexOf(startstr) + startstr.length();
|
||||
}
|
||||
if(!"".equals(endstr)){
|
||||
endnum=str.indexOf(endstr, str.indexOf(startstr) + startstr.length());
|
||||
}
|
||||
String getstr = str.substring(startnum,endnum);
|
||||
return getstr;
|
||||
}catch(Exception e){
|
||||
LogUtil.APP.error("subCentreStr截取字符串出现异常,请检查参数!",e);
|
||||
return "截取字符串出现异常,请检查参数!";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 截取字符串从指定字符开始
|
||||
*
|
||||
* @param str
|
||||
* @param startstr
|
||||
* @return
|
||||
*/
|
||||
public static String subStartStr(String str, String startstr) {
|
||||
try{
|
||||
String getstr = str.substring(str.indexOf(startstr) + startstr.length());
|
||||
return getstr;
|
||||
}catch(Exception e){
|
||||
LogUtil.APP.error("subStartStr截取字符串出现异常,请检查参数!",e);
|
||||
return "截取字符串出现异常,请检查参数!";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 截取字符串到指定字符结束
|
||||
*
|
||||
* @param str
|
||||
* @param endstr
|
||||
* @return
|
||||
*/
|
||||
public static String subEndStr(String str, String endstr) {
|
||||
try{
|
||||
String getstr = str.substring(0, str.indexOf(endstr));
|
||||
return getstr;
|
||||
}catch(Exception e){
|
||||
LogUtil.APP.error("subEndStr截取字符串出现异常,请检查参数!",e);
|
||||
return "截取字符串出现异常,请检查参数!";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过字符串位置截取指定字符串的中间字段
|
||||
*
|
||||
* @param str
|
||||
* @param startnum
|
||||
* @param endnum
|
||||
* @return
|
||||
*/
|
||||
public static String subCentreNum(String str, String startnum, String endnum) {
|
||||
String getstr = "";
|
||||
if("".equals(startnum)){
|
||||
startnum="0";
|
||||
}
|
||||
if("".equals(endnum)){
|
||||
endnum=String.valueOf(str.length());
|
||||
}
|
||||
try{
|
||||
if (isInteger(startnum) && isInteger(endnum)) {
|
||||
int start = Integer.valueOf(startnum);
|
||||
int end = Integer.valueOf(endnum);
|
||||
if (start > end) {
|
||||
getstr = "截取字符串开始位置数字不能大于结束位置数字";
|
||||
} else if (start < 0 || end < 0) {
|
||||
getstr = "截取字符串位置的数字不能小于0";
|
||||
} else if (start > str.length() || end > str.length()) {
|
||||
getstr = "截取字符串位置的数字不能大于字符串本身的长度【" + str.length() + "】";
|
||||
} else {
|
||||
getstr = str.substring(start, end);
|
||||
}
|
||||
} else {
|
||||
getstr = "指定的开始或是结束位置字符不是数字类型,请检查!";
|
||||
}
|
||||
|
||||
return getstr;
|
||||
}catch(Exception e){
|
||||
LogUtil.APP.error("subCentreNum截取字符串出现异常,请检查参数!",e);
|
||||
return "截取字符串出现异常,请检查参数!";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过字符串位置截取字符串从指定字符开始
|
||||
*
|
||||
* @param str
|
||||
* @param startnum
|
||||
* @return
|
||||
*/
|
||||
public static String subStartNum(String str, String startnum) {
|
||||
String getstr = "";
|
||||
try{
|
||||
if (isInteger(startnum)) {
|
||||
int start = Integer.valueOf(startnum);
|
||||
if (start < 0) {
|
||||
getstr = "截取字符串位置的数字不能小于0";
|
||||
} else if (start > str.length()) {
|
||||
getstr = "截取字符串位置的数字不能大于字符串本身的长度【" + str.length() + "】";
|
||||
} else {
|
||||
getstr = str.substring(start);
|
||||
}
|
||||
} else {
|
||||
getstr = "指定的开始位置字符不是数字类型,请检查!";
|
||||
}
|
||||
|
||||
return getstr;
|
||||
}catch(Exception e){
|
||||
LogUtil.APP.error("subStartNum截取字符串出现异常,请检查参数!",e);
|
||||
return "截取字符串出现异常,请检查参数!";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 截取字符串到指定字符结束
|
||||
*
|
||||
* @param str
|
||||
* @param endnum
|
||||
* @return
|
||||
*/
|
||||
public static String subEndNum(String str, String endnum) {
|
||||
String getstr = "";
|
||||
try{
|
||||
if (isInteger(endnum)) {
|
||||
int end = Integer.valueOf(endnum);
|
||||
if (end < 0) {
|
||||
getstr = "截取字符串位置的数字不能小于0";
|
||||
} else if (end > str.length()) {
|
||||
getstr = "截取字符串位置的数字不能大于字符串本身的长度【" + str.length() + "】";
|
||||
} else {
|
||||
getstr = str.substring(0, end);
|
||||
}
|
||||
} else {
|
||||
getstr = "指定的结束位置字符不是数字类型,请检查!";
|
||||
}
|
||||
|
||||
return getstr;
|
||||
}catch(Exception e){
|
||||
LogUtil.APP.error("subEndNum截取字符串出现异常,请检查参数!",e);
|
||||
return "截取字符串出现异常,请检查参数!";
|
||||
}
|
||||
}
|
||||
|
||||
public static String subStrRgex(String str, String rgex, String num) {
|
||||
List<String> list = new ArrayList<String>();
|
||||
try{
|
||||
// 匹配的模式
|
||||
Pattern pattern = Pattern.compile(rgex);
|
||||
Matcher m = pattern.matcher(str);
|
||||
while (m.find()) {
|
||||
// int i = 1;
|
||||
list.add(m.group());
|
||||
// i++;
|
||||
}
|
||||
|
||||
String getstr = "";
|
||||
if (isInteger(num)) {
|
||||
int index = Integer.valueOf(num);
|
||||
if (index < 0) {
|
||||
getstr = "截取字符串索引数字不能小于0";
|
||||
} else if (index > str.length()) {
|
||||
getstr = "截取字符串索引的数字不能大于字符串本身的长度【" + str.length() + "】";
|
||||
} else if (index > list.size()) {
|
||||
getstr = "未能在指定字符串中根据正则式找到匹配的字符串或是指定的索引数字大于能找到的匹配字符串索引量";
|
||||
} else {
|
||||
getstr = list.get(index - 1);
|
||||
}
|
||||
} else {
|
||||
getstr = "指定的索引位置字符不是数字类型,请检查!";
|
||||
}
|
||||
return getstr;
|
||||
}catch(Exception e){
|
||||
LogUtil.APP.error("subStrRgex截取字符串出现异常,请检查参数!",e);
|
||||
return "截取字符串出现异常,请检查参数!";
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isInteger(String str) {
|
||||
String patternStr="^[-\\+]?[\\d]*$";
|
||||
Pattern pattern = Pattern.compile(patternStr);
|
||||
return pattern.matcher(str).matches();
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化返回JSON中Value的值
|
||||
*/
|
||||
private static String JSONVALUE = "【获取JSON KEY中的Value异常】";
|
||||
|
||||
/**
|
||||
* 用于计数KEY的序号
|
||||
*/
|
||||
private static int COUNTER = 1;
|
||||
|
||||
/**
|
||||
* 遍历JSON对象
|
||||
*
|
||||
* @param json
|
||||
* @param key
|
||||
* @param keyindex
|
||||
* @return
|
||||
*/
|
||||
private static JSONObject parseJsonString(String json, String key, int keyindex) {
|
||||
LinkedHashMap<String, Object> jsonMap = JSON.parseObject(json,
|
||||
new TypeReference<LinkedHashMap<String, Object>>() {
|
||||
}, Feature.OrderedField);
|
||||
for (Map.Entry<String, Object> entry : jsonMap.entrySet()) {
|
||||
parseJsonMap(entry, key, keyindex);
|
||||
}
|
||||
return new JSONObject(jsonMap);
|
||||
}
|
||||
|
||||
/**
|
||||
* 遍历后JSON对象中的key以及value
|
||||
*
|
||||
* @param entry
|
||||
* @param key
|
||||
* @param keyindex
|
||||
* @return
|
||||
*/
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
private static Map.Entry<String, Object> parseJsonMap(Map.Entry<String, Object> entry, String key, int keyindex) {
|
||||
// 如果是单个map继续遍历
|
||||
if (entry.getValue() instanceof Map) {
|
||||
LinkedHashMap<String, Object> jsonMap = JSON.parseObject(entry.getValue().toString(),
|
||||
new TypeReference<LinkedHashMap<String, Object>>() {
|
||||
}, Feature.OrderedField);
|
||||
for (Map.Entry<String, Object> entry2 : jsonMap.entrySet()) {
|
||||
parseJsonMap(entry2, key, keyindex);
|
||||
}
|
||||
}
|
||||
// 如果是list就提取出来
|
||||
if (entry.getValue() instanceof List) {
|
||||
List list = (List) entry.getValue();
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
// 如果还有,循环提取
|
||||
//list.set(i, parseJsonString(list.get(i).toString(), key, keyindex));
|
||||
//如何还有,循环提取
|
||||
try{
|
||||
list.set(i, parseJsonString(list.get(i).toString(), key, keyindex));
|
||||
}catch(JSONException jsone){
|
||||
if(key.equals(entry.getKey())){
|
||||
if(keyindex==COUNTER){
|
||||
JSONVALUE = entry.getValue().toString();
|
||||
}
|
||||
COUNTER++;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// 获取key中的value
|
||||
if (key.equals(entry.getKey())) {
|
||||
if (keyindex == COUNTER) {
|
||||
JSONVALUE = entry.getValue().toString();
|
||||
}
|
||||
COUNTER++;
|
||||
}
|
||||
|
||||
return entry;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取JSON或是JSONArray对象指定序号Key中的Value
|
||||
*
|
||||
* @param json
|
||||
* @param key
|
||||
* @param indexstr
|
||||
* @return
|
||||
*/
|
||||
public static String getJsonValue(String json, String key, String indexstr) {
|
||||
json = json.trim();
|
||||
int index = 1;
|
||||
String result = JSONVALUE;
|
||||
if (isInteger(indexstr) && !"0".equals(indexstr)) {
|
||||
index = Integer.valueOf(indexstr);
|
||||
} else {
|
||||
result = JSONVALUE + "指定的key值序号不是大于0的整数(序号从1开始),请检查!";
|
||||
return result;
|
||||
}
|
||||
|
||||
if (json.startsWith("{") && json.endsWith("}")) {
|
||||
try {
|
||||
JSONObject jsonStr = JSONObject.parseObject(json, Feature.OrderedField);
|
||||
parseJsonString(jsonStr.toString(), key, index);
|
||||
result = JSONVALUE;
|
||||
} catch (Exception e) {
|
||||
result = JSONVALUE + "格式化成JSON异常,请检查参数:" + json;
|
||||
return result;
|
||||
}
|
||||
} else if (json.startsWith("[") && json.endsWith("]")) {
|
||||
try {
|
||||
// JSONArray jsonarr = JSONArray.parseArray(json);
|
||||
// 直接使用fastjson的接口实现有序解析
|
||||
JSONArray jsonarr = JSONArray.parseObject(json.getBytes("UTF-8"), JSONArray.class, Feature.OrderedField);
|
||||
for (int i = 0; i < jsonarr.size(); i++) {
|
||||
JSONObject jsonStr = jsonarr.getJSONObject(i);
|
||||
parseJsonString(jsonStr.toJSONString(), key, index);
|
||||
if (!JSONVALUE.startsWith("【获取JSON KEY中的Value异常】")) {
|
||||
result = JSONVALUE;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
result = JSONVALUE + "格式化成JSONArray异常,请检查参数:" + json;
|
||||
return result;
|
||||
}
|
||||
} else {
|
||||
result = JSONVALUE + "格式化成JSON或是JSONArray时出现异常,请检查参数:" + json;
|
||||
}
|
||||
|
||||
if (result.equals("【获取JSON KEY中的Value异常】")) {
|
||||
result = JSONVALUE + "没有找到对应的KEY值,请确认!";
|
||||
}
|
||||
|
||||
COUNTER = 1;
|
||||
JSONVALUE = "【获取JSON KEY中的Value异常】";
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过jsonPath表达式获取JSON字符串指定值
|
||||
* @param expressionParams
|
||||
* @param jsonString
|
||||
* @return
|
||||
* @author Seagull
|
||||
* @date 2019年8月28日
|
||||
*/
|
||||
public static String jsonPathGetParams(String expressionParams, String jsonString) {
|
||||
String type="String";
|
||||
String expression="";
|
||||
if(expressionParams.endsWith("]")&&expressionParams.contains("[")){
|
||||
try{
|
||||
type=expressionParams.substring(0,expressionParams.indexOf("["));
|
||||
expression=expressionParams.substring(expressionParams.indexOf("[")+1, expressionParams.lastIndexOf("]"));
|
||||
if("list".equals(type.toLowerCase())){
|
||||
//去除测试响应头域消息
|
||||
if(jsonString.startsWith(Constants.RESPONSE_HEAD)){
|
||||
jsonString = jsonString.substring(jsonString.indexOf(Constants.RESPONSE_END)+1);
|
||||
}
|
||||
|
||||
//去除测试响应头域消息
|
||||
if(jsonString.startsWith(Constants.RESPONSE_CODE)){
|
||||
jsonString = jsonString.substring(jsonString.indexOf(Constants.RESPONSE_END)+1);
|
||||
}
|
||||
|
||||
List<Object> list = JsonPath.parse(jsonString).read(expression);
|
||||
jsonString="";
|
||||
for(Object result:list){
|
||||
result = (String)jsonString+result+",";
|
||||
jsonString = (String)result;
|
||||
}
|
||||
}else{
|
||||
jsonString=JsonPath.parse(jsonString).read(expression);
|
||||
}
|
||||
}catch(PathNotFoundException pnfe){
|
||||
LogUtil.APP.error("通过jsonPath获取JSON字符串指定值出现异常,没有找到对应参数路径,请确认JSON字符串【{}】表达式是否正确【{}】!",jsonString,expression);
|
||||
}catch(Exception e){
|
||||
LogUtil.APP.error("通过jsonPath获取JSON字符串指定值出现异,请检查您的动作参数格式(String/List[表达式])或是被提取的json字符串是否正常!",expressionParams);
|
||||
}
|
||||
}else{
|
||||
LogUtil.APP.warn("获取JSON字符串指定jsonPath表达式【{}】异常,请检查您的动作参数格式(String/List[表达式])是否正常!",expressionParams);
|
||||
}
|
||||
LogUtil.APP.info("获取JSON字符串指定jsonPath表达式【{}】的值是:{}",expression,jsonString);
|
||||
return jsonString;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,264 +1,269 @@
|
|||
package luckyclient.netty;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.core.io.support.PropertiesLoaderUtils;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import io.netty.channel.ChannelHandlerAdapter;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.EventLoop;
|
||||
import io.netty.handler.timeout.IdleState;
|
||||
import io.netty.handler.timeout.IdleStateEvent;
|
||||
import luckyclient.utils.config.SysConfig;
|
||||
|
||||
|
||||
public class ClientHandler extends ChannelHandlerAdapter {
|
||||
|
||||
//从application.properties文件中获取用到的参数;
|
||||
private static Resource resource = new ClassPathResource("application.properties");
|
||||
private static Properties props;
|
||||
|
||||
static {
|
||||
try {
|
||||
props = PropertiesLoaderUtils.loadProperties(resource);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private static String port = props.getProperty("server.port");
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ClientHandler.class);
|
||||
|
||||
private static final String HOST_NAME = SysConfig.getConfiguration().getProperty("host.name");
|
||||
|
||||
private static final String CLIENT_VERSION = SysConfig.getConfiguration().getProperty("client.verison");
|
||||
|
||||
private static final String SERVER_IP = SysConfig.getConfiguration().getProperty("server.web.ip");
|
||||
|
||||
private static final String SERVER_PORT = SysConfig.getConfiguration().getProperty("server.web.port");
|
||||
|
||||
private int byteRead;
|
||||
|
||||
|
||||
private volatile int lastLength = 0;
|
||||
|
||||
public RandomAccessFile randomAccessFile;
|
||||
|
||||
|
||||
private static ChannelHandlerContext ctx;
|
||||
|
||||
public ClientHandler() throws IOException {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelRead(ChannelHandlerContext ctx, Object msg) throws UnsupportedEncodingException, InterruptedException {
|
||||
//服务端消息处理,如果接收到测试任务方法,则直接产生一个http请求并发送请求到本地
|
||||
String jsonStr = msg.toString();
|
||||
JSONObject json = new JSONObject();
|
||||
try {
|
||||
json = JSON.parseObject(jsonStr);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("收到服务端非Json消息,但是异常:" + jsonStr);
|
||||
return;
|
||||
}
|
||||
log.info("收到服务端消息:" + json.toString());
|
||||
//解析消息
|
||||
if ("run".equals(json.get("method"))) {
|
||||
try {
|
||||
//返回请求
|
||||
JSONObject re = new JSONObject();
|
||||
re.put("method", "return");
|
||||
Result result = new Result(1, "同步等待消息返回", json.get("uuid").toString(), null);
|
||||
//如果是调度请求,则发起一个HTTP请求
|
||||
//获取是get方法还是post方法
|
||||
String getOrPost = json.get("getOrPost").toString();
|
||||
String urlParam = "http://127.0.0.1:" + port + "/" + json.get("url").toString();
|
||||
Integer socketTimeout = Integer.valueOf(json.get("socketTimeout").toString());
|
||||
String tmpResult = "";
|
||||
if ("get".equals(getOrPost)) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> jsonparams = (Map<String, Object>) json.get("data");
|
||||
//get方法
|
||||
try {
|
||||
tmpResult = HttpRequest.httpClientGet(urlParam, jsonparams, socketTimeout);
|
||||
} catch (Exception e) {
|
||||
log.error("转发服务端GET请求出错");
|
||||
}
|
||||
} else {
|
||||
String jsonparams = json.get("data").toString();
|
||||
//post方法
|
||||
try {
|
||||
tmpResult = HttpRequest.httpClientPost(urlParam, jsonparams, socketTimeout);
|
||||
} catch (Exception e) {
|
||||
log.error("转发服务端POST请求出错");
|
||||
}
|
||||
}
|
||||
result.setMessage(tmpResult);
|
||||
re.put("data", result);
|
||||
sendMessage(re.toString());
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
} else if ("download".equals(json.get("method"))) {
|
||||
String loadpath = json.get("path").toString();
|
||||
String path = System.getProperty("user.dir") + loadpath;
|
||||
String fileName = json.get("fileName").toString();
|
||||
//发出http请求下载文件
|
||||
try {
|
||||
HttpRequest.downLoadFromUrl("http://" + SERVER_IP + ":" + SERVER_PORT + "/common/download?fileName=" + fileName, fileName, path);
|
||||
//返回请求
|
||||
JSONObject re = new JSONObject();
|
||||
Result result = new Result(1, "上传成功", json.get("uuid").toString(), null);
|
||||
re.put("method", "return");
|
||||
re.put("data", result);
|
||||
sendMessage(re.toString());
|
||||
log.info("下载驱动包成功,路径为:" + path + ";文件名为:" + fileName);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
//返回请求
|
||||
JSONObject re = new JSONObject();
|
||||
Result result = new Result(0, "上传失败", json.get("uuid").toString(), null);
|
||||
re.put("method", "return");
|
||||
re.put("data", result);
|
||||
sendMessage(re.toString());
|
||||
log.error("下载驱动包失败,路径为:" + path + ";文件名为:" + fileName);
|
||||
}
|
||||
} else if ("upload".equals(json.get("method"))) {
|
||||
try {
|
||||
//上传截图到服务器
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> jsonparams = (Map<String, Object>) json.get("data");
|
||||
String fileName = jsonparams.get("imgName").toString();
|
||||
String ctxPath = System.getProperty("user.dir") + File.separator + "log" + File.separator + "ScreenShot" + File.separator + fileName;
|
||||
File file = new File(ctxPath);
|
||||
int start = Integer.valueOf(json.get("start").toString());
|
||||
FileUploadFile fileUploadFile = new FileUploadFile();
|
||||
fileUploadFile.setFile(file);
|
||||
if (start != -1) {
|
||||
if (start == 0)
|
||||
lastLength = 1024 * 10;
|
||||
randomAccessFile = new RandomAccessFile(fileUploadFile.getFile(), "r");
|
||||
randomAccessFile.seek(start); //将文件定位到start
|
||||
log.info("长度:" + (randomAccessFile.length() - start));
|
||||
int a = (int) (randomAccessFile.length() - start);
|
||||
int b = (int) (randomAccessFile.length() / 1024 * 2);
|
||||
if (a < lastLength) {
|
||||
lastLength = a;
|
||||
}
|
||||
log.info("文件长度:" + (randomAccessFile.length()) + ",start:" + start + ",a:" + a + ",b:" + b + ",lastLength:" + lastLength);
|
||||
byte[] bytes = new byte[lastLength];
|
||||
log.info("bytes的长度是=" + bytes.length);
|
||||
if ((byteRead = randomAccessFile.read(bytes)) != -1 && (randomAccessFile.length() - start) > 0) {
|
||||
log.info("byteRead = " + byteRead);
|
||||
fileUploadFile.setEndPos(byteRead);
|
||||
fileUploadFile.setBytes(bytes);
|
||||
//返回请求
|
||||
JSONObject re = new JSONObject();
|
||||
Result result = new Result(1, "上传成功", json.get("uuid").toString(), fileUploadFile);
|
||||
re.put("method", "upload");
|
||||
re.put("data", result);
|
||||
re.put("uuid", json.get("uuid").toString());
|
||||
re.put("imgName", fileName);
|
||||
re.put("start", start);
|
||||
sendMessage(re.toString());
|
||||
try {
|
||||
ctx.writeAndFlush(fileUploadFile);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
} else {
|
||||
randomAccessFile.close();
|
||||
log.info("文件已经读完channelRead()--------" + byteRead);
|
||||
//返回请求
|
||||
JSONObject re = new JSONObject();
|
||||
Result result = new Result(1, "上传成功", json.get("uuid").toString(), null);
|
||||
re.put("method", "return");
|
||||
re.put("data", result);
|
||||
sendMessage(re.toString());
|
||||
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
//返回请求
|
||||
JSONObject re = new JSONObject();
|
||||
Result result = new Result(0, "异常错误", json.get("uuid").toString(), null);
|
||||
re.put("method", "return");
|
||||
re.put("data", result);
|
||||
sendMessage(re.toString());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelActive(ChannelHandlerContext ctx) throws Exception {
|
||||
//发送客户端登录消息
|
||||
JSONObject json = new JSONObject();
|
||||
json.put("hostName", HOST_NAME);
|
||||
json.put("version", CLIENT_VERSION);
|
||||
json.put("method", "clientUp");
|
||||
ClientHandler.ctx = ctx;
|
||||
sendMessage(json.toString());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelInactive(ChannelHandlerContext ctx) {
|
||||
log.info("连接已断开,正在尝试重连...");
|
||||
//使用过程中断线重连
|
||||
final EventLoop eventLoop = ctx.channel().eventLoop();
|
||||
eventLoop.schedule(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
NettyClient.start();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}, 1, TimeUnit.SECONDS);
|
||||
|
||||
ctx.fireChannelInactive();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
|
||||
cause.printStackTrace();
|
||||
ctx.close();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
|
||||
throws Exception {
|
||||
if (evt instanceof IdleStateEvent) {
|
||||
IdleStateEvent event = (IdleStateEvent) evt;
|
||||
if (event.state().equals(IdleState.READER_IDLE)) {
|
||||
/**发送心跳,保持长连接*/
|
||||
JSONObject json = new JSONObject();
|
||||
json.put("method", "ping");
|
||||
json.put("hostName", HOST_NAME);
|
||||
//ctx.channel().writeAndFlush(json.toString() + "$_").sync();
|
||||
sendMessage(json.toString());
|
||||
//log.info("心跳发送成功!");
|
||||
}
|
||||
}
|
||||
super.userEventTriggered(ctx, evt);
|
||||
}
|
||||
|
||||
|
||||
public static void sendMessage(String json) throws InterruptedException {
|
||||
ctx.channel().writeAndFlush(Unpooled.copiedBuffer((json + "$_").getBytes()));
|
||||
}
|
||||
package luckyclient.netty;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.core.io.support.PropertiesLoaderUtils;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import io.netty.channel.ChannelHandlerAdapter;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.EventLoop;
|
||||
import io.netty.handler.timeout.IdleState;
|
||||
import io.netty.handler.timeout.IdleStateEvent;
|
||||
import luckyclient.utils.config.SysConfig;
|
||||
import springboot.RunService;
|
||||
|
||||
|
||||
public class ClientHandler extends ChannelHandlerAdapter {
|
||||
|
||||
//从application.properties文件中获取用到的参数;
|
||||
private static Resource resource = new ClassPathResource("application.properties");
|
||||
private static Properties props;
|
||||
|
||||
static {
|
||||
try {
|
||||
props = PropertiesLoaderUtils.loadProperties(resource);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private static String port = props.getProperty("server.port");
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ClientHandler.class);
|
||||
|
||||
private static final String NETTY_HOST = SysConfig.getConfiguration().getProperty("netty.host");
|
||||
|
||||
private static final String CLIENT_NAME = SysConfig.getConfiguration().getProperty("client.name");
|
||||
|
||||
private static final String CLIENT_VERSION = SysConfig.getConfiguration().getProperty("client.verison");
|
||||
|
||||
private static final String SERVER_IP = SysConfig.getConfiguration().getProperty("server.web.ip");
|
||||
|
||||
private static final String SERVER_PORT = SysConfig.getConfiguration().getProperty("server.web.port");
|
||||
|
||||
private int byteRead;
|
||||
|
||||
|
||||
private volatile int lastLength = 0;
|
||||
|
||||
public RandomAccessFile randomAccessFile;
|
||||
|
||||
|
||||
private static ChannelHandlerContext ctx;
|
||||
|
||||
public ClientHandler() throws IOException {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelRead(ChannelHandlerContext ctx, Object msg) throws UnsupportedEncodingException, InterruptedException {
|
||||
//服务端消息处理,如果接收到测试任务方法,则直接产生一个http请求并发送请求到本地
|
||||
String jsonStr = msg.toString();
|
||||
JSONObject json = new JSONObject();
|
||||
try {
|
||||
json = JSON.parseObject(jsonStr);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("收到服务端非Json消息,但是异常:" + jsonStr);
|
||||
return;
|
||||
}
|
||||
log.info("收到服务端消息:" + json.toString());
|
||||
//解析消息
|
||||
if ("run".equals(json.get("method"))) {
|
||||
try {
|
||||
//返回请求
|
||||
JSONObject re = new JSONObject();
|
||||
re.put("method", "return");
|
||||
Result result = new Result(1, "同步等待消息返回", json.get("uuid").toString(), null);
|
||||
//如果是调度请求,则发起一个HTTP请求
|
||||
//获取是get方法还是post方法
|
||||
String getOrPost = json.get("getOrPost").toString();
|
||||
String urlParam = "http://127.0.0.1:" + port + "/" + json.get("url").toString();
|
||||
Integer socketTimeout = Integer.valueOf(json.get("socketTimeout").toString());
|
||||
String tmpResult = "";
|
||||
if ("get".equals(getOrPost)) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> jsonparams = (Map<String, Object>) json.get("data");
|
||||
//get方法
|
||||
try {
|
||||
tmpResult = HttpRequest.httpClientGet(urlParam, jsonparams, socketTimeout);
|
||||
} catch (Exception e) {
|
||||
log.error("转发服务端GET请求出错");
|
||||
}
|
||||
} else {
|
||||
String jsonparams = json.get("data").toString();
|
||||
//post方法
|
||||
try {
|
||||
tmpResult = HttpRequest.httpClientPost(urlParam, jsonparams, socketTimeout);
|
||||
} catch (Exception e) {
|
||||
log.error("转发服务端POST请求出错");
|
||||
}
|
||||
}
|
||||
result.setMessage(tmpResult);
|
||||
re.put("data", result);
|
||||
sendMessage(re.toString());
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
} else if ("download".equals(json.get("method"))) {
|
||||
String loadpath = json.get("path").toString();
|
||||
String path = System.getProperty("user.dir") + loadpath;
|
||||
String fileName = json.get("fileName").toString();
|
||||
//发出http请求下载文件
|
||||
try {
|
||||
HttpRequest.downLoadFromUrl("http://" + SERVER_IP + ":" + SERVER_PORT + "/common/download?fileName=" + fileName, fileName, path);
|
||||
//返回请求
|
||||
JSONObject re = new JSONObject();
|
||||
Result result = new Result(1, "上传成功", json.get("uuid").toString(), null);
|
||||
re.put("method", "return");
|
||||
re.put("data", result);
|
||||
sendMessage(re.toString());
|
||||
log.info("下载驱动包成功,路径为:" + path + ";文件名为:" + fileName);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
//返回请求
|
||||
JSONObject re = new JSONObject();
|
||||
Result result = new Result(0, "上传失败", json.get("uuid").toString(), null);
|
||||
re.put("method", "return");
|
||||
re.put("data", result);
|
||||
sendMessage(re.toString());
|
||||
log.error("下载驱动包失败,路径为:" + path + ";文件名为:" + fileName);
|
||||
}
|
||||
} else if ("upload".equals(json.get("method"))) {
|
||||
try {
|
||||
//上传截图到服务器
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> jsonparams = (Map<String, Object>) json.get("data");
|
||||
String fileName = jsonparams.get("imgName").toString();
|
||||
String ctxPath = System.getProperty("user.dir") + File.separator + "log" + File.separator + "ScreenShot" + File.separator + fileName;
|
||||
File file = new File(ctxPath);
|
||||
int start = Integer.valueOf(json.get("start").toString());
|
||||
FileUploadFile fileUploadFile = new FileUploadFile();
|
||||
fileUploadFile.setFile(file);
|
||||
if (start != -1) {
|
||||
if (start == 0)
|
||||
lastLength = 1024 * 10;
|
||||
randomAccessFile = new RandomAccessFile(fileUploadFile.getFile(), "r");
|
||||
randomAccessFile.seek(start); //将文件定位到start
|
||||
log.info("长度:" + (randomAccessFile.length() - start));
|
||||
int a = (int) (randomAccessFile.length() - start);
|
||||
int b = (int) (randomAccessFile.length() / 1024 * 2);
|
||||
if (a < lastLength) {
|
||||
lastLength = a;
|
||||
}
|
||||
log.info("文件长度:" + (randomAccessFile.length()) + ",start:" + start + ",a:" + a + ",b:" + b + ",lastLength:" + lastLength);
|
||||
byte[] bytes = new byte[lastLength];
|
||||
log.info("bytes的长度是=" + bytes.length);
|
||||
if ((byteRead = randomAccessFile.read(bytes)) != -1 && (randomAccessFile.length() - start) > 0) {
|
||||
log.info("byteRead = " + byteRead);
|
||||
fileUploadFile.setEndPos(byteRead);
|
||||
fileUploadFile.setBytes(bytes);
|
||||
//返回请求
|
||||
JSONObject re = new JSONObject();
|
||||
Result result = new Result(1, "上传成功", json.get("uuid").toString(), fileUploadFile);
|
||||
re.put("method", "upload");
|
||||
re.put("data", result);
|
||||
re.put("uuid", json.get("uuid").toString());
|
||||
re.put("imgName", fileName);
|
||||
re.put("start", start);
|
||||
sendMessage(re.toString());
|
||||
try {
|
||||
ctx.writeAndFlush(fileUploadFile);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
} else {
|
||||
randomAccessFile.close();
|
||||
log.info("文件已经读完channelRead()--------" + byteRead);
|
||||
//返回请求
|
||||
JSONObject re = new JSONObject();
|
||||
Result result = new Result(1, "上传成功", json.get("uuid").toString(), null);
|
||||
re.put("method", "return");
|
||||
re.put("data", result);
|
||||
sendMessage(re.toString());
|
||||
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
//返回请求
|
||||
JSONObject re = new JSONObject();
|
||||
Result result = new Result(0, "异常错误", json.get("uuid").toString(), null);
|
||||
re.put("method", "return");
|
||||
re.put("data", result);
|
||||
sendMessage(re.toString());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelActive(ChannelHandlerContext ctx) throws Exception {
|
||||
//发送客户端登录消息
|
||||
JSONObject json = new JSONObject();
|
||||
json.put("hostName", NETTY_HOST);
|
||||
json.put("clientName", CLIENT_NAME);
|
||||
json.put("version", CLIENT_VERSION);
|
||||
json.put("ip", RunService.CLIENT_IP);
|
||||
json.put("method", "clientUp");
|
||||
ClientHandler.ctx = ctx;
|
||||
sendMessage(json.toString());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelInactive(ChannelHandlerContext ctx) {
|
||||
log.info("连接已断开,正在尝试重连...");
|
||||
//使用过程中断线重连
|
||||
final EventLoop eventLoop = ctx.channel().eventLoop();
|
||||
eventLoop.schedule(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
NettyClient.start();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}, 1, TimeUnit.SECONDS);
|
||||
|
||||
ctx.fireChannelInactive();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
|
||||
cause.printStackTrace();
|
||||
ctx.close();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
|
||||
throws Exception {
|
||||
if (evt instanceof IdleStateEvent) {
|
||||
IdleStateEvent event = (IdleStateEvent) evt;
|
||||
if (event.state().equals(IdleState.READER_IDLE)) {
|
||||
/**发送心跳,保持长连接*/
|
||||
JSONObject json = new JSONObject();
|
||||
json.put("method", "ping");
|
||||
json.put("hostName", NETTY_HOST);
|
||||
//ctx.channel().writeAndFlush(json.toString() + "$_").sync();
|
||||
sendMessage(json.toString());
|
||||
//log.info("心跳发送成功!");
|
||||
}
|
||||
}
|
||||
super.userEventTriggered(ctx, evt);
|
||||
}
|
||||
|
||||
|
||||
public static void sendMessage(String json) throws InterruptedException {
|
||||
ctx.channel().writeAndFlush(Unpooled.copiedBuffer((json + "$_").getBytes()));
|
||||
}
|
||||
}
|
|
@ -1,53 +1,54 @@
|
|||
package springboot;
|
||||
|
||||
import java.io.File;
|
||||
import java.net.InetAddress;
|
||||
|
||||
import org.apache.log4j.PropertyConfigurator;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
import cn.hutool.core.util.BooleanUtil;
|
||||
import luckyclient.netty.NettyClient;
|
||||
import luckyclient.utils.config.SysConfig;
|
||||
|
||||
/**
|
||||
* =================================================================
|
||||
* 这是一个受限制的自由软件!您不能在任何未经允许的前提下对程序代码进行修改和用于商业用途;也不允许对程序代码修改后以任何形式任何目的的再发布。
|
||||
* 为了尊重作者的劳动成果,LuckyFrame关键版权信息严禁篡改
|
||||
* 有任何疑问欢迎联系作者讨论。 QQ:1573584944 seagull1985
|
||||
* =================================================================
|
||||
* @author seagull
|
||||
* @date 2018年7月27日 上午10:16:40
|
||||
*/
|
||||
@SpringBootApplication
|
||||
public class RunService {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(RunService.class);
|
||||
private static final Boolean NETTY_MODEL= BooleanUtil.toBoolean(SysConfig.getConfiguration().getProperty("netty.model"));
|
||||
public static void main(String[] args) {
|
||||
// TODO Auto-generated method stub
|
||||
PropertyConfigurator.configure(System.getProperty("user.dir") + File.separator +"bootlog4j.conf");
|
||||
SpringApplication.run(RunService.class, args);
|
||||
try {
|
||||
String host = InetAddress.getLocalHost().getHostAddress();
|
||||
log.info("启动客户端监听,请稍后......监听IP:{}",host);
|
||||
} catch (Exception e) {
|
||||
log.error("获取服务IP出现异常......", e);
|
||||
}
|
||||
if(NETTY_MODEL){
|
||||
try {
|
||||
log.info("##################客户端netty开启#################");
|
||||
NettyClient.start();
|
||||
} catch (Exception e) {
|
||||
log.error("连接服务端netty异常......");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}else{
|
||||
HttpImpl.checkHostNet();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
package springboot;
|
||||
|
||||
import java.io.File;
|
||||
import java.net.InetAddress;
|
||||
|
||||
import org.apache.log4j.PropertyConfigurator;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
import cn.hutool.core.util.BooleanUtil;
|
||||
import luckyclient.netty.NettyClient;
|
||||
import luckyclient.utils.config.SysConfig;
|
||||
|
||||
/**
|
||||
* =================================================================
|
||||
* 这是一个受限制的自由软件!您不能在任何未经允许的前提下对程序代码进行修改和用于商业用途;也不允许对程序代码修改后以任何形式任何目的的再发布。
|
||||
* 为了尊重作者的劳动成果,LuckyFrame关键版权信息严禁篡改
|
||||
* 有任何疑问欢迎联系作者讨论。 QQ:1573584944 seagull1985
|
||||
* =================================================================
|
||||
* @author seagull
|
||||
* @date 2018年7月27日 上午10:16:40
|
||||
*/
|
||||
@SpringBootApplication
|
||||
public class RunService {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(RunService.class);
|
||||
private static final Boolean NETTY_MODEL= BooleanUtil.toBoolean(SysConfig.getConfiguration().getProperty("netty.model"));
|
||||
public static String CLIENT_IP = "";
|
||||
public static void main(String[] args) {
|
||||
// TODO Auto-generated method stub
|
||||
PropertyConfigurator.configure(System.getProperty("user.dir") + File.separator +"bootlog4j.conf");
|
||||
SpringApplication.run(RunService.class, args);
|
||||
try {
|
||||
CLIENT_IP = InetAddress.getLocalHost().getHostAddress();
|
||||
log.info("启动客户端监听,请稍后......监听IP:{}",CLIENT_IP);
|
||||
} catch (Exception e) {
|
||||
log.error("获取服务IP出现异常......", e);
|
||||
}
|
||||
if(NETTY_MODEL){
|
||||
try {
|
||||
log.info("##################客户端netty开启#################");
|
||||
NettyClient.start();
|
||||
} catch (Exception e) {
|
||||
log.error("连接服务端netty异常......");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}else{
|
||||
HttpImpl.checkHostNet();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue