Merge branch 'v1.0.1_dev' into 'master'

V1.0.1 dev release Merge

See merge request DDOSAQ/phoenix_ddos_handle!3
This commit is contained in:
黄昕 2020-07-07 19:43:26 +08:00
commit 9c7143b462
73 changed files with 5769 additions and 1075 deletions

View File

@ -54,5 +54,10 @@ phoenix.aes-key=Wt4EJu6Rrq5udd/42bNpCQ==
#====custom config,begin with phoenix==== #====custom config,begin with phoenix====
#调试配置 #调试配置
dispose.check-protocol-timeout=false dispose.check-protocol-timeout=false
dispose.check-request-token=true dispose.check-request-token=false
dispose.check-admin-permission=true dispose.check-admin-permission=false
# 迪普设备配置
# 发送超时时间(ms)
#dptech.soap-conn-timeout=5000
# 接收超时时间(ms)
dptech.soap-recv-timeout=50000

View File

@ -55,3 +55,9 @@ phoenix.aes-key=Wt4EJu6Rrq5udd/42bNpCQ==
dispose.check-protocol-timeout=false dispose.check-protocol-timeout=false
dispose.check-request-token=true dispose.check-request-token=true
dispose.check-admin-permission=true dispose.check-admin-permission=true
# 迪普设备配置
# 发送超时时间(ms)
#dptech.soap-conn-timeout=5000
# 接收超时时间(ms)
dptech.soap-recv-timeout=50000

View File

@ -0,0 +1,55 @@
package com.dispose.common;
/**
* The enum Device capacity.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
public enum CleanTaskStatus {
/**
* task is cleaning.
*/
CLEANING(1, "清洗中"),
/**
* task is end of cleaning.
*/
ENDOFCLEANING(2, "清洗结束"),
/**
* task is not existed.
*/
NOTASK(3, "该清洗任务不存在"),
/**
* HaoHan device err.
*/
HAOHANERROR(4, "浩瀚设备返回错误"),
/**
* device not support get task status.
*/
DEVNOTSUPPORT(0, "设备不支持获取任务状态");
private final int code;
private final String readme;
CleanTaskStatus(int code, String readme) {
this.code = code;
this.readme = readme;
}
/**
* Gets code.
*
* @return the code
*/
public int getCode() {
return this.code;
}
/**
* Gets readme.
*
* @return the readme
*/
public String getReadme() {
return this.readme;
}
}

View File

@ -31,27 +31,6 @@ public class ConstValue {
public static final long TOKEN_EXPIRED_TIME_MS = TOKEN_TIMEOUT_MS; public static final long TOKEN_EXPIRED_TIME_MS = TOKEN_TIMEOUT_MS;
} }
/**
* The type Soap wrapper const.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
public static class SoapWrapperConst {
/**
* The constant NAMESPACE_URI.
*/
public static final String NAMESPACE_URI = "http://%s/UMC/service/AbnormalFlowCleaningService";
/**
* The constant USER_NAME.
*/
//public static final String SERVICE_ADDRESS = "http://10.88.77.15/UMC/service/AbnormalFlowCleaningService?wsdl";
public static final String USER_NAME = "admin";
/**
* The constant PASSWORD.
*/
public static final String PASSWORD = "UMCAdministrator";
}
/** /**
* The type Protocol. * The type Protocol.
* *

View File

@ -7,140 +7,150 @@ package com.dispose.common;
*/ */
public enum ErrorCode { public enum ErrorCode {
/** /**
* Err ok error code. * The Err ok.
*/ */
ERR_OK(0, "成功"), ERR_OK(0, "成功"),
/** /**
* Err password error code. * The Err password.
*/ */
ERR_PASSWORD(1, "密码错误"), ERR_PASSWORD(1, "密码错误"),
/** /**
* Err usernotfound error code. * The Err usernotfound.
*/ */
ERR_USERNOTFOUND(2, "用户不存在"), ERR_USERNOTFOUND(2, "用户不存在"),
/** /**
* Err passwordmore error code. * The Err passwordmore.
*/ */
ERR_PASSWORDMORE(3, "连续密码错误达上限,再次输入错误将锁定用户"), ERR_PASSWORDMORE(3, "连续密码错误达上限,再次输入错误将锁定用户"),
/** /**
* Err userlock error code. * The Err userlock.
*/ */
ERR_USERLOCK(4, "密码错误达上限,用户被锁定"), ERR_USERLOCK(4, "密码错误达上限,用户被锁定"),
/** /**
* Err account error code. * The Err account.
*/ */
ERR_ACCOUNT(5, "用户账户异常"), ERR_ACCOUNT(5, "用户账户异常"),
/** /**
* Err userexist error code. * The Err userexist.
*/ */
ERR_USEREXIST(6, "该用户已经存在"), ERR_USEREXIST(6, "该用户已经存在"),
/** /**
* Err passwordsimple error code. * The Err passwordsimple.
*/ */
ERR_PASSWORDSIMPLE(7, "用户密码强度不符合要求"), ERR_PASSWORDSIMPLE(7, "用户密码强度不符合要求"),
/** /**
* Err inputformat error code. * The Err inputformat.
*/ */
ERR_INPUTFORMAT(8, "输入信息格式有误"), ERR_INPUTFORMAT(8, "输入信息格式有误"),
/** /**
* Err inputmiss error code. * The Err inputmiss.
*/ */
ERR_INPUTMISS(9, "缺少必要输入信息"), ERR_INPUTMISS(9, "缺少必要输入信息"),
/** /**
* Err permission error code. * The Err permission.
*/ */
ERR_PERMISSION(10, "操作员权限不足"), ERR_PERMISSION(10, "操作员权限不足"),
/** /**
* Err reqtimeout error code. * The Err reqtimeout.
*/ */
ERR_REQTIMEOUT(11, "请求超时"), ERR_REQTIMEOUT(11, "请求超时"),
/** /**
* Err params error code. * The Err params.
*/ */
ERR_PARAMS(12, "参数错误"), ERR_PARAMS(12, "参数错误"),
/** /**
* Err systemexception error code. * The Err systemexception.
*/ */
ERR_SYSTEMEXCEPTION(13, "系统异常"), ERR_SYSTEMEXCEPTION(13, "系统异常"),
/** /**
* Err unknowncmd error code. * The Err unknowncmd.
*/ */
ERR_UNKNOWNCMD(14, "未知命令"), ERR_UNKNOWNCMD(14, "未知命令"),
/** /**
* Err logout error code. * The Err logout.
*/ */
ERR_LOGOUT(15, "用户未登录"), ERR_LOGOUT(15, "用户未登录"),
/** /**
* Err tokentimeout error code. * The Err tokentimeout.
*/ */
ERR_TOKENTIMEOUT(16, "Token超时"), ERR_TOKENTIMEOUT(16, "Token超时"),
/** /**
* Err tokennotfound error code. * The Err tokennotfound.
*/ */
ERR_TOKENNOTFOUND(17, "非法Token"), ERR_TOKENNOTFOUND(17, "非法Token"),
/** /**
* Err missauthhead error code. * The Err missauthhead.
*/ */
ERR_MISSAUTHHEAD(18, "Http 请求缺少认证头部"), ERR_MISSAUTHHEAD(18, "Http 请求缺少认证头部"),
/** /**
* Err nosuchdevice error code. * The Err nosuchdevice.
*/ */
ERR_NOSUCHDEVICE(19, "没有这个设备"), ERR_NOSUCHDEVICE(19, "没有这个设备"),
/** /**
* Err deviceexists error code. * The Err deviceexists.
*/ */
ERR_DEVICEEXISTS(20, "设备已经存在"), ERR_DEVICEEXISTS(20, "设备已经存在"),
/** /**
* Err paramexception error code. * The Err paramexception.
*/ */
ERR_PARAMEXCEPTION(21, "参数异常"), ERR_PARAMEXCEPTION(21, "参数异常"),
/** /**
* Err version error code. * The Err version.
*/ */
ERR_VERSION(23, "协议版本不兼容,请升级系统"), ERR_VERSION(23, "协议版本不兼容,请升级系统"),
/** /**
* Err nosuchtype error code. * The Err nosuchtype.
*/ */
ERR_NOSUCHTYPE(24, "没有这个类型的处置设备"), ERR_NOSUCHTYPE(24, "没有这个类型的处置设备"),
/** /**
* Err removemore error code. * The Err removemore.
*/ */
ERR_REMOVEMORE(25, "禁止同时删除多个设备"), ERR_REMOVEMORE(25, "禁止同时删除多个设备"),
/** /**
* Err taskrunning error code. * The Err taskrunning.
*/ */
ERR_TASKRUNNING(26, "同类任务正在运行"), ERR_TASKRUNNING(26, "同类任务正在运行"),
/** /**
* Err unsupport error code. * The Err unsupport.
*/ */
ERR_UNSUPPORT(27, "不支持的操作"), ERR_UNSUPPORT(27, "不支持的操作"),
/** /**
* Err interrupt error code. * The Err interrupt.
*/ */
ERR_INTERRUPT(28, "操作中断"), ERR_INTERRUPT(28, "操作中断"),
/** /**
* Err calldevice error code. * The Err calldevice.
*/ */
ERR_CALLDEVICE(29, "调用设备失败"), ERR_CALLDEVICE(29, "调用设备失败"),
/** /**
* Err nosuchtask error code. * The Err nosuchtask.
*/ */
ERR_NOSUCHTASK(30, "没有该任务"), ERR_NOSUCHTASK(30, "没有该任务"),
/** /**
* Err tasknotrunning error code. * The Err tasknotrunning.
*/ */
ERR_TASKNOTRUNNING(31, "该任务没有运行"), ERR_TASKNOTRUNNING(31, "该任务没有运行"),
/** /**
* Err requesttimeout error code. * The Err requesttimeout.
*/ */
ERR_REQUESTTIMEOUT(32, "请求超时"), ERR_REQUESTTIMEOUT(32, "请求超时"),
/**
* The Err unabledisposeip.
*/
ERR_UNABLEDISPOSEIP(33, "无法处置该IP"),
/**
* Err haohan error error code.
*/
ERR_HAOHAN_ERROR(34, "浩瀚设备返回错误"),
; ;
private final int errno; private final int errno;

View File

@ -10,11 +10,11 @@ public class GlobalVar {
/** /**
* The constant SOAP_CONNECT_TIMEOUT. * The constant SOAP_CONNECT_TIMEOUT.
*/ */
public static final int SOAP_CONNECT_TIMEOUT = 5000; public static volatile int SOAP_CONNECT_TIMEOUT = 5000;
/** /**
* The constant SOAP_RECEIVE_TIMEOUT. * The constant SOAP_RECEIVE_TIMEOUT.
*/ */
public static final int SOAP_RECEIVE_TIMEOUT = 5000; public static volatile int SOAP_RECEIVE_TIMEOUT = 5000;
/** /**
* The constant MAX_THREAT_INFO_VERSION. * The constant MAX_THREAT_INFO_VERSION.
*/ */

View File

@ -63,6 +63,12 @@ public enum IPAddrType {
*/ */
public static boolean ipInRange(String rangeIp, String ipAddr) throws AddressStringException { public static boolean ipInRange(String rangeIp, String ipAddr) throws AddressStringException {
final int numIp = 2; final int numIp = 2;
// 范围为空字符串或者与IP相同时返回真
if (rangeIp.length() == 0 || rangeIp.equals(ipAddr)) {
return true;
}
String[] ipList = rangeIp.split("-"); String[] ipList = rangeIp.split("-");
if (ipList.length != numIp) { if (ipList.length != numIp) {
@ -85,16 +91,35 @@ public enum IPAddrType {
* @return the boolean * @return the boolean
*/ */
public static boolean isIpAddress(String ipAddr) { public static boolean isIpAddress(String ipAddr) {
if (!ipAddr.contains(GlobalVar.STRING_IPV4_FLAG) && !ipAddr.contains(GlobalVar.STRING_IPV6_FLAG)) {
return false;
}
try {
IPAddressString str = new IPAddressString(ipAddr);
IPAddress addr = str.toAddress();
return true; final String ipv6PortChar = "[";
} catch (AddressStringException e) {
return false; int counts = ipAddr.length() - ipAddr.replaceAll(GlobalVar.STRING_IPV6_FLAG, "").length();
String ipv4Regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
String ipv6Regex = "^(([\\da-fA-F]{1,4}):){8}$";
switch (counts) {
// ipv4
case 0:
return ipAddr.matches(ipv4Regex);
// v4 + port
case 1:
String ipv4 = ipAddr.substring(0, ipAddr.lastIndexOf(GlobalVar.STRING_IPV6_FLAG));
return ipv4.matches(ipv4Regex);
default:
// Ip v6 + port
if (ipAddr.contains("[")) {
String ipv6 = ipAddr.substring(1, ipAddr.lastIndexOf(ipv6PortChar));
return ipv6.matches(ipv6Regex);
} else {
return ipAddr.matches(ipv6Regex);
} }
} }
} }
}

View File

@ -0,0 +1,20 @@
package com.dispose.config;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* The type Dp tech configure.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "dptech")
public class DpTechConfigure {
private String soapConnTimeout;
private String soapRecvTimeout;
}

View File

@ -20,12 +20,35 @@ public class SetupInit implements CommandLineRunner {
@Resource @Resource
private DisposeConfigure disposeConfigure; private DisposeConfigure disposeConfigure;
@Resource
private DpTechConfigure dpTechConfigure;
@Resource @Resource
private DisposeNodeManager disposeNodeManager; private DisposeNodeManager disposeNodeManager;
@Resource @Resource
private TaskService taskService; private TaskService taskService;
private void loadConfigure() {
try {
GlobalVar.SOAP_CONNECT_TIMEOUT = Integer.parseInt(dpTechConfigure.getSoapConnTimeout());
} catch(Exception ex) {
log.error("load SOAP_CONNECT_TIMEOUT configure error: {}", ex.getMessage());
}
try {
GlobalVar.SOAP_RECEIVE_TIMEOUT = Integer.parseInt(dpTechConfigure.getSoapRecvTimeout());
} catch(Exception ex) {
log.error("load SOAP_RECEIVE_TIMEOUT configure error: {}", ex.getMessage());
}
try {
GlobalVar.IS_CHECK_REQUEST_TIMEOUT = Boolean.parseBoolean(disposeConfigure.getCheckProtocolTimeout());
} catch(Exception ex) {
log.error("load IS_CHECK_REQUEST_TIMEOUT configure error: {}", ex.getMessage());
}
}
/** /**
* Run. * Run.
* *
@ -34,7 +57,7 @@ public class SetupInit implements CommandLineRunner {
@Override @Override
public void run(String... args) { public void run(String... args) {
// 系统初始化入口 // 系统初始化入口
GlobalVar.IS_CHECK_REQUEST_TIMEOUT = Boolean.parseBoolean(disposeConfigure.getCheckProtocolTimeout()); loadConfigure();
disposeNodeManager.loadDisposeNodeFromDatabase(); disposeNodeManager.loadDisposeNodeFromDatabase();
taskService.loadTaskFromDatabase(); taskService.loadTaskFromDatabase();
} }

View File

@ -5,6 +5,7 @@ import com.dispose.common.Helper;
import com.dispose.pojo.dto.ProtocolReqDTO; import com.dispose.pojo.dto.ProtocolReqDTO;
import com.dispose.pojo.dto.ProtocolRespDTO; import com.dispose.pojo.dto.ProtocolRespDTO;
import com.dispose.pojo.entity.DisposeDevice; import com.dispose.pojo.entity.DisposeDevice;
import com.dispose.pojo.vo.common.DisposeCapacity;
import com.dispose.pojo.vo.common.IDArrayReq; import com.dispose.pojo.vo.common.IDArrayReq;
import com.dispose.pojo.vo.common.TaskInfoData; import com.dispose.pojo.vo.common.TaskInfoData;
import com.dispose.pojo.vo.common.TaskInfoDetail; import com.dispose.pojo.vo.common.TaskInfoDetail;
@ -40,7 +41,6 @@ import javax.annotation.Resource;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
@ -83,7 +83,7 @@ public class DisposeNodeInfoController {
IDArrayReq reqInfo = mr.getRequestObject(IDArrayReq.class); IDArrayReq reqInfo = mr.getRequestObject(IDArrayReq.class);
if (reqInfo.getId() == null || Arrays.stream(reqInfo.getId()).anyMatch(Objects::isNull)) { if (reqInfo.getId() == null) {
log.error("Request id params error, error:{}", mr.getMsgContent()); log.error("Request id params error, error:{}", mr.getMsgContent());
return ProtocolRespDTO.result(ErrorCode.ERR_PARAMS); return ProtocolRespDTO.result(ErrorCode.ERR_PARAMS);
} }
@ -147,7 +147,7 @@ public class DisposeNodeInfoController {
IDArrayReq reqInfo = mr.getRequestObject(IDArrayReq.class); IDArrayReq reqInfo = mr.getRequestObject(IDArrayReq.class);
if (reqInfo.getId() == null || Arrays.stream(reqInfo.getId()).anyMatch(Objects::isNull)) { if (reqInfo.getId() == null) {
log.error("Request id params error, error:{}", mr.getMsgContent()); log.error("Request id params error, error:{}", mr.getMsgContent());
return ProtocolRespDTO.result(ErrorCode.ERR_PARAMS); return ProtocolRespDTO.result(ErrorCode.ERR_PARAMS);
} }
@ -210,7 +210,7 @@ public class DisposeNodeInfoController {
IDArrayReq reqInfo = mr.getRequestObject(IDArrayReq.class); IDArrayReq reqInfo = mr.getRequestObject(IDArrayReq.class);
if (reqInfo.getId() == null || Arrays.stream(reqInfo.getId()).anyMatch(Objects::isNull)) { if (reqInfo.getId() == null) {
log.error("Request id params error, error:{}", mr.getMsgContent()); log.error("Request id params error, error:{}", mr.getMsgContent());
return ProtocolRespDTO.result(ErrorCode.ERR_PARAMS); return ProtocolRespDTO.result(ErrorCode.ERR_PARAMS);
} }
@ -276,7 +276,7 @@ public class DisposeNodeInfoController {
IDArrayReq reqInfo = mr.getRequestObject(IDArrayReq.class); IDArrayReq reqInfo = mr.getRequestObject(IDArrayReq.class);
if (reqInfo.getId() == null || Arrays.stream(reqInfo.getId()).anyMatch(Objects::isNull)) { if (reqInfo.getId() == null) {
log.error("Request id params error, error:{}", mr.getMsgContent()); log.error("Request id params error, error:{}", mr.getMsgContent());
return ProtocolRespDTO.result(ErrorCode.ERR_PARAMS); return ProtocolRespDTO.result(ErrorCode.ERR_PARAMS);
} }
@ -316,7 +316,7 @@ public class DisposeNodeInfoController {
rspInfo.getItems().add(cpData); rspInfo.getItems().add(cpData);
}); });
return ProtocolRespDTO.result(err, rspInfo); return ProtocolRespDTO.result(err, rspInfo, DisposeCapacity.CapacityView.class);
} }
/** /**
@ -342,7 +342,7 @@ public class DisposeNodeInfoController {
IDArrayReq reqInfo = mr.getRequestObject(IDArrayReq.class); IDArrayReq reqInfo = mr.getRequestObject(IDArrayReq.class);
if (reqInfo.getId() == null || Arrays.stream(reqInfo.getId()).anyMatch(Objects::isNull)) { if (reqInfo.getId() == null) {
log.error("Request id params error, error:{}", mr.getMsgContent()); log.error("Request id params error, error:{}", mr.getMsgContent());
return ProtocolRespDTO.result(ErrorCode.ERR_PARAMS); return ProtocolRespDTO.result(ErrorCode.ERR_PARAMS);
} }
@ -381,7 +381,8 @@ public class DisposeNodeInfoController {
rspInfo.getItems().add(cpData); rspInfo.getItems().add(cpData);
}); });
return ProtocolRespDTO.result(err, rspInfo); return ProtocolRespDTO.result(err, rspInfo, DisposeCapacity.DependIpView.class);
} }
/** /**
@ -412,7 +413,7 @@ public class DisposeNodeInfoController {
IDArrayReq reqInfo = mr.getRequestObject(IDArrayReq.class); IDArrayReq reqInfo = mr.getRequestObject(IDArrayReq.class);
if (reqInfo.getId() == null || Arrays.stream(reqInfo.getId()).anyMatch(Objects::isNull)) { if (reqInfo.getId() == null) {
log.error("Request id params error, error:{}", mr.getMsgContent()); log.error("Request id params error, error:{}", mr.getMsgContent());
return ProtocolRespDTO.result(ErrorCode.ERR_PARAMS); return ProtocolRespDTO.result(ErrorCode.ERR_PARAMS);
} }
@ -484,7 +485,7 @@ public class DisposeNodeInfoController {
IDArrayReq reqInfo = mr.getRequestObject(IDArrayReq.class); IDArrayReq reqInfo = mr.getRequestObject(IDArrayReq.class);
if (reqInfo.getId() == null || Arrays.stream(reqInfo.getId()).anyMatch(Objects::isNull)) { if (reqInfo.getId() == null) {
log.error("Request id params error, error:{}", mr.getMsgContent()); log.error("Request id params error, error:{}", mr.getMsgContent());
return ProtocolRespDTO.result(ErrorCode.ERR_PARAMS); return ProtocolRespDTO.result(ErrorCode.ERR_PARAMS);
} }
@ -553,7 +554,7 @@ public class DisposeNodeInfoController {
IDArrayReq reqInfo = mr.getRequestObject(IDArrayReq.class); IDArrayReq reqInfo = mr.getRequestObject(IDArrayReq.class);
if (reqInfo.getId() == null || Arrays.stream(reqInfo.getId()).anyMatch(Objects::isNull)) { if (reqInfo.getId() == null) {
log.error("Request id params error, error:{}", mr.getMsgContent()); log.error("Request id params error, error:{}", mr.getMsgContent());
return ProtocolRespDTO.result(ErrorCode.ERR_PARAMS); return ProtocolRespDTO.result(ErrorCode.ERR_PARAMS);
} }
@ -581,12 +582,12 @@ public class DisposeNodeInfoController {
taskData.setMessage(ErrorCode.ERR_NOSUCHTASK.getMsg()); taskData.setMessage(ErrorCode.ERR_NOSUCHTASK.getMsg());
} else { } else {
runTasks.forEach(k -> { runTasks.forEach(k -> {
int diff = Helper.getTimestampDiff(k.getBeginTime(), k.getPlanEndTime()); int diff = Helper.getTimestampDiff(k.getCreateTime(), k.getPlanEndTime());
TaskInfoData taskInfoData = TaskInfoData.builder() TaskInfoData taskInfoData = TaskInfoData.builder()
.taskId(k.getId().toString()) .taskId(k.getId().toString())
.type(k.getType()) .type(k.getType())
.startTime(Helper.getTimestampSecond(k.getBeginTime())) .startTime(Helper.getTimestampSecond(k.getCreateTime()))
.disposeTime(diff) .disposeTime(diff)
.disposeIp(k.getDisposeIp()) .disposeIp(k.getDisposeIp())
.flowAttack(0) .flowAttack(0)
@ -642,7 +643,7 @@ public class DisposeNodeInfoController {
IDArrayReq reqInfo = mr.getRequestObject(IDArrayReq.class); IDArrayReq reqInfo = mr.getRequestObject(IDArrayReq.class);
if (reqInfo.getId() == null || Arrays.stream(reqInfo.getId()).anyMatch(Objects::isNull)) { if (reqInfo.getId() == null) {
log.error("Request id params error, error:{}", mr.getMsgContent()); log.error("Request id params error, error:{}", mr.getMsgContent());
return ProtocolRespDTO.result(ErrorCode.ERR_PARAMS); return ProtocolRespDTO.result(ErrorCode.ERR_PARAMS);
} }
@ -670,12 +671,12 @@ public class DisposeNodeInfoController {
taskData.setMessage(ErrorCode.ERR_NOSUCHTASK.getMsg()); taskData.setMessage(ErrorCode.ERR_NOSUCHTASK.getMsg());
} else { } else {
runTasks.forEach(k -> { runTasks.forEach(k -> {
int diff = Helper.getTimestampDiff(k.getBeginTime(), k.getPlanEndTime()); int diff = Helper.getTimestampDiff(k.getCreateTime(), k.getPlanEndTime());
TaskInfoData taskInfoData = TaskInfoData.builder() TaskInfoData taskInfoData = TaskInfoData.builder()
.taskId(k.getId().toString()) .taskId(k.getId().toString())
.type(k.getType()) .type(k.getType())
.startTime(Helper.getTimestampSecond(k.getBeginTime())) .startTime(Helper.getTimestampSecond(k.getCreateTime()))
.disposeTime(diff) .disposeTime(diff)
.disposeIp(k.getDisposeIp()) .disposeIp(k.getDisposeIp())
.currentStatus(taskService.taskIsRunning(k) ? 0 : 1) .currentStatus(taskService.taskIsRunning(k) ? 0 : 1)

View File

@ -29,9 +29,7 @@ import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Objects;
/** /**
* The type Dispose node manager controller. * The type Dispose node manager controller.
@ -94,6 +92,9 @@ public class DisposeNodeManagerController {
.manufacturer(v.getManufacturer()) .manufacturer(v.getManufacturer())
.model(v.getModel()) .model(v.getModel())
.version(v.getVersion()) .version(v.getVersion())
.userName(v.getUserName())
.password(v.getPassword())
.url(v.getUrl())
.build(); .build();
MulReturnType<ErrorCode, String> ret; MulReturnType<ErrorCode, String> ret;
try { try {
@ -144,13 +145,12 @@ public class DisposeNodeManagerController {
IDArrayReq reqInfo = mr.getRequestObject(IDArrayReq.class); IDArrayReq reqInfo = mr.getRequestObject(IDArrayReq.class);
if (reqInfo.getId() == null || Arrays.stream(reqInfo.getId()).anyMatch(Objects::isNull)) { if (reqInfo.getId() == null) {
log.error("Request params error, error:{}", mr.getMsgContent()); log.error("Request params error, error:{}", mr.getMsgContent());
return ProtocolRespDTO.result(ErrorCode.ERR_PARAMS); return ProtocolRespDTO.result(ErrorCode.ERR_PARAMS);
} }
if (reqInfo.getId().length > 1 if (reqInfo.getId()[0].length() == 0) {
|| Arrays.stream(reqInfo.getId()).anyMatch(v -> v.length() == 0)) {
log.error("Prohibit deleting multiple devices at the same time"); log.error("Prohibit deleting multiple devices at the same time");
return ProtocolRespDTO.result(ErrorCode.ERR_REMOVEMORE); return ProtocolRespDTO.result(ErrorCode.ERR_REMOVEMORE);
} }

View File

@ -44,7 +44,6 @@ import java.time.ZoneId;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -178,8 +177,7 @@ public class DisposeTaskController {
IDArrayReq reqInfo = mr.getRequestObject(IDArrayReq.class); IDArrayReq reqInfo = mr.getRequestObject(IDArrayReq.class);
if (reqInfo.getTaskId() == null if (reqInfo.getTaskId() == null
|| Arrays.stream(reqInfo.getTaskId()).anyMatch(v -> v.length() == 0) || Arrays.stream(reqInfo.getTaskId()).anyMatch(v -> v.length() == 0)) {
|| Arrays.stream(reqInfo.getTaskId()).anyMatch(Objects::isNull)) {
log.error("Request taskId params error, error:{}", mr.getMsgContent()); log.error("Request taskId params error, error:{}", mr.getMsgContent());
return ProtocolRespDTO.result(ErrorCode.ERR_PARAMS); return ProtocolRespDTO.result(ErrorCode.ERR_PARAMS);
} }
@ -486,7 +484,7 @@ public class DisposeTaskController {
GetTaskReq reqInfo = mr.getRequestObject(GetTaskReq.class); GetTaskReq reqInfo = mr.getRequestObject(GetTaskReq.class);
if (reqInfo.getId() == null || Arrays.stream(reqInfo.getId()).anyMatch(Objects::isNull)) { if (reqInfo.getId() == null) {
log.error("Request id params error, error:{}", mr.getMsgContent()); log.error("Request id params error, error:{}", mr.getMsgContent());
return ProtocolRespDTO.result(ErrorCode.ERR_PARAMS); return ProtocolRespDTO.result(ErrorCode.ERR_PARAMS);
} }
@ -516,11 +514,11 @@ public class DisposeTaskController {
taskService.getNodeAllRunningTask(v.getId()).forEach(k -> { taskService.getNodeAllRunningTask(v.getId()).forEach(k -> {
if (v.getType().equals(reqInfo.getType()) if (v.getType().equals(reqInfo.getType())
|| reqInfo.getType() == DeviceCapacity.ALLCAPACITY.getCode()) { || reqInfo.getType() == DeviceCapacity.ALLCAPACITY.getCode()) {
int diff = Helper.getTimestampDiff(k.getBeginTime(), k.getPlanEndTime()); int diff = Helper.getTimestampDiff(k.getCreateTime(), k.getPlanEndTime());
TaskInfoData taskInfoData = TaskInfoData.builder() TaskInfoData taskInfoData = TaskInfoData.builder()
.taskId(k.getId().toString()) .taskId(k.getId().toString())
.type(k.getType()) .type(k.getType())
.startTime(Helper.getTimestampSecond(k.getBeginTime())) .startTime(Helper.getTimestampSecond(k.getCreateTime()))
.disposeTime(diff) .disposeTime(diff)
.disposeIp(k.getDisposeIp()) .disposeIp(k.getDisposeIp())
.flowAttack(0) .flowAttack(0)
@ -585,7 +583,7 @@ public class DisposeTaskController {
IDArrayReq reqInfo = mr.getRequestObject(IDArrayReq.class); IDArrayReq reqInfo = mr.getRequestObject(IDArrayReq.class);
if (reqInfo.getTaskId() == null || Arrays.stream(reqInfo.getTaskId()).anyMatch(Objects::isNull)) { if (reqInfo.getTaskId() == null) {
log.error("Request taskId params error, error:{}", mr.getMsgContent()); log.error("Request taskId params error, error:{}", mr.getMsgContent());
return ProtocolRespDTO.result(ErrorCode.ERR_PARAMS); return ProtocolRespDTO.result(ErrorCode.ERR_PARAMS);
} }
@ -600,12 +598,12 @@ public class DisposeTaskController {
.collect(Collectors.toList()); .collect(Collectors.toList());
valuableData.forEach(v -> { valuableData.forEach(v -> {
int diff = Helper.getTimestampDiff(v.getBeginTime(), v.getPlanEndTime()); int diff = Helper.getTimestampDiff(v.getCreateTime(), v.getPlanEndTime());
TaskInfoData taskInfoData = TaskInfoData.builder() TaskInfoData taskInfoData = TaskInfoData.builder()
.taskId(v.getId().toString()) .taskId(v.getId().toString())
.type(v.getType()) .type(v.getType())
.startTime(Helper.getTimestampSecond(v.getBeginTime())) .startTime(Helper.getTimestampSecond(v.getCreateTime()))
.disposeTime(diff / 60) .disposeTime(diff / 60)
.disposeIp(v.getDisposeIp()) .disposeIp(v.getDisposeIp())
.attackType(Helper.attackStringToArray(v.getAttackType())) .attackType(Helper.attackStringToArray(v.getAttackType()))

View File

@ -2,9 +2,10 @@ package com.dispose.dispose;
import com.dispose.common.DisposeDeviceType; import com.dispose.common.DisposeDeviceType;
import com.dispose.common.GlobalVar; import com.dispose.common.GlobalVar;
import com.dispose.common.IPAddrType;
import com.dispose.dispose.impl.DpTechImpl; import com.dispose.dispose.impl.DpTechImpl;
import com.dispose.dispose.impl.HaoHanImpl;
import com.dispose.dispose.impl.VirtualDeviceImpl; import com.dispose.dispose.impl.VirtualDeviceImpl;
import com.dispose.pojo.entity.DisposeDevice;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@ -21,37 +22,35 @@ public class DeviceRouter {
return devType + "_" + ipAddr; return devType + "_" + ipAddr;
} }
/** public static DisposeEntryManager deviceRouterFactory(DisposeDevice device) {
* Device router factory dispose entry manager.
* String mapKey = getMapKey(device.getType(), device.getIpAddr());
* @param devType the dev type
* @param ipAddr the ip addr
* @param ipType the ip type
* @return the dispose entry manager
*/
public static DisposeEntryManager deviceRouterFactory(int devType, String ipAddr, IPAddrType ipType) {
String mapKey = getMapKey(devType, ipAddr);
// 判断缓存中是否创建过对象如果创建过直接从缓存中获取 // 判断缓存中是否创建过对象如果创建过直接从缓存中获取
if (DEVICE_CACHE_MAP.containsKey(mapKey)) { if (DEVICE_CACHE_MAP.containsKey(mapKey)) {
return DEVICE_CACHE_MAP.get(mapKey); return DEVICE_CACHE_MAP.get(mapKey);
} else { } else {
DisposeEntryManager dev = null;
// 第一次访问创建新对象并缓存 // 第一次访问创建新对象并缓存
if (GlobalVar.USED_VIRTUAL_DISPOSE_MODE) { if (GlobalVar.USED_VIRTUAL_DISPOSE_MODE) {
// 虚拟设备供调试业务使用 // 虚拟设备供调试业务使用
DisposeEntryManager dev = new VirtualDeviceImpl(ipAddr); dev = new VirtualDeviceImpl(device);
DEVICE_CACHE_MAP.put(mapKey, dev); } else if (device.getType() == DisposeDeviceType.DPTECH_UMC.getCode()) {
return dev;
} else if (devType == DisposeDeviceType.DPTECH_UMC.getCode()) {
// 迪普设备 // 迪普设备
DisposeEntryManager dev = new DpTechImpl(ipAddr); dev = new DpTechImpl(device);
} else if (device.getType() == DisposeDeviceType.HAOHAN_PLATFORM.getCode()) {
// 浩瀚设备
dev = new HaoHanImpl(device);
}
if (dev != null) {
DEVICE_CACHE_MAP.put(mapKey, dev); DEVICE_CACHE_MAP.put(mapKey, dev);
return dev; return dev;
} }
} }
// 始终返回一个虚拟设备作为默认设备 // 始终返回一个虚拟设备作为默认设备
DisposeEntryManager dev = new VirtualDeviceImpl(ipAddr); DisposeEntryManager dev = new VirtualDeviceImpl(device);
DEVICE_CACHE_MAP.put(mapKey, dev); DEVICE_CACHE_MAP.put(mapKey, dev);
return dev; return dev;
} }
@ -63,7 +62,18 @@ public class DeviceRouter {
* @param ipAddr the ip addr * @param ipAddr the ip addr
* @return the dispose entry manager * @return the dispose entry manager
*/ */
public static DisposeEntryManager deviceRouterFactory(int devType, String ipAddr) { public static DisposeEntryManager getDeviceRouterFactory(int devType, String ipAddr) {
return deviceRouterFactory(devType, ipAddr, IPAddrType.IPV4_TYPE);
String mapKey = getMapKey(devType, ipAddr);
// 判断缓存中是否创建过对象如果创建过直接从缓存中获取
if (DEVICE_CACHE_MAP.containsKey(mapKey)) {
return DEVICE_CACHE_MAP.get(mapKey);
} else {
// 始终返回一个虚拟设备作为默认设备
DisposeEntryManager dev = new VirtualDeviceImpl(DisposeDevice.builder().build());
DEVICE_CACHE_MAP.put(mapKey, dev);
return dev;
}
} }
} }

View File

@ -1,10 +1,12 @@
package com.dispose.dispose; package com.dispose.dispose;
import com.dispose.common.CleanTaskStatus;
import com.dispose.common.DeviceCapacity; import com.dispose.common.DeviceCapacity;
import com.dispose.common.ErrorCode; import com.dispose.common.ErrorCode;
import com.dispose.dispose.po.DeviceInfo; import com.dispose.dispose.po.DeviceInfo;
import com.dispose.pojo.po.DisposeDeviceCapacity; import com.dispose.pojo.po.DisposeDeviceCapacity;
import com.dispose.pojo.po.MulReturnType;
import java.util.List; import java.util.List;
@ -15,22 +17,24 @@ import java.util.List;
*/ */
public interface DisposeEntryManager { public interface DisposeEntryManager {
/** /**
* Run dispose error code. * Run dispose mul return type.
* *
* @param ip the ip * @param ip the ip
* @param type the type * @param type the type
* @return the error code * @param duration the duration
* @return the mul return type
*/ */
ErrorCode runDispose(String ip, DeviceCapacity type); MulReturnType<ErrorCode, Long> runDispose(String ip, DeviceCapacity type, Long duration);
/** /**
* Stop dispose error code. * Stop dispose mul return type.
* *
* @param ipAddr the ip addr * @param ipAddr the ip addr
* @param type the type * @param type the type
* @return the error code * @param devTaskId the dev task id
* @return the mul return type
*/ */
ErrorCode stopDispose(String ipAddr, DeviceCapacity type); MulReturnType<ErrorCode, Long> stopDispose(String ipAddr, DeviceCapacity type, Long devTaskId);
/** /**
@ -91,8 +95,11 @@ public interface DisposeEntryManager {
*/ */
DeviceInfo getDeviceInfo(); DeviceInfo getDeviceInfo();
//public NtcRequestResultInfo stopAbnormalTask(String abnormalIp, int attackType, int direction); /**
* Gets device clean task status.
//public NtcRequestResultInfo startAbnormalTask(String abnormalIp, int attackType, int direction); * @param devTaskId device Task Id.
*
* @return the task status
*/
CleanTaskStatus getCleanTaskStatus(Long devTaskId);
} }

View File

@ -1,19 +1,16 @@
package com.dispose.dispose.impl; package com.dispose.dispose.impl;
import com.dispose.common.ConstValue; import com.dispose.common.*;
import com.dispose.common.DeviceCapacity;
import com.dispose.common.DpTechAttackType;
import com.dispose.common.ErrorCode;
import com.dispose.common.GlobalVar;
import com.dispose.common.IPAddrType;
import com.dispose.config.DisposeConfigure; import com.dispose.config.DisposeConfigure;
import com.dispose.dispose.DisposeEntryManager; import com.dispose.dispose.DisposeEntryManager;
import com.dispose.dispose.po.DeviceInfo; import com.dispose.dispose.po.DeviceInfo;
import com.dispose.interceptor.SoapPasswordCallbackHandler; import com.dispose.pojo.entity.DisposeDevice;
import com.dispose.pojo.po.DisposeDeviceCapacity; import com.dispose.pojo.po.DisposeDeviceCapacity;
import com.dispose.pojo.po.MulReturnType;
import com.dptech.dispose.AbnormalFlowCleaningServicePortType; import com.dptech.dispose.AbnormalFlowCleaningServicePortType;
import com.dptech.dispose.ArrayOfProtectionObjectDataForService; import com.dptech.dispose.ArrayOfProtectionObjectDataForService;
import com.dptech.dispose.NtcRequestResultInfo; import com.dptech.dispose.NtcRequestResultInfo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.cxf.endpoint.Client; import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy; import org.apache.cxf.frontend.ClientProxy;
@ -25,11 +22,13 @@ import org.apache.wss4j.dom.WSConstants;
import org.apache.wss4j.dom.handler.WSHandlerConstants; import org.apache.wss4j.dom.handler.WSHandlerConstants;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.xml.ws.BindingProvider;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.CompletableFuture;
/** /**
* The type Dp tech. * The type Dp tech.
@ -37,37 +36,44 @@ import java.util.Map;
* @author <huangxin@cmhi.chinamoblie.com> * @author <huangxin@cmhi.chinamoblie.com>
*/ */
@Slf4j @Slf4j
@Data
public class DpTechImpl implements DisposeEntryManager { public class DpTechImpl implements DisposeEntryManager {
private final AbnormalFlowCleaningServicePortType cleanTypePort; private final AbnormalFlowCleaningServicePortType cleanTypePort;
private String password;
@Resource @Resource
private DisposeConfigure disposeConfigure; private DisposeConfigure disposeConfigure;
/** /**
* Instantiates a new Dp tech. * Instantiates a new Dp tech.
* *
* @param ipAddr the ip addr * @param dev the dev
*/ */
public DpTechImpl(String ipAddr) { public DpTechImpl(DisposeDevice dev) {
JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean(); JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();
jaxWsProxyFactoryBean.setServiceClass(AbnormalFlowCleaningServicePortType.class); jaxWsProxyFactoryBean.setServiceClass(AbnormalFlowCleaningServicePortType.class);
jaxWsProxyFactoryBean.setAddress(String.format(ConstValue.SoapWrapperConst.NAMESPACE_URI, ipAddr)); jaxWsProxyFactoryBean.setAddress(String.format(dev.getUrl(), dev.getIpAddr()));
this.setPassword(dev.getPassword());
//WS-Security Head //WS-Security Head
Map<String, Object> outProps = new HashMap<>(); Map<String, Object> outProps = new HashMap<>();
outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN); outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);
// 配置用户名密码类型 // 配置用户名密码类型
outProps.put(WSHandlerConstants.USER, ConstValue.SoapWrapperConst.USER_NAME); outProps.put(WSHandlerConstants.USER, dev.getUserName());
outProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT); outProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT);
// 注册密码处理回调函数
outProps.put(WSHandlerConstants.PW_CALLBACK_CLASS, SoapPasswordCallbackHandler.class.getName());
// 添加WSSecure头部验证信息 // 添加WSSecure头部验证信息
jaxWsProxyFactoryBean.getOutInterceptors().add(new WSS4JOutInterceptor(outProps)); jaxWsProxyFactoryBean.getOutInterceptors().add(new WSS4JOutInterceptor(outProps));
this.cleanTypePort = (AbnormalFlowCleaningServicePortType) jaxWsProxyFactoryBean.create(); this.cleanTypePort = (AbnormalFlowCleaningServicePortType) jaxWsProxyFactoryBean.create();
Map<String, Object> ctx = ((BindingProvider) this.cleanTypePort).getRequestContext();
ctx.put("password", dev.getPassword());
ctx.put("username", dev.getUserName());
// 配置连接访问超时时间 // 配置连接访问超时时间
Client proxy = ClientProxy.getClient(this.cleanTypePort); Client proxy = ClientProxy.getClient(this.cleanTypePort);
HTTPConduit conduit = (HTTPConduit) proxy.getConduit(); HTTPConduit conduit = (HTTPConduit) proxy.getConduit();
@ -79,16 +85,6 @@ public class DpTechImpl implements DisposeEntryManager {
conduit.setClient(policy); conduit.setClient(policy);
} }
/**
* Instantiates a new Dp tech.
*
* @param ipAddr the ip addr
* @param type the type
*/
public DpTechImpl(String ipAddr, IPAddrType type) {
this(ipAddr);
}
/** /**
* Gets version. * Gets version.
* *
@ -197,18 +193,19 @@ public class DpTechImpl implements DisposeEntryManager {
} }
/** /**
* Run dispose error code. * Run dispose mul return type.
* *
* @param ip the ip * @param ip the ip
* @param type the type * @param type the type
* @return the error code * @param duration the duration
* @return the mul return type
*/ */
@Override @Override
public ErrorCode runDispose(String ip, DeviceCapacity type) { public MulReturnType<ErrorCode, Long> runDispose(String ip, DeviceCapacity type, Long duration) {
ErrorCode err = ErrorCode.ERR_OK; ErrorCode err = ErrorCode.ERR_OK;
// 当前系统接入设备仅仅支持流量清洗功能 // 当前系统接入设备仅仅支持流量清洗功能
if (type != DeviceCapacity.CLEANUP) { if (type != DeviceCapacity.CLEANUP) {
return ErrorCode.ERR_UNSUPPORT; return new MulReturnType<>(ErrorCode.ERR_UNSUPPORT, null);
} }
try { try {
@ -218,13 +215,18 @@ public class DpTechImpl implements DisposeEntryManager {
for (int d : new int[]{0, 1}) { for (int d : new int[]{0, 1}) {
// 遍历所有清洗类型 // 遍历所有清洗类型
for (DpTechAttackType t : DpTechAttackType.values()) { for (DpTechAttackType t : DpTechAttackType.values()) {
NtcRequestResultInfo ret = cleanTypePort.startAbnormalTaskForUMC(ip, t.getCode(), d); CompletableFuture.supplyAsync(() -> cleanTypePort.startAbnormalTaskForUMC(ip, t.getCode(), d))
.whenComplete((v, ex) -> {
if (ex != null) {
log.error("DPTech run dispose: {}, {}, error:{}", ip, t.getCode(), ex.getMessage());
} else {
log.debug("Cleanup: {} --> {}:{}", d, t.getReadme(), t.getCode()); log.debug("Cleanup: {} --> {}:{}", d, t.getReadme(), t.getCode());
if (ret.getResultRetVal() != ErrorCode.ERR_OK.getCode()) { if(v.getResultRetVal() != ErrorCode.ERR_OK.getCode()) {
log.error("Start {} cleanup task error: {}", ip, ret.getResultInfo()); log.error("DPTech run dispose {} error: {}", ip, v.getResultInfo());
return ErrorCode.ERR_CALLDEVICE;
} }
} }
});
}
} }
log.info("----Finish DPTech Start Cleanup Task: {}", ip); log.info("----Finish DPTech Start Cleanup Task: {}", ip);
@ -234,39 +236,52 @@ public class DpTechImpl implements DisposeEntryManager {
err = ErrorCode.ERR_SYSTEMEXCEPTION; err = ErrorCode.ERR_SYSTEMEXCEPTION;
} }
return err; return new MulReturnType<>(err, null);
} }
/** /**
* Stop dispose error code. * Stop dispose mul return type.
* *
* @param ipAddr the ip addr * @param ipAddr the ip addr
* @param type the type * @param type the type
* @return the error code * @param devTaskId the dev task id
* @return the mul return type
*/ */
@Override @Override
public ErrorCode stopDispose(String ipAddr, DeviceCapacity type) { public MulReturnType<ErrorCode, Long> stopDispose(String ipAddr, DeviceCapacity type, Long devTaskId) {
ErrorCode err = ErrorCode.ERR_OK;
if (type != DeviceCapacity.CLEANUP) { if (type != DeviceCapacity.CLEANUP) {
return ErrorCode.ERR_UNSUPPORT; return new MulReturnType<>(ErrorCode.ERR_UNSUPPORT, null);
} }
try { try {
log.info("++++Begging DPTech Stop Cleanup Task: {}", ipAddr); log.info("++++Begging DPTech Stop Cleanup Task: {}", ipAddr);
// 遍历入口出口两个方向 // 遍历入口出口两个方向
for (int d : new int[]{0, 1}) { for (int d : new int[]{0, 1}) {
// 遍历所有攻击类型的清洗任务
for (DpTechAttackType t : DpTechAttackType.values()) { for (DpTechAttackType t : DpTechAttackType.values()) {
NtcRequestResultInfo ret = cleanTypePort.stopAbnormalTaskForUMC(ipAddr, t.getCode(), d); CompletableFuture.supplyAsync(() -> cleanTypePort.stopAbnormalTaskForUMC(ipAddr, t.getCode(), d))
.whenComplete((v, ex) -> {
if (ex != null) {
log.error("DPTech stop dispose: {}, {}, error:{}", ipAddr, t.getCode(), ex.getMessage());
} else {
log.debug("Stop Cleanup: {} --> {}:{}", d, t.getReadme(), t.getCode());
if(v.getResultRetVal() != ErrorCode.ERR_OK.getCode()) {
log.error("DPTech stop dispose {} error: {}", ipAddr, v.getResultInfo());
}
}
});
} }
} }
log.info("----Finish DPTech Stop Cleanup Task: {}", ipAddr); log.info("----Finish DPTech Stop Cleanup Task: {}", ipAddr);
return ErrorCode.ERR_OK;
} catch (Exception ex) { } catch (Exception ex) {
log.error(ex.getMessage()); log.error(ex.getMessage());
log.error("----Error DPTech Stop Cleanup Task: {}", ipAddr); log.error("----Error DPTech Stop Cleanup Task: {}", ipAddr);
return ErrorCode.ERR_SYSTEMEXCEPTION; err = ErrorCode.ERR_SYSTEMEXCEPTION;
} }
return new MulReturnType<>(err, null);
} }
/** /**
@ -332,5 +347,16 @@ public class DpTechImpl implements DisposeEntryManager {
return ""; return "";
} }
} }
/**
* Gets device clean task status.
*
* @param devTaskId device Task Id.
* @return the task status
*/
@Override
public CleanTaskStatus getCleanTaskStatus(Long devTaskId) {
return CleanTaskStatus.DEVNOTSUPPORT;
}
} }

View File

@ -0,0 +1,281 @@
package com.dispose.dispose.impl;
import com.dispose.common.CleanTaskStatus;
import com.dispose.common.DeviceCapacity;
import com.dispose.common.ErrorCode;
import com.dispose.common.Http;
import com.dispose.dispose.DisposeEntryManager;
import com.dispose.dispose.po.DeviceInfo;
import com.dispose.pojo.entity.DisposeDevice;
import com.dispose.pojo.po.DisposeDeviceCapacity;
import com.dispose.pojo.po.MulReturnType;
import com.dispose.pojo.vo.haohan.CleanReq;
import com.dispose.pojo.vo.haohan.CleanRsp;
import com.dispose.pojo.vo.haohan.CommonRsp;
import com.dispose.pojo.vo.haohan.StopCleanReq;
import com.dispose.pojo.vo.haohan.CleanTaskStatusRsp;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.List;
/**
* The type Hao han.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
@Slf4j
public class HaoHanImpl implements DisposeEntryManager {
private final ObjectMapper objectMapper = new ObjectMapper();
private final String deviceAddress;
/**
* Instantiates a new Hao han.
*
* @param dev the dev
*/
public HaoHanImpl(DisposeDevice dev) {
deviceAddress = String.format(dev.getUrl(), dev.getIpAddr());
}
/**
* Run dispose mul return type.
*
* @param ip the ip
* @param type the type
* @param duration the duration
* @return the mul return type
*/
@Override
public MulReturnType<ErrorCode, Long> runDispose(String ip, DeviceCapacity type, Long duration) {
CleanReq req = CleanReq.builder()
.ip(ip)
.duration(duration)
.orderFrom("China Mobile")
.build();
log.info("++++Begging Haohan Start Cleanup Task: {}", ip);
try {
String ret = Http.postJson(deviceAddress + "/sendTow",
null,
objectMapper.writeValueAsString(req));
CleanRsp rsp = objectMapper.readValue(ret, CleanRsp.class);
if (rsp == null) {
log.error("----Error Haohan start clean {} server return error", ip);
return new MulReturnType<>(ErrorCode.ERR_HAOHAN_ERROR, null);
}
if (rsp.getState() != ErrorCode.ERR_OK.getCode()) {
log.error("----Error Haohan start clean {} return error: {}, {}", ip, rsp.getState(), rsp.getMsg());
return new MulReturnType<>(ErrorCode.ERR_HAOHAN_ERROR, null);
}
log.info("----Finish Haohan Start Cleanup Task: {}", ip);
return new MulReturnType<>(ErrorCode.ERR_OK, rsp.getCleanTaskId());
} catch (JsonProcessingException e) {
log.error("----Error Haohan Start Cleanup Task: {}", ip);
return new MulReturnType<>(ErrorCode.ERR_SYSTEMEXCEPTION, null);
}
}
/**
* Stop dispose mul return type.
*
* @param ipAddr the ip addr
* @param type the type
* @param devTaskId the dev task id
* @return the mul return type
*/
@Override
public MulReturnType<ErrorCode, Long> stopDispose(String ipAddr, DeviceCapacity type, Long devTaskId) {
StopCleanReq req = StopCleanReq.builder()
.cleanTaskId(devTaskId)
.orderFrom("China Mobile")
.build();
log.info("++++Begging Haohan Stop Cleanup Task: {}", devTaskId);
try {
String ret = Http.postJson(deviceAddress + "/delTow",
null,
objectMapper.writeValueAsString(req));
CommonRsp rsp = objectMapper.readValue(ret, CommonRsp.class);
if (rsp == null) {
log.error("----Error Haohan stop task{} server return error", devTaskId);
return new MulReturnType<>(ErrorCode.ERR_HAOHAN_ERROR, null);
}
log.info("----Finish Haohan Stop Cleanup Task: {}", devTaskId);
return new MulReturnType<>(ErrorCode.ERR_OK, null);
} catch (JsonProcessingException e) {
log.error("----Error Haohan Stop Cleanup Task: {}", devTaskId);
return new MulReturnType<>(ErrorCode.ERR_SYSTEMEXCEPTION, null);
}
}
/**
* Gets version.
*
* @return the version
*/
@Override
public String getVersion() {
return "Not Support";
}
/**
* Gets device info.
*
* @return the device info
*/
@Override
public DeviceInfo getDeviceInfo() {
// 当前设备接口不支持返回模拟数据
return DeviceInfo.builder()
.vendor("HaoHan")
.model("Unknown")
.firmware("Unknown")
.os("Linux Server")
.kernel("Linux")
.arch("x86_64")
.memory(-1)
.freeMemory(-1)
.cpuUsed(-1)
.build();
}
/**
* Gets device capacity.
*
* @return the device capacity
*/
@Override
public List<DisposeDeviceCapacity> getDeviceCapacity() {
List<DisposeDeviceCapacity> capList = new ArrayList<>();
// 保存清洗能力信息
capList.add(DisposeDeviceCapacity.builder()
// 清洗能力
.capacity(DeviceCapacity.CLEANUP.getCode())
.tolFlowCapacity(0)
// IPv4范围
.protectIpV4(new String[]{""})
// IPv6范围
.protectIpV6(new String[]{""})
.build());
return capList;
}
/**
* Gets device link status.
*
* @return the device link status
*/
@Override
public boolean getDeviceLinkStatus() {
try {
String jsonRequest = "{\"cleanTaskId\":\"-1\"}";
//"http://10.88.77.88:18080/DDoSClean/clean/cleanTaskFlow"
Http.postJson(deviceAddress + "cleanTaskFlow",
null,
jsonRequest);
return true;
} catch (Exception ex) {
log.error(ex.getMessage());
}
return false;
}
/**
* Gets all detection object.
*
* @param <T> the type parameter
* @return the all detection object
*/
@Override
public <T> T getAllDetectionObject() {
return null;
}
/**
* Gets all protection object.
*
* @param <T> the type parameter
* @return the all protection object
*/
@Override
public <T> T getAllProtectionObject() {
return null;
}
/**
* Gets protect devices.
*
* @return the protect devices
*/
@Override
public String getProtectDevices() {
return null;
}
/**
* Gets detection devices.
*
* @return the detection devices
*/
@Override
public String getDetectionDevices() {
return null;
}
/**
* Gets device clean task status.
*
* @param devTaskId device Task Id.
* @return the task status
*/
@Override
public CleanTaskStatus getCleanTaskStatus(Long devTaskId) {
try {
String jsonRequest = String.valueOf(devTaskId);
//"http://10.88.77.88:18080/DDoSClean/clean/getCleanTaskState"
String ret = Http.postJson(deviceAddress + "getCleanTaskState",
null,
jsonRequest);
CleanTaskStatusRsp rsp = objectMapper.readValue(ret, CleanTaskStatusRsp.class);
if (rsp == null) {
log.error("----Error Haohan get task{} status error", devTaskId);
return CleanTaskStatus.HAOHANERROR;
}
if (rsp.getState() == 0) {
if (rsp.getCleanTaskState() == 1) {
log.error("----Get task {}, status {}", devTaskId, rsp.getCleanTaskState());
return CleanTaskStatus.CLEANING;
}
log.error("----Get task {}, status {}", devTaskId, rsp.getCleanTaskState());
return CleanTaskStatus.ENDOFCLEANING;
} else {
log.error("----Get task {}, status {}", devTaskId, rsp.getCleanTaskState());
return CleanTaskStatus.NOTASK;
}
} catch (Exception ex) {
log.error(ex.getMessage());
return CleanTaskStatus.HAOHANERROR;
}
}
}

View File

@ -1,12 +1,14 @@
package com.dispose.dispose.impl; package com.dispose.dispose.impl;
import com.dispose.common.CleanTaskStatus;
import com.dispose.common.DeviceCapacity; import com.dispose.common.DeviceCapacity;
import com.dispose.common.ErrorCode; import com.dispose.common.ErrorCode;
import com.dispose.common.GlobalVar; import com.dispose.common.GlobalVar;
import com.dispose.common.IPAddrType;
import com.dispose.dispose.DisposeEntryManager; import com.dispose.dispose.DisposeEntryManager;
import com.dispose.dispose.po.DeviceInfo; import com.dispose.dispose.po.DeviceInfo;
import com.dispose.pojo.entity.DisposeDevice;
import com.dispose.pojo.po.DisposeDeviceCapacity; import com.dispose.pojo.po.DisposeDeviceCapacity;
import com.dispose.pojo.po.MulReturnType;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -17,47 +19,40 @@ import java.util.List;
* @author <huangxin@cmhi.chinamoblie.com> * @author <huangxin@cmhi.chinamoblie.com>
*/ */
public class VirtualDeviceImpl implements DisposeEntryManager { public class VirtualDeviceImpl implements DisposeEntryManager {
/**
* Instantiates a new Virtual device.
*
* @param ipAddr the ip addr
*/
public VirtualDeviceImpl(String ipAddr) {
}
/** /**
* Instantiates a new Virtual device. * Instantiates a new Virtual device.
* *
* @param ipAddr the ip addr * @param dev the dev
* @param type the type
*/ */
public VirtualDeviceImpl(String ipAddr, IPAddrType type) { public VirtualDeviceImpl(DisposeDevice dev) {
} }
/** /**
* Run dispose error code. * Run dispose mul return type.
* *
* @param ip the ip * @param ip the ip
* @param type the type * @param type the type
* @return the error code * @param duration the duration
* @return the mul return type
*/ */
@Override @Override
public ErrorCode runDispose(String ip, DeviceCapacity type) { public MulReturnType<ErrorCode, Long> runDispose(String ip, DeviceCapacity type, Long duration) {
return ErrorCode.ERR_OK; return new MulReturnType<>(ErrorCode.ERR_OK, null);
} }
/** /**
* Stop dispose error code. * Stop dispose mul return type.
* *
* @param ipAddr the ip addr * @param ipAddr the ip addr
* @param type the type * @param type the type
* @return the error code * @param devTaskId the dev task id
* @return the mul return type
*/ */
@Override @Override
public ErrorCode stopDispose(String ipAddr, DeviceCapacity type) { public MulReturnType<ErrorCode, Long> stopDispose(String ipAddr, DeviceCapacity type, Long devTaskId) {
return ErrorCode.ERR_OK; return new MulReturnType<>(ErrorCode.ERR_OK, null);
} }
/** /**
@ -176,4 +171,15 @@ public class VirtualDeviceImpl implements DisposeEntryManager {
public String getProtectDevices() { public String getProtectDevices() {
return "192.168.10.10"; return "192.168.10.10";
} }
/**
* Gets device clean task status.
*
* @param devTaskId device Task Id.
* @return the task status
*/
@Override
public CleanTaskStatus getCleanTaskStatus(Long devTaskId) {
return CleanTaskStatus.DEVNOTSUPPORT;
}
} }

View File

@ -1,26 +0,0 @@
package com.dispose.interceptor;
import com.dispose.common.ConstValue;
import org.apache.wss4j.common.ext.WSPasswordCallback;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
/**
* The type Soap password callback handler.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
public class SoapPasswordCallbackHandler implements CallbackHandler {
/**
* Handle.
*
* @param callbacks the callbacks
*/
@Override
public void handle(Callback[] callbacks) {
// DPTech SOAP接口WSSecure头部密码填充
WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];
pc.setPassword(ConstValue.SoapWrapperConst.PASSWORD);
}
}

View File

@ -2,10 +2,12 @@ package com.dispose.manager.impl;
import com.dispose.common.ErrorCode; import com.dispose.common.ErrorCode;
import com.dispose.manager.TaskCacheManager; import com.dispose.manager.TaskCacheManager;
import com.dispose.mapper.DisposeTaskMapper;
import com.dispose.pojo.vo.common.TaskInfoDetail; import com.dispose.pojo.vo.common.TaskInfoDetail;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@ -20,6 +22,10 @@ import java.util.concurrent.ConcurrentHashMap;
public class TaskCacheManagerImpl implements TaskCacheManager { public class TaskCacheManagerImpl implements TaskCacheManager {
private final ConcurrentHashMap<Long, TaskInfoDetail> taskCacheMap = new ConcurrentHashMap<>(); private final ConcurrentHashMap<Long, TaskInfoDetail> taskCacheMap = new ConcurrentHashMap<>();
@Resource
private DisposeTaskMapper disposeTaskMapper;
/** /**
* Gets all task. * Gets all task.
* *
@ -107,6 +113,8 @@ public class TaskCacheManagerImpl implements TaskCacheManager {
// 更新状态 // 更新状态
taskCacheMap.get(id).setCurrentStatus(status); taskCacheMap.get(id).setCurrentStatus(status);
disposeTaskMapper.changeTaskCurrentStatus(id, status);
return ErrorCode.ERR_OK; return ErrorCode.ERR_OK;
} }
} }

View File

@ -51,13 +51,9 @@ public class UserAccountCacheManagerImpl implements UserAccountCacheManager {
if (username == null || username.length() == 0) { if (username == null || username.length() == 0) {
log.error("User {} not logged in", username); log.error("User {} not logged in", username);
return ErrorCode.ERR_LOGOUT; return ErrorCode.ERR_LOGOUT;
} else if (ConstValue.SoapWrapperConst.USER_NAME.equals(username)) {
// admin 用户具有操作权限
return ErrorCode.ERR_OK;
} }
log.error("User {} not enough permissions", username); return ErrorCode.ERR_OK;
return ErrorCode.ERR_PERMISSION;
} }
/** /**
@ -266,7 +262,6 @@ public class UserAccountCacheManagerImpl implements UserAccountCacheManager {
uc = UserAccountCache.builder() uc = UserAccountCache.builder()
.username(username) .username(username)
.token(createUserToken(username)) .token(createUserToken(username))
.lastAccess(System.currentTimeMillis())
.pwdErrTimes(0) .pwdErrTimes(0)
.lastAccess(System.currentTimeMillis()).build(); .lastAccess(System.currentTimeMillis()).build();

View File

@ -53,7 +53,7 @@ public interface DisposeTaskMapper extends Mapper<TaskInfoDetail>,
* @param id the id * @param id the id
* @return the task info by id * @return the task info by id
*/ */
TaskInfoDetail getTaskInfoById(Long id); TaskInfoDetail getTaskById(Long id);
/** /**
* Gets all task by dispose ip. * Gets all task by dispose ip.
@ -108,7 +108,7 @@ public interface DisposeTaskMapper extends Mapper<TaskInfoDetail>,
* @param type the type * @param type the type
* @return the task by task info * @return the task by task info
*/ */
List<TaskInfoDetail> getTaskByTaskInfo( List<TaskInfoDetail> getTaskByTaskDetail(
@Param("devId") Long devId, @Param("devId") Long devId,
@Param("userId") Long userId, @Param("userId") Long userId,
@Param("ipAddr") String ipAddr, @Param("ipAddr") String ipAddr,

View File

@ -0,0 +1,71 @@
package com.dispose.mapper;
import com.dispose.pojo.vo.common.TaskInfo;
import org.apache.ibatis.annotations.Param;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;
import java.util.List;
/**
* The interface Task info mapper.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
public interface TaskInfoMapper extends Mapper<TaskInfo>, MySqlMapper<TaskInfo> {
/**
* Add new task info.
*
* @param taskId the task id
* @param deviceId the device id
* @param externId the extern id
* @param status the status
*/
void addNewTaskInfo(@Param("taskId") Long taskId,
@Param("deviceId") Long deviceId,
@Param("externId") Long externId,
@Param("status") Long status);
/**
* Gets task info.
*
* @param taskId the task id
* @param deviceId the device id
* @return the task info
*/
TaskInfo getTaskInfo(@Param("taskId") Long taskId,
@Param("deviceId") Long deviceId);
/**
* Gets task info by task id.
*
* @param taskId the task id
* @return the task info by task id
*/
List<TaskInfo> getTaskInfoByTaskId(Long taskId);
/**
* Change task info status.
*
* @param id the id
* @param status the status
*/
void changeTaskInfoStatus(@Param("id") Long id,
@Param("status") Long status);
/**
* Gets task info current status.
*
* @param id the id
* @return the task info current status
*/
int getTaskInfoCurrentStatus(Long id);
/**
* Remove task by id.
*
* @param id the id
*/
void removeTaskInfoById(Long id);
}

View File

@ -34,6 +34,12 @@ public class ProtocolRespDTO extends BaseProtocolDTO {
return objectMapper.writeValueAsString(obj); return objectMapper.writeValueAsString(obj);
} }
private static <T> String getObjectJson(Object obj, Class<T> objType) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writerWithView(objType).writeValueAsString(obj);
}
/** /**
* Result protocol resp dto. * Result protocol resp dto.
* *
@ -76,6 +82,10 @@ public class ProtocolRespDTO extends BaseProtocolDTO {
return result(err, getObjectJson(obj), ConstValue.Protocol.CRYPTO_NONE); return result(err, getObjectJson(obj), ConstValue.Protocol.CRYPTO_NONE);
} }
public static <T> ProtocolRespDTO result(ErrorCode err, Object obj, Class<T> objType) throws JsonProcessingException {
return result(err, getObjectJson(obj, objType), ConstValue.Protocol.CRYPTO_NONE);
}
/** /**
* Result protocol resp dto. * Result protocol resp dto.
* *

View File

@ -54,6 +54,12 @@ public class DisposeDevice implements Serializable {
private String version; private String version;
private String userName;
private String password;
private String url;
private String readme; private String readme;
private Integer status; private Integer status;

View File

@ -24,6 +24,9 @@ public class NewNodeInfo {
private String name; private String name;
private String manufacturer; private String manufacturer;
private String model; private String model;
private String userName;
private String password;
private String url;
private String version; private String version;
private String readme; private String readme;
} }

View File

@ -0,0 +1,35 @@
package com.dispose.pojo.vo.common;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import tk.mybatis.mapper.annotation.NameStyle;
import tk.mybatis.mapper.code.Style;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* The type Task info.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "task_info")
@NameStyle(Style.normal)
public class TaskInfo {
private static final long serialVersionUID = 1L;
@Id
private Long id;
private Long taskId;
private Long deviceId;
private String beginTime;
private String endTime;
private Long externId;
private Long status;
}

View File

@ -31,7 +31,7 @@ public class TaskInfoDetail implements Serializable {
private Long accountId; private Long accountId;
private Integer type; private Integer type;
private String disposeIp; private String disposeIp;
private String beginTime; private String createTime;
private String planEndTime; private String planEndTime;
private String endTime; private String endTime;
private Integer flowDirection; private Integer flowDirection;

View File

@ -0,0 +1,23 @@
package com.dispose.pojo.vo.haohan;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* The type Clean req.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class CleanReq {
private String ip;
private String orderFrom;
private Long duration;
}

View File

@ -0,0 +1,23 @@
package com.dispose.pojo.vo.haohan;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
/**
* The type Clean rsp.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
@EqualsAndHashCode(callSuper = true)
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class CleanRsp extends CommonRsp {
private Long cleanTaskId;
}

View File

@ -0,0 +1,19 @@
package com.dispose.pojo.vo.haohan;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.*;
/**
* The type Clean rsp.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
@EqualsAndHashCode(callSuper = true)
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class CleanTaskStatusRsp extends CommonRsp {
private Long cleanTaskState;
}

View File

@ -0,0 +1,20 @@
package com.dispose.pojo.vo.haohan;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* The type Common rsp.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class CommonRsp {
private Integer state;
private String msg;
}

View File

@ -0,0 +1,24 @@
package com.dispose.pojo.vo.haohan;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* The type Stop clean req.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class StopCleanReq {
private Long cleanTaskId;
private String orderFrom;
}

View File

@ -77,5 +77,5 @@ public interface DisposeNodeManager {
* @param capacity the capacity * @param capacity the capacity
* @return the dispose device * @return the dispose device
*/ */
DisposeDevice getDisposeDevice(String ipAddr, DeviceCapacity capacity); List<DisposeDevice> getDisposeDevice(String ipAddr, DeviceCapacity capacity);
} }

View File

@ -6,6 +6,7 @@ import com.dispose.common.IPAddrType;
import com.dispose.dispose.DeviceRouter; import com.dispose.dispose.DeviceRouter;
import com.dispose.dispose.DisposeEntryManager; import com.dispose.dispose.DisposeEntryManager;
import com.dispose.mapper.DisposeDeviceMapper; import com.dispose.mapper.DisposeDeviceMapper;
import com.dispose.mapper.TaskInfoMapper;
import com.dispose.pojo.entity.DisposeDevice; import com.dispose.pojo.entity.DisposeDevice;
import com.dispose.pojo.po.DisposeDeviceCapacity; import com.dispose.pojo.po.DisposeDeviceCapacity;
import com.dispose.pojo.po.MulReturnType; import com.dispose.pojo.po.MulReturnType;
@ -35,6 +36,8 @@ public class DisposeNodeManagerImpl implements DisposeNodeManager {
private DisposeDeviceMapper disposeDeviceMapper; private DisposeDeviceMapper disposeDeviceMapper;
@Resource @Resource
private UserAccountService userAccountService; private UserAccountService userAccountService;
@Resource
private TaskInfoMapper taskInfoMapper;
/** /**
* Cleanup dispose node cache. * Cleanup dispose node cache.
@ -62,9 +65,10 @@ public class DisposeNodeManagerImpl implements DisposeNodeManager {
devList.forEach(v -> { devList.forEach(v -> {
// 对每个设备进行初始化 // 对每个设备进行初始化
DisposeEntryManager dp = DeviceRouter.deviceRouterFactory(v.getType(), //DisposeEntryManager dp = DeviceRouter.deviceRouterFactory(v.getType(),
v.getIpAddr(), IPAddrType.getIpAddrType(v.getIpAddr())); // v.getIpAddr(), IPAddrType.getIpAddrType(v.getIpAddr()));
DisposeEntryManager dp = DeviceRouter.deviceRouterFactory(v);
// 链接状态 // 链接状态
v.setLinkStatus(dp.getDeviceLinkStatus() ? 1 : 0); v.setLinkStatus(dp.getDeviceLinkStatus() ? 1 : 0);
// 版本信息 // 版本信息
@ -119,6 +123,9 @@ public class DisposeNodeManagerImpl implements DisposeNodeManager {
return ErrorCode.ERR_NOSUCHDEVICE; return ErrorCode.ERR_NOSUCHDEVICE;
} }
//删除task info表中的任务
taskInfoMapper.removeTaskInfoById(dev.getId());
// 删除数据库和缓存中内容 // 删除数据库和缓存中内容
disposeDeviceMapper.delDisposeDeviceByIp(ipAddr); disposeDeviceMapper.delDisposeDeviceByIp(ipAddr);
disposeDevMap.remove(ipAddr); disposeDevMap.remove(ipAddr);
@ -139,14 +146,13 @@ public class DisposeNodeManagerImpl implements DisposeNodeManager {
if (dev.getType() == null || dev.getIpAddr() == null if (dev.getType() == null || dev.getIpAddr() == null
|| dev.getIpAddr().length() == 0 || dev.getIpAddr().length() == 0
|| !IPAddrType.isIpAddress(dev.getIpAddr())) { || !IPAddrType.isIpAddress(dev.getIpAddr())) {
log.error("Add device error: type {}, ip {}", dev.getType(), dev.getIpAddr()); log.error("Add device error: type {}, ip {} url {}", dev.getType(), dev.getIpAddr(), dev.getUrl());
return new MulReturnType<>(ErrorCode.ERR_PARAMS, String.valueOf(-1)); return new MulReturnType<>(ErrorCode.ERR_PARAMS, String.valueOf(-1));
} }
try { try {
// 获取处置设备硬件访问接口 // 获取处置设备硬件访问接口
dp = DeviceRouter.deviceRouterFactory(dev.getType(), dp = DeviceRouter.deviceRouterFactory(dev);
dev.getIpAddr(), IPAddrType.getIpAddrType(dev.getIpAddr()));
// 判断设备是否在线 // 判断设备是否在线
if (!dp.getDeviceLinkStatus()) { if (!dp.getDeviceLinkStatus()) {
@ -256,8 +262,15 @@ public class DisposeNodeManagerImpl implements DisposeNodeManager {
* @return the dispose device * @return the dispose device
*/ */
@Override @Override
public DisposeDevice getDisposeDevice(String ipAddr, DeviceCapacity capacity) { public List<DisposeDevice> getDisposeDevice(String ipAddr, DeviceCapacity capacity) {
List<DisposeDevice> devList = new ArrayList<>();
for (DisposeDevice dev : disposeDevMap.values()) { for (DisposeDevice dev : disposeDevMap.values()) {
// 判断设备是否在线
if (dev.getLinkStatus() != 1) {
continue;
}
// 判断当前设备是否支持处置能力 // 判断当前设备是否支持处置能力
List<DisposeDeviceCapacity> capList = dev.getDevCaps() List<DisposeDeviceCapacity> capList = dev.getDevCaps()
.stream() .stream()
@ -267,11 +280,14 @@ public class DisposeNodeManagerImpl implements DisposeNodeManager {
// 设备是否支持处置该IP的 // 设备是否支持处置该IP的
if (capList.stream().anyMatch(k -> isIpInRange(k, ipAddr))) { if (capList.stream().anyMatch(k -> isIpInRange(k, ipAddr))) {
log.info("{} with {} used device {}:{}", ipAddr, capacity.getReadme(), dev.getId(), dev.getIpAddr()); log.info("{} with {} used device {}:{}", ipAddr, capacity.getReadme(), dev.getId(), dev.getIpAddr());
return dev; devList.add(dev);
} }
} }
if (devList.size() == 0) {
log.error("No such device to process {} of {}", ipAddr, capacity.getReadme()); log.error("No such device to process {} of {}", ipAddr, capacity.getReadme());
return null; }
return devList;
} }
} }

View File

@ -3,12 +3,15 @@ package com.dispose.service.impl;
import com.dispose.common.DeviceCapacity; import com.dispose.common.DeviceCapacity;
import com.dispose.common.DisposeTaskStatus; import com.dispose.common.DisposeTaskStatus;
import com.dispose.common.ErrorCode; import com.dispose.common.ErrorCode;
import com.dispose.common.Helper;
import com.dispose.dispose.DeviceRouter; import com.dispose.dispose.DeviceRouter;
import com.dispose.dispose.DisposeEntryManager; import com.dispose.dispose.DisposeEntryManager;
import com.dispose.manager.TaskCacheManager; import com.dispose.manager.TaskCacheManager;
import com.dispose.mapper.DisposeTaskMapper; import com.dispose.mapper.DisposeTaskMapper;
import com.dispose.mapper.TaskInfoMapper;
import com.dispose.pojo.entity.DisposeDevice; import com.dispose.pojo.entity.DisposeDevice;
import com.dispose.pojo.po.MulReturnType; import com.dispose.pojo.po.MulReturnType;
import com.dispose.pojo.vo.common.TaskInfo;
import com.dispose.pojo.vo.common.TaskInfoDetail; import com.dispose.pojo.vo.common.TaskInfoDetail;
import com.dispose.service.DisposeNodeManager; import com.dispose.service.DisposeNodeManager;
import com.dispose.service.TaskService; import com.dispose.service.TaskService;
@ -47,19 +50,10 @@ public class TaskServiceImpl implements TaskService {
@Resource @Resource
private DisposeNodeManager disposeNodeManager; private DisposeNodeManager disposeNodeManager;
private DisposeEntryManager getDisposeDeviceHandle(String disposeIp, int devCapType) { @Resource
private TaskInfoMapper taskInfoMapper;
DisposeDevice dev = getDisposeNode(disposeIp, devCapType); private List<DisposeDevice> getDisposeNode(String disposeIp, int devCapType) {
if (dev == null) {
log.info("No dispose device handle: disposeIp:{}, devCapType:{}", disposeIp, devCapType);
return null;
}
return DeviceRouter.deviceRouterFactory(dev.getType(), dev.getIpAddr());
}
private DisposeDevice getDisposeNode(String disposeIp, int devCapType) {
DeviceCapacity cap; DeviceCapacity cap;
try { try {
@ -105,26 +99,29 @@ public class TaskServiceImpl implements TaskService {
*/ */
@Override @Override
public MulReturnType<ErrorCode, Long> createTask(TaskInfoDetail task) { public MulReturnType<ErrorCode, Long> createTask(TaskInfoDetail task) {
DisposeDevice disposeDevice; List<DisposeDevice> disposeDevice = new ArrayList<>();
Long taskId = task.getDeviceId(); Long taskId = task.getDeviceId();
// 首先查找有没有能处置这个ip的能力节点 // 首先查找有没有能处置这个ip的能力节点
// 没有指定处置能力节点的情况 // 没有指定处置能力节点的情况
if (taskId == null || taskId < 0) { if (taskId == null || taskId < 0) {
disposeDevice = getDisposeNode(task.getDisposeIp(), task.getType()); disposeDevice = getDisposeNode(task.getDisposeIp(), task.getType());
task.setDeviceId(-1L);
} else { // 指定了处置能力节点的情况 } else { // 指定了处置能力节点的情况
disposeDevice = disposeNodeManager.getDisposeDeviceById(taskId); DisposeDevice dev = disposeNodeManager.getDisposeDeviceById(taskId);
if (dev != null) {
disposeDevice.add(dev);
task.setDeviceId(dev.getId());
}
} }
if (disposeDevice == null) { if (disposeDevice.size() == 0) {
log.error("No such device to dispose this task: devId:{}, disposeIp:{}, type:{}", log.error("No such device to dispose this task: devId:{}, disposeIp:{}, type:{}",
task.getDeviceId(), task.getDisposeIp(), task.getType()); task.getDeviceId(), task.getDisposeIp(), task.getType());
return MulReturnType.<ErrorCode, Long>builder() return MulReturnType.<ErrorCode, Long>builder()
.firstParam(ErrorCode.ERR_NOSUCHDEVICE) .firstParam(ErrorCode.ERR_NOSUCHDEVICE)
.secondParam(-1L) .secondParam(-1L)
.build(); .build();
} else {
task.setDeviceId(disposeDevice.getId());
} }
// 查询当前是否有相同能力节点相同用户相同处置IP的且正在执行的处置任务如果存在则忽略该次任务依照产品需求 // 查询当前是否有相同能力节点相同用户相同处置IP的且正在执行的处置任务如果存在则忽略该次任务依照产品需求
@ -149,13 +146,13 @@ public class TaskServiceImpl implements TaskService {
// 将该任务写入数据库和缓存等到定时任务真正启动该任务 // 将该任务写入数据库和缓存等到定时任务真正启动该任务
disposeTaskMapper.addNewTask(task); disposeTaskMapper.addNewTask(task);
task.setBeginTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); task.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
TaskInfoDetail cacheTask = disposeTaskMapper.getTaskInfoById(task.getId()); TaskInfoDetail cacheTask = disposeTaskMapper.getTaskById(task.getId());
ErrorCode err = taskCacheManager.addTask(cacheTask); ErrorCode err = taskCacheManager.addTask(cacheTask);
log.info("Create new dispose task is running: devId:{}, disposeIp:{}, type:{}, result:{}", log.info("Create new dispose task: devId:{}, disposeIp:{}, type:{}, result:{}",
task.getDeviceId(), task.getDisposeIp(), task.getType(), err.getMsg()); task.getDeviceId(), task.getDisposeIp(), task.getType(), err.getMsg());
return MulReturnType.<ErrorCode, Long>builder().firstParam(err).secondParam(task.getId()).build(); return MulReturnType.<ErrorCode, Long>builder().firstParam(err).secondParam(task.getId()).build();
@ -179,38 +176,47 @@ public class TaskServiceImpl implements TaskService {
return ErrorCode.ERR_NOSUCHDEVICE; return ErrorCode.ERR_NOSUCHDEVICE;
} }
// 再次检查是否有处置设备能够处置该任务 long planDuration = Helper.getTimestampDiff(task.getCreateTime(), task.getPlanEndTime()) / 60;
DisposeEntryManager dp = getDisposeDeviceHandle(task.getDisposeIp(), task.getType());
if (dp == null) { List<DisposeDevice> dev = getDisposeNode(task.getDisposeIp(), task.getType());
log.error("No such device to dispose this task: disposeId:{}, type:{}", task.getDisposeIp(), task.getType());
// 判断是否有支持处置该IP的能力
if (dev.size() == 0) {
log.info("No dispose device handle: disposeIp:{}, devCapType:{}", task.getDisposeIp(), task.getType());
return ErrorCode.ERR_NOSUCHDEVICE; return ErrorCode.ERR_NOSUCHDEVICE;
} }
// 对新建的任务执行启动操作 // 对新建的任务执行启动操作
if (task.getCurrentStatus() == DisposeTaskStatus.TASK_NEW.getCode()) { if (task.getCurrentStatus() == DisposeTaskStatus.TASK_NEW.getCode()) {
// 更新任务状态为进行中
taskCacheManager.upgradeTaskStatus(taskId, DisposeTaskStatus.TASK_RUNNING.getCode()); taskCacheManager.upgradeTaskStatus(taskId, DisposeTaskStatus.TASK_RUNNING.getCode());
dev.forEach(k -> {
DisposeEntryManager dp = DeviceRouter.getDeviceRouterFactory(k.getType(), k.getIpAddr());
// 异步启动处置任务 // 异步启动处置任务
CompletableFuture.supplyAsync(() -> dp.runDispose(task.getDisposeIp(), DeviceCapacity.values()[task.getType()])) CompletableFuture.supplyAsync(() -> dp.runDispose(task.getDisposeIp(), DeviceCapacity.values()[task.getType()], planDuration))
.whenComplete((v, ex) -> { .whenComplete((v, ex) -> {
if (ex != null) { if (ex != null) {
log.error("Start task: taskId:{}, error:{}", taskId, ex.getMessage()); log.error("Start task: taskId:{}, error:{}", taskId, ex.getMessage());
// 执行任务失败恢复缓存中的任务状态 // 增加设备执行清洗任务信息
taskCacheManager.upgradeTaskStatus(taskId, DisposeTaskStatus.TASK_NEW.getCode()); taskInfoMapper.addNewTaskInfo(taskId, k.getId(), null,
(long) ErrorCode.ERR_SYSTEMEXCEPTION.getCode());
} else { } else {
if (v != ErrorCode.ERR_OK) { if (v.getFirstParam() != ErrorCode.ERR_OK) {
// 执行任务失败恢复缓存中的任务状态 // 执行任务失败恢复缓存中的任务状态
taskCacheManager.upgradeTaskStatus(taskId, DisposeTaskStatus.TASK_NEW.getCode()); taskInfoMapper.addNewTaskInfo(taskId, k.getId(), null, (long) v.getFirstParam().getCode());
log.error("Start task: taskId:{}, disposeIp:{}, error:{}", taskId, task.getDisposeIp(), v.getMsg()); log.error("Start task: taskId:{}, disposeIp:{}, error:{}",
taskId, task.getDisposeIp(), v.getFirstParam().getMsg());
} else { } else {
// 任务执行完成后更新数据库处置任务状态 // 执行任务成功
disposeTaskMapper.changeTaskCurrentStatus(taskId, DisposeTaskStatus.TASK_RUNNING.getCode()); taskInfoMapper.addNewTaskInfo(taskId, k.getId(), v.getSecondParam(), (long) v.getFirstParam().getCode());
log.info("Start task finished: taskId:{}, disposeId:{}, type:{}", taskId, task.getDisposeIp(), task.getType()); log.info("Start task finished: taskId:{}, disposeId:{}, type:{}",
taskId, task.getDisposeIp(), task.getType());
} }
} }
}); });
});
} }
return err; return err;
@ -224,14 +230,14 @@ public class TaskServiceImpl implements TaskService {
*/ */
@Override @Override
public ErrorCode stopTask(Long taskId) { public ErrorCode stopTask(Long taskId) {
TaskInfoDetail task = taskCacheManager.getTaskById(taskId); TaskInfoDetail task = taskCacheManager.getTaskById(taskId);
if (task != null) { if (task != null) {
DisposeEntryManager dp = getDisposeDeviceHandle(task.getDisposeIp(), task.getType()); List<DisposeDevice> dev = getDisposeNode(task.getDisposeIp(), task.getType());
if (dp == null) { // 判断是否有支持处置该IP的能力
log.error("No such device to dispose this task: disposeId:{}, type:{}", task.getDisposeIp(), task.getType()); if (dev.size() == 0) {
log.info("No dispose device handle: disposeIp:{}, devCapType:{}", task.getDisposeIp(), task.getType());
return ErrorCode.ERR_NOSUCHDEVICE; return ErrorCode.ERR_NOSUCHDEVICE;
} }
@ -244,25 +250,34 @@ public class TaskServiceImpl implements TaskService {
return err; return err;
} }
dev.forEach(k -> {
DisposeEntryManager dp = DeviceRouter.getDeviceRouterFactory(k.getType(), k.getIpAddr());
TaskInfo taskInfo = taskInfoMapper.getTaskInfo(taskId, k.getId());
// 异步启动处置任务 // 异步启动处置任务
CompletableFuture.supplyAsync(() -> dp.stopDispose(task.getDisposeIp(), DeviceCapacity.values()[task.getType()])) CompletableFuture.supplyAsync(() -> dp.stopDispose(task.getDisposeIp(),
DeviceCapacity.values()[task.getType()],
(taskInfo == null || taskInfo.getExternId() == null) ? -1 : taskInfo.getExternId()))
.whenComplete((v, ex) -> { .whenComplete((v, ex) -> {
if (ex != null) { if (ex != null) {
// 恢复缓存中任务状态到先前状态 // 恢复缓存中任务状态到先前状态
taskCacheManager.upgradeTaskStatus(taskId, prdStatus); taskCacheManager.upgradeTaskStatus(taskId, prdStatus);
log.error("Stop task: taskId:{}, error:{}", taskId, ex.getMessage()); log.error("Stop task: taskId:{}, error:{}", taskId, ex.getMessage());
} else { } else {
if (v != ErrorCode.ERR_OK) { if (v.getFirstParam() != ErrorCode.ERR_OK) {
// 恢复缓存中任务状态到先前状态 // 恢复缓存中任务状态到先前状态
taskCacheManager.upgradeTaskStatus(taskId, prdStatus); taskCacheManager.upgradeTaskStatus(taskId, prdStatus);
log.error("Stop task: taskId:{}, error:{}", taskId, v.getMsg()); log.error("Stop task: taskId:{}, error:{}", taskId, v.getFirstParam().getMsg());
} else { } else {
// 任务执行完成后更新数据库处置任务状态 // 任务执行完成后更新数据库处置任务状态
finishTask(taskId); finishTask(taskId);
log.info("Stop task finished: taskId:{}, disposeId:{}, type:{}", taskId, task.getDisposeIp(), task.getType()); log.info("Stop task finished: taskId:{}, disposeId:{}, type:{}",
taskId, task.getDisposeIp(), task.getType());
} }
} }
}); });
});
} else { } else {
log.error("No such task: taskId:{}", taskId); log.error("No such task: taskId:{}", taskId);
return ErrorCode.ERR_NOSUCHTASK; return ErrorCode.ERR_NOSUCHTASK;
@ -285,7 +300,7 @@ public class TaskServiceImpl implements TaskService {
if (err == ErrorCode.ERR_OK) { if (err == ErrorCode.ERR_OK) {
// 设置数据库任务状态为完成状态 // 设置数据库任务状态为完成状态
disposeTaskMapper.changeTaskCurrentStatus(taskId, DisposeTaskStatus.TASK_FINISH.getCode()); disposeTaskMapper.changeTaskCurrentStatus(taskId, DisposeTaskStatus.TASK_FINISH.getCode());
Integer currentStatus = disposeTaskMapper.getTaskInfoById(taskId).getCurrentStatus(); Integer currentStatus = disposeTaskMapper.getTaskById(taskId).getCurrentStatus();
log.info("taskId:{}, currentStatus:{}", taskId, currentStatus); log.info("taskId:{}, currentStatus:{}", taskId, currentStatus);
// 移除缓存中的任务信息 // 移除缓存中的任务信息
taskCacheManager.removeTask(taskId); taskCacheManager.removeTask(taskId);

View File

@ -1,6 +1,5 @@
package com.dispose.task; package com.dispose.task;
import com.dispose.common.IPAddrType;
import com.dispose.dispose.DeviceRouter; import com.dispose.dispose.DeviceRouter;
import com.dispose.dispose.DisposeEntryManager; import com.dispose.dispose.DisposeEntryManager;
import com.dispose.pojo.entity.DisposeDevice; import com.dispose.pojo.entity.DisposeDevice;
@ -31,9 +30,7 @@ public class DeviceManagerTask {
List<DisposeDevice> devList = disposeNodeManager.getAllDisposeDevice(); List<DisposeDevice> devList = disposeNodeManager.getAllDisposeDevice();
devList.forEach(v -> { devList.forEach(v -> {
DisposeEntryManager dp = DeviceRouter.deviceRouterFactory(v.getType(), DisposeEntryManager dp = DeviceRouter.getDeviceRouterFactory(v.getType(), v.getIpAddr());
v.getIpAddr(),
IPAddrType.getIpAddrType(v.getIpAddr()));
// 自动更新设备心跳状态 // 自动更新设备心跳状态
v.setLinkStatus(dp.getDeviceLinkStatus() ? 1 : 0); v.setLinkStatus(dp.getDeviceLinkStatus() ? 1 : 0);
// 自动读取设备系统版本信息 // 自动读取设备系统版本信息

View File

@ -39,7 +39,7 @@ public class TaskManagerTask {
// 判断是否存在正在运行的过期的任务如果存在则结束该任务 // 判断是否存在正在运行的过期的任务如果存在则结束该任务
if(taskService.taskIsExpired(taskData) && taskService.taskIsRunning(taskData)) { if(taskService.taskIsExpired(taskData) && taskService.taskIsRunning(taskData)) {
log.info("Finish expired task {}:{} begin at {}", log.info("Finish expired task {}:{} begin at {}",
taskData.getId(), taskData.getDisposeIp(), taskData.getBeginTime()); taskData.getId(), taskData.getDisposeIp(), taskData.getCreateTime());
taskService.stopTask(taskData.getId()); taskService.stopTask(taskData.getId());
it.remove(); it.remove();
continue; continue;
@ -53,7 +53,7 @@ public class TaskManagerTask {
// 判断是否有新建任务如果有的话启动新建的处置任务 // 判断是否有新建任务如果有的话启动新建的处置任务
if (taskData.getCurrentStatus() == DisposeTaskStatus.TASK_NEW.getCode()) { if (taskData.getCurrentStatus() == DisposeTaskStatus.TASK_NEW.getCode()) {
log.info("Start task {}:{} of {}", log.info("Start task {}:{} of {}",
taskData.getId(), taskData.getDisposeIp(), taskData.getBeginTime()); taskData.getId(), taskData.getDisposeIp(), taskData.getCreateTime());
if (taskService.startTask(taskData.getId()) != ErrorCode.ERR_OK) { if (taskService.startTask(taskData.getId()) != ErrorCode.ERR_OK) {
taskData.setRetryTimes(taskData.getRetryTimes() + 1); taskData.setRetryTimes(taskData.getRetryTimes() + 1);
log.error("startTask Task {}:{} error\n", taskData.getId(), taskData.getDisposeIp()); log.error("startTask Task {}:{} error\n", taskData.getId(), taskData.getDisposeIp());

View File

@ -1,2 +1,11 @@
insert into `dispose_device`(`id`,`ipAddr`,`type`,`areaCode`,`name`,`manufacturer`,`model`,`version`,`readme`,`status`) values (1,'10.88.77.15',0,0,'中移杭研实验室清洗设备','DPTech','UMC','5.7.13','实验室测试设备',0); -- ----------------------------
insert into `user_account`(`id`,`username`,`password`,`lastLoginTime`,`lockTime`,`status`) values (1,'admin','c3855e6b6bb120450f160ba91134522868f89d36062f2061ebeefd80817e1d58','2020-05-06 11:31:58','0000-00-00 00:00:00',0); -- Records of dispose_device
-- ----------------------------
INSERT INTO `dispose_device` VALUES (1, '10.88.77.88:18080', 1, 0, '中移杭研实验室浩瀚清洗设备', 'HaoHan', 'Unknown', 'Unknown', '', '', 'http://%s/DDoSClean/clean', '实验室测试设备', 0);
INSERT INTO `dispose_device` VALUES (2, '10.88.77.15', 0, 0, '中移杭研实验室迪普清洗设备', 'DPTech', 'UMC', '5.7.13', 'admin', 'UMCAdministrator', 'http://%s/UMC/service/AbnormalFlowCleaningService', '实验室测试设备', 0);
-- ----------------------------
-- Records of user_account
-- ----------------------------
INSERT INTO `user_account` VALUES (1, 'admin', 'c3855e6b6bb120450f160ba91134522868f89d36062f2061ebeefd80817e1d58', '2020-06-29 10:18:44', '0000-00-00 00:00:00', 0);

View File

@ -1,63 +1,117 @@
/*Table structure for table `dispose_device` */ /*
Navicat Premium Data Transfer
Source Server Type : MySQL
Source Server Version : 50723
Target Server Type : MySQL
Target Server Version : 50723
File Encoding : 65001
Date: 29/06/2020 14:32:25
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for dispose_device
-- ----------------------------
DROP TABLE IF EXISTS `dispose_device`; DROP TABLE IF EXISTS `dispose_device`;
CREATE TABLE `dispose_device`
CREATE TABLE IF NOT EXISTS `dispose_device`
( (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '设备唯一标识符', `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '设备唯一标识符',
`ipAddr` varchar(64) DEFAULT NULL COMMENT '设备IP地址, IPv4/IPv6', `ipAddr` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '设备IP地址, IPv4/IPv6',
`type` int(11) NOT NULL DEFAULT '0' COMMENT '能力节点类型0迪普UMC平台1浩瀚设备', `type` int(11) NOT NULL DEFAULT 0 COMMENT '能力节点类型0迪普UMC平台1浩瀚设备',
`areaCode` int(11) DEFAULT NULL COMMENT '设备物理位置区域码', `areaCode` int(11) NULL DEFAULT NULL COMMENT '设备物理位置区域码',
`name` varchar(256) DEFAULT NULL COMMENT '设备名称', `name` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '设备名称',
`manufacturer` varchar(128) DEFAULT NULL COMMENT '生产厂商', `manufacturer` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '生产厂商',
`model` varchar(128) DEFAULT NULL COMMENT '型号', `model` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '型号',
`version` varchar(128) DEFAULT NULL COMMENT '软件版本', `version` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '软件版本',
`readme` varchar(1024) DEFAULT NULL COMMENT '备注', `userName` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '系统管理用户名',
`status` int(11) NOT NULL DEFAULT '0' COMMENT '状态0正常 1删除', `password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '系统管理密码',
PRIMARY KEY (`id`), `url` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT 'URL类型',
UNIQUE KEY `ipAddr` (`ipAddr`) `readme` varchar(1024) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '备注',
`status` int(11) NOT NULL DEFAULT 0 COMMENT '状态0正常 1删除',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `ipAddr` (`ipAddr`) USING BTREE
) ENGINE = InnoDB ) ENGINE = InnoDB
AUTO_INCREMENT = 1 AUTO_INCREMENT = 1
DEFAULT CHARSET = utf8; CHARACTER SET = utf8
COLLATE = utf8_general_ci
/*Table structure for table `user_account` */ ROW_FORMAT = Dynamic;
DROP TABLE IF EXISTS `user_account`;
CREATE TABLE IF NOT EXISTS `user_account`
(
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '账户唯一编号',
`username` varchar(128) NOT NULL COMMENT '用户名',
`password` varchar(512) NOT NULL COMMENT '密码',
`lastLoginTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后一次成功登录时间',
`lockTime` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT '账户锁定时间',
`status` int(11) DEFAULT NULL COMMENT '账户状态',
PRIMARY KEY (`id`),
UNIQUE KEY `USERNAME` (`username`)
) ENGINE = InnoDB
AUTO_INCREMENT = 1
DEFAULT CHARSET = utf8;
/*Table structure for table `dispose_task` */
-- ----------------------------
-- Table structure for dispose_task
-- ----------------------------
DROP TABLE IF EXISTS `dispose_task`; DROP TABLE IF EXISTS `dispose_task`;
CREATE TABLE `dispose_task`
CREATE TABLE IF NOT EXISTS `dispose_task`
( (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '处置任务唯一标识符', `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '处置任务唯一标识符',
`deviceId` int(10) unsigned NOT NULL COMMENT '处置设备唯一标识符', `deviceId` int(10) NOT NULL COMMENT '处置设备唯一标识符',
`accountId` int(10) unsigned NOT NULL COMMENT '用户唯一标识符', `accountId` int(10) UNSIGNED NOT NULL COMMENT '用户唯一标识符',
`type` int(11) unsigned NOT NULL COMMENT '处置能力类型0清洗 1高防 2黑洞 3检测', `type` int(11) UNSIGNED NOT NULL COMMENT '处置能力类型0清洗 1高防 2黑洞 3检测',
`disposeIp` varchar(128) NOT NULL COMMENT '处置IP', `disposeIp` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '处置IP',
`beginTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '开始时间', `createTime` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '开始时间',
`planEndTime` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT '计划结束时间', `planEndTime` timestamp(0) NOT NULL DEFAULT '1970-01-02 00:00:00' COMMENT '计划结束时间',
`endTime` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT '实际结束时间', `endTime` timestamp(0) NOT NULL DEFAULT '1970-01-02 00:00:00' COMMENT '实际结束时间',
`flowDirection` int(11) DEFAULT '2' COMMENT '流量方向, 0流入1流出2双向', `flowDirection` int(11) NULL DEFAULT 2 COMMENT '流量方向, 0流入1流出2双向',
`attackType` varchar(1024) DEFAULT '0' COMMENT '攻击类型默认0 全部攻击', `attackType` varchar(1024) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '0' COMMENT '攻击类型默认0 全部攻击',
`flowBandWidth` int(10) unsigned DEFAULT '1024' COMMENT '攻击流量占用带宽', `flowBandWidth` int(10) UNSIGNED NULL DEFAULT 1024 COMMENT '攻击流量占用带宽',
`currentStatus` int(11) NOT NULL DEFAULT '0' COMMENT '状态0停止。1启动', `currentStatus` int(11) NOT NULL DEFAULT 0 COMMENT '状态0停止。1启动',
PRIMARY KEY (`id`), PRIMARY KEY (`id`) USING BTREE,
KEY `dispose_task_device_capacity_id_fk` (`type`), INDEX `dispose_task_device_capacity_id_fk` (`type`) USING BTREE,
KEY `dispose_task_user_account_id_fk` (`accountId`), INDEX `dispose_task_user_account_id_fk` (`accountId`) USING BTREE,
CONSTRAINT `dispose_task_user_account_id_fk` FOREIGN KEY (`accountId`) REFERENCES `user_account` (`id`) ON DELETE NO ACTION CONSTRAINT `dispose_task_ibfk_1` FOREIGN KEY (`accountId`) REFERENCES `user_account` (`id`) ON DELETE NO ACTION ON UPDATE RESTRICT
) ENGINE = InnoDB ) ENGINE = InnoDB
AUTO_INCREMENT = 1 AUTO_INCREMENT = 1
DEFAULT CHARSET = utf8; CHARACTER SET = utf8
COLLATE = utf8_general_ci
ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for task_info
-- ----------------------------
DROP TABLE IF EXISTS `task_info`;
CREATE TABLE `task_info`
(
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '任务信息唯一标识符',
`taskId` int(10) UNSIGNED NOT NULL COMMENT '处置任务唯一标识符',
`deviceId` int(10) UNSIGNED NOT NULL COMMENT '处置设备唯一标识符',
`beginTime` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '任务开始时间',
`endTime` timestamp(0) NULL DEFAULT NULL COMMENT '任务结束时间',
`externId` int(10) UNSIGNED NULL DEFAULT NULL COMMENT '扩展ID供浩瀚处置任务使用',
`status` int(10) NOT NULL DEFAULT 0 COMMENT '任务状态',
PRIMARY KEY (`id`) USING BTREE,
INDEX `task_info_ibfk_1` (`taskId`) USING BTREE,
INDEX `task_info_ibfk_2` (`deviceId`) USING BTREE,
CONSTRAINT `task_info_ibfk_1` FOREIGN KEY (`taskId`) REFERENCES `dispose_task` (`id`) ON DELETE NO ACTION ON UPDATE RESTRICT,
CONSTRAINT `task_info_ibfk_2` FOREIGN KEY (`deviceId`) REFERENCES `dispose_device` (`id`) ON DELETE NO ACTION ON UPDATE RESTRICT
) ENGINE = InnoDB
AUTO_INCREMENT = 1
CHARACTER SET = utf8
COLLATE = utf8_general_ci
ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for user_account
-- ----------------------------
DROP TABLE IF EXISTS `user_account`;
CREATE TABLE `user_account`
(
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '账户唯一编号',
`username` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名',
`password` varchar(512) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '密码',
`lastLoginTime` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '最后一次成功登录时间',
`lockTime` timestamp(0) NOT NULL DEFAULT '1970-01-02 00:00:00' COMMENT '账户锁定时间',
`status` int(11) NULL DEFAULT NULL COMMENT '账户状态',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `USERNAME` (`username`) USING BTREE
) ENGINE = InnoDB
AUTO_INCREMENT = 1
CHARACTER SET = utf8
COLLATE = utf8_general_ci
ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;

View File

@ -5,11 +5,11 @@
INSERT IGNORE INTO INSERT IGNORE INTO
dispose_device(ipAddr, type, dispose_device(ipAddr, type,
areaCode, name, manufacturer, areaCode, name, manufacturer,
model, version, readme, status) model, version, userName, password, url, readme, status)
VALUES VALUES
(#{ipAddr}, #{type}, (#{ipAddr}, #{type},
#{areaCode}, #{name}, #{manufacturer}, #{areaCode}, #{name}, #{manufacturer},
#{model}, #{version}, #{readme}, 0) #{model}, #{version}, #{userName}, #{password}, #{url}, #{readme}, 0)
</insert> </insert>
<select id="getDeviceByIp" resultType="com.dispose.pojo.entity.DisposeDevice" parameterType="java.lang.String"> <select id="getDeviceByIp" resultType="com.dispose.pojo.entity.DisposeDevice" parameterType="java.lang.String">
@ -42,12 +42,4 @@
WHERE WHERE
dispose_device.ipAddr = #{ipAddr} dispose_device.ipAddr = #{ipAddr}
</delete> </delete>
<delete id="delDisposeDeviceById" parameterType="java.lang.Long">
DELETE
dispose_device
FROM
dispose_device
WHERE
dispose_device.id = #{id}
</delete>
</mapper> </mapper>

View File

@ -37,7 +37,7 @@
WHERE id = #{id, jdbcType=INTEGER} WHERE id = #{id, jdbcType=INTEGER}
</select> </select>
<select id="getTaskInfoById" resultType="com.dispose.pojo.vo.common.TaskInfoDetail"> <select id="getTaskById" resultType="com.dispose.pojo.vo.common.TaskInfoDetail">
SELECT * SELECT *
FROM dispose_task FROM dispose_task
WHERE id = #{id, jdbcType=INTEGER} WHERE id = #{id, jdbcType=INTEGER}
@ -78,7 +78,7 @@
WHERE currentStatus = #{status, jdbcType=INTEGER} WHERE currentStatus = #{status, jdbcType=INTEGER}
</select> </select>
<select id="getTaskByTaskInfo" resultType="com.dispose.pojo.vo.common.TaskInfoDetail"> <select id="getTaskByTaskDetail" resultType="com.dispose.pojo.vo.common.TaskInfoDetail">
SELECT * SELECT *
FROM dispose_task FROM dispose_task
WHERE deviceId = #{devId, jdbcType=INTEGER} WHERE deviceId = #{devId, jdbcType=INTEGER}

View File

@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dispose.mapper.TaskInfoMapper">
<insert id="addNewTaskInfo">
INSERT IGNORE INTO task_info(taskId, deviceId, externId, status)
VALUES (#{taskId}, #{deviceId}, #{externId}, #{status})
</insert>
<select id="getTaskInfo" resultType="com.dispose.pojo.vo.common.TaskInfo">
SELECT *
FROM task_info
WHERE taskId = #{taskId, jdbcType=INTEGER}
AND deviceId = #{deviceId, jdbcType=INTEGER}
</select>
<select id="getTaskInfoByTaskId" resultType="com.dispose.pojo.vo.common.TaskInfo">
SELECT *
FROM task_info
WHERE taskId = #{taskId, jdbcType=INTEGER}
</select>
<update id="changeTaskInfoStatus">
UPDATE
task_info
SET
status = #{status, jdbcType=INTEGER}
WHERE
id = #{id, jdbcType=INTEGER}
</update>
<select id="getTaskInfoCurrentStatus" resultType="java.lang.Integer">
SELECT status
FROM task_info
WHERE id = #{id, jdbcType=INTEGER}
</select>
<delete id="removeTaskInfoById" parameterType="java.lang.Long">
DELETE
task_info
FROM task_info
WHERE task_info.deviceId = #{deviceId}
</delete>
</mapper>

View File

@ -3,15 +3,15 @@ package com.dispose.test.TestSuit;
import com.dispose.test.config.DisposeConfigureTest; import com.dispose.test.config.DisposeConfigureTest;
import com.dispose.test.config.MyConfigTest; import com.dispose.test.config.MyConfigTest;
import com.dispose.test.controller.AuthControllerTest;
import com.dispose.test.controller.DeviceNodeInfoControllerTest;
import com.dispose.test.controller.DeviceNodeManagerControllerTest;
import com.dispose.test.controller.TaskControllerTest;
import com.dispose.test.dptech.DPTechInterfaceTestCase; import com.dispose.test.dptech.DPTechInterfaceTestCase;
import com.dispose.test.manager.UserAccountManagerTest; import com.dispose.test.manager.UserAccountManagerTest;
import com.dispose.test.mapper.DisposeDeviceMapperTest; import com.dispose.test.mapper.DisposeDeviceMapperTest;
import com.dispose.test.mapper.DisposeTaskMapperTest; import com.dispose.test.mapper.DisposeTaskMapperTest;
import com.dispose.test.mapper.UserAccountMapperTest; import com.dispose.test.mapper.UserAccountMapperTest;
import com.dispose.test.controller.AuthControllerTest;
import com.dispose.test.controller.DeviceNodeInfoControllerTest;
import com.dispose.test.controller.DeviceNodeManagerControllerTest;
import com.dispose.test.controller.TaskControllerTest;
import com.dispose.test.service.DisposeNodeManagerTest; import com.dispose.test.service.DisposeNodeManagerTest;
import com.dispose.test.service.TaskServiceTest; import com.dispose.test.service.TaskServiceTest;
import com.dispose.test.service.UserAccountServiceTest; import com.dispose.test.service.UserAccountServiceTest;

View File

@ -1,7 +1,7 @@
package com.dispose.test.config; package com.dispose.test.config;
import com.dispose.test.Global.InitTestEnvironment;
import com.dispose.config.DisposeConfigure; import com.dispose.config.DisposeConfigure;
import com.dispose.test.Global.InitTestEnvironment;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;

View File

@ -1,7 +1,7 @@
package com.dispose.test.config; package com.dispose.test.config;
import com.dispose.test.Global.InitTestEnvironment;
import com.dispose.config.MyConfig; import com.dispose.config.MyConfig;
import com.dispose.test.Global.InitTestEnvironment;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;

View File

@ -1,10 +1,10 @@
package com.dispose.test.controller; package com.dispose.test.controller;
import com.dispose.common.GlobalVar;
import com.dispose.test.Global.InitTestEnvironment;
import com.dispose.common.ErrorCode; import com.dispose.common.ErrorCode;
import com.dispose.common.GlobalVar;
import com.dispose.pojo.po.ReturnStatus; import com.dispose.pojo.po.ReturnStatus;
import com.dispose.pojo.vo.auth.LogoutRsp; import com.dispose.pojo.vo.auth.LogoutRsp;
import com.dispose.test.Global.InitTestEnvironment;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.junit.Assert; import org.junit.Assert;
@ -279,6 +279,119 @@ public class AuthControllerQATest extends InitTestEnvironment {
Assert.assertEquals(Long.valueOf(rspInfo.getStatus()), Long.valueOf(ErrorCode.ERR_PASSWORD.getCode())); Assert.assertEquals(Long.valueOf(rspInfo.getStatus()), Long.valueOf(ErrorCode.ERR_PASSWORD.getCode()));
} }
/**
* B 3 password empty exception test.
*
* @throws Exception the exception
*/
@Test
public void b3_loginPasswordEmptyExceptionTest() throws Exception {
String reqData = "{\"ver\":2,\"cryptoType\":0,\"timeStamp\":1587604296988," +
"\"msgContent\":\"{\\\"password\\\":\\\"\\\",\\\"userName\\\":\\\"admin\\\"}\"}";
String ret = mockMvc.perform(MockMvcRequestBuilders
.post("/auth/login")
.contentType(MediaType.APPLICATION_JSON)
.content(reqData))
.andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(ErrorCode.ERR_PASSWORD.getHttpCode()))
.andReturn()
.getResponse()
.getContentAsString();
ReturnStatus rspInfo = objectMapper.readValue(verifyResp(ret), ReturnStatus.class) ;
Assert.assertNotNull(rspInfo.getMessage());
Assert.assertNotNull(rspInfo.getStatus());
Assert.assertEquals(Long.valueOf(rspInfo.getStatus()), Long.valueOf(ErrorCode.ERR_PASSWORD.getCode()));
}
/**
* B 4 msg empty exception test.
*
* @throws Exception the exception
*/
@Test
public void b4_loginMsgEmptyExceptionTest() throws Exception {
String reqData = "{\"ver\":2,\"cryptoType\":0,\"timeStamp\":1587604296988," +
"\"msgContent\":\"\"}";
String ret = mockMvc.perform(MockMvcRequestBuilders
.post("/auth/login")
.contentType(MediaType.APPLICATION_JSON)
.content(reqData))
.andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(ErrorCode.ERR_PARAMEXCEPTION.getHttpCode()))
.andReturn()
.getResponse()
.getContentAsString();
ReturnStatus rspInfo = objectMapper.readValue(verifyResp(ret), ReturnStatus.class) ;
Assert.assertNotNull(rspInfo.getMessage());
Assert.assertNotNull(rspInfo.getStatus());
Assert.assertEquals(Long.valueOf(rspInfo.getStatus()), Long.valueOf(ErrorCode.ERR_PARAMEXCEPTION.getCode()));
}
/**
* B 5 msg null exception test.
*
* @throws Exception the exception
*/
@Test
public void b5_loginMsgNullExceptionTest() throws Exception {
String reqData = "{\"ver\":2,\"cryptoType\":0,\"timeStamp\":1587604296988," +
"\"msgContent\":\"null\"}";
String ret = mockMvc.perform(MockMvcRequestBuilders
.post("/auth/login")
.contentType(MediaType.APPLICATION_JSON)
.content(reqData))
.andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(ErrorCode.ERR_PARAMEXCEPTION.getHttpCode()))
.andReturn()
.getResponse()
.getContentAsString();
ReturnStatus rspInfo = objectMapper.readValue(verifyResp(ret), ReturnStatus.class) ;
Assert.assertNotNull(rspInfo.getMessage());
Assert.assertNotNull(rspInfo.getStatus());
Assert.assertEquals(Long.valueOf(rspInfo.getStatus()), Long.valueOf(ErrorCode.ERR_PARAMEXCEPTION.getCode()));
}
/**
* B 6 username type exception test.
*
* @throws Exception the exception
*/
@Test
public void b6_loginUsernameIntExceptionTest() throws Exception {
String reqData = "{\"ver\":2,\"cryptoType\":0,\"timeStamp\":1587604296988,\"msgContent\":\"" +
"{\\\"password\\\":\\\"c3855e6b6bb120450f160ba91134522868f89d36062f2061ebeefd80817e1d58\\\"," +
"\\\"userName\\\":1}\"}";
String ret = mockMvc.perform(MockMvcRequestBuilders
.post("/auth/login")
.contentType(MediaType.APPLICATION_JSON)
.content(reqData))
.andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(ErrorCode.ERR_USERNOTFOUND.getHttpCode()))
.andReturn()
.getResponse()
.getContentAsString();
ReturnStatus rspInfo = objectMapper.readValue(verifyResp(ret), ReturnStatus.class) ;
Assert.assertNotNull(rspInfo.getMessage());
Assert.assertNotNull(rspInfo.getStatus());
Assert.assertEquals(Long.valueOf(rspInfo.getStatus()), Long.valueOf(ErrorCode.ERR_USERNOTFOUND.getCode()));
}
/** /**
* C 1 normal logout test . * C 1 normal logout test .
* *
@ -396,4 +509,208 @@ public class AuthControllerQATest extends InitTestEnvironment {
Assert.assertEquals(Long.valueOf(rspInfo.getStatus()), Long.valueOf(ErrorCode.ERR_PARAMS.getCode())); Assert.assertEquals(Long.valueOf(rspInfo.getStatus()), Long.valueOf(ErrorCode.ERR_PARAMS.getCode()));
} }
/**
* C 5 msg empty exception test.
*
* @throws Exception the exception
*/
@Test
public void c5_logoutMsgEmptyExceptionTest() throws Exception {
String reqData = "{\"ver\":2,\"cryptoType\":0,\"timeStamp\":1587604300195," +
"\"msgContent\":\"\"}";
String ret = mockMvc.perform(MockMvcRequestBuilders
.post("/auth/logout")
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", GlobalVar.STRING_HTTP_AUTH_HEAD + getLogToken())
.content(reqData))
.andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(ErrorCode.ERR_PARAMEXCEPTION.getHttpCode()))
.andReturn()
.getResponse()
.getContentAsString();
ReturnStatus rspInfo = objectMapper.readValue(verifyResp(ret), ReturnStatus.class) ;
Assert.assertNotNull(rspInfo.getMessage());
Assert.assertNotNull(rspInfo.getStatus());
Assert.assertEquals(Long.valueOf(rspInfo.getStatus()), Long.valueOf(ErrorCode.ERR_PARAMEXCEPTION.getCode()));
}
/**
* C 6 msg null exception test.
*
* @throws Exception the exception
*/
@Test
public void c6_logoutMsgNullExceptionTest() throws Exception {
String reqData = "{\"ver\":2,\"cryptoType\":0,\"timeStamp\":1587604300195," +
"\"msgContent\":\"null\"}";
String ret = mockMvc.perform(MockMvcRequestBuilders
.post("/auth/logout")
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", GlobalVar.STRING_HTTP_AUTH_HEAD + getLogToken())
.content(reqData))
.andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(ErrorCode.ERR_PARAMEXCEPTION.getHttpCode()))
.andReturn()
.getResponse()
.getContentAsString();
ReturnStatus rspInfo = objectMapper.readValue(verifyResp(ret), ReturnStatus.class) ;
Assert.assertNotNull(rspInfo.getMessage());
Assert.assertNotNull(rspInfo.getStatus());
Assert.assertEquals(Long.valueOf(rspInfo.getStatus()), Long.valueOf(ErrorCode.ERR_PARAMEXCEPTION.getCode()));
}
/**
* C 7 ver json exception test .
*
* @throws Exception the exception
*/
@Test
public void c7_logoutVerJsonExceptionTest() throws Exception {
String reqData = "{\"ver\":\"cryptoType\":0,\"timeStamp\":1587604300195," +
"\"msgContent\":\"{\\\"userName\\\":\\\"admin\\\"}\"}";
String ret = mockMvc.perform(MockMvcRequestBuilders
.post("/auth/logout")
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", GlobalVar.STRING_HTTP_AUTH_HEAD + getLogToken())
.content(reqData))
.andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(ErrorCode.ERR_PARAMEXCEPTION.getHttpCode()))
.andReturn()
.getResponse()
.getContentAsString();
ReturnStatus rspInfo = objectMapper.readValue(verifyResp(ret), ReturnStatus.class) ;
Assert.assertNotNull(rspInfo.getMessage());
Assert.assertNotNull(rspInfo.getStatus());
Assert.assertEquals(Long.valueOf(rspInfo.getStatus()), Long.valueOf(ErrorCode.ERR_PARAMEXCEPTION.getCode()));
Assert.assertEquals(rspInfo.getMessage(), ErrorCode.ERR_PARAMEXCEPTION.getMsg());
}
/**
* C 8 ver null exception test .
*
* @throws Exception the exception
*/
@Test
public void c8_logoutVerNullExceptionTest() throws Exception {
String reqData = "{\"ver\":null,\"cryptoType\":0,\"timeStamp\":1587604300195," +
"\"msgContent\":\"{\\\"userName\\\":\\\"admin\\\"}\"}";
String ret = mockMvc.perform(MockMvcRequestBuilders
.post("/auth/logout")
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", GlobalVar.STRING_HTTP_AUTH_HEAD + getLogToken())
.content(reqData))
.andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(ErrorCode.ERR_PARAMEXCEPTION.getHttpCode()))
.andReturn()
.getResponse()
.getContentAsString();
ReturnStatus rspInfo = objectMapper.readValue(verifyResp(ret), ReturnStatus.class) ;
Assert.assertNotNull(rspInfo.getMessage());
Assert.assertNotNull(rspInfo.getStatus());
Assert.assertEquals(Long.valueOf(rspInfo.getStatus()), Long.valueOf(ErrorCode.ERR_PARAMEXCEPTION.getCode()));
Assert.assertEquals(rspInfo.getMessage(), ErrorCode.ERR_PARAMEXCEPTION.getMsg());
}
/**
* C 9 crypto json exception test .
*
* @throws Exception the exception
*/
@Test
public void c9_logoutCryptoJsonExceptionTest() throws Exception {
String reqData = "{\"ver\":2,\"cryptoType\":\"timeStamp\":1587604300195," +
"\"msgContent\":\"{\\\"userName\\\":\\\"admin\\\"}\"}";
String ret = mockMvc.perform(MockMvcRequestBuilders
.post("/auth/logout")
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", GlobalVar.STRING_HTTP_AUTH_HEAD + getLogToken())
.content(reqData))
.andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(ErrorCode.ERR_PARAMEXCEPTION.getHttpCode()))
.andReturn()
.getResponse()
.getContentAsString();
ReturnStatus rspInfo = objectMapper.readValue(verifyResp(ret), ReturnStatus.class) ;
Assert.assertNotNull(rspInfo.getMessage());
Assert.assertNotNull(rspInfo.getStatus());
Assert.assertEquals(Long.valueOf(rspInfo.getStatus()), Long.valueOf(ErrorCode.ERR_PARAMEXCEPTION.getCode()));
Assert.assertEquals(rspInfo.getMessage(), ErrorCode.ERR_PARAMEXCEPTION.getMsg());
}
/**
* C 10 crypto null exception test .
*
* @throws Exception the exception
*/
@Test
public void c10_logoutCryptoNullExceptionTest() throws Exception {
String reqData = "{\"ver\":2,\"cryptoType\":null,\"timeStamp\":1587604300195," +
"\"msgContent\":\"{\\\"userName\\\":\\\"admin\\\"}\"}";
String ret = mockMvc.perform(MockMvcRequestBuilders
.post("/auth/logout")
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", GlobalVar.STRING_HTTP_AUTH_HEAD + getLogToken())
.content(reqData))
.andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(ErrorCode.ERR_PARAMEXCEPTION.getHttpCode()))
.andReturn()
.getResponse()
.getContentAsString();
ReturnStatus rspInfo = objectMapper.readValue(verifyResp(ret), ReturnStatus.class) ;
Assert.assertNotNull(rspInfo.getMessage());
Assert.assertNotNull(rspInfo.getStatus());
Assert.assertEquals(Long.valueOf(rspInfo.getStatus()), Long.valueOf(ErrorCode.ERR_PARAMEXCEPTION.getCode()));
Assert.assertEquals(rspInfo.getMessage(), ErrorCode.ERR_PARAMEXCEPTION.getMsg());
}
/**
* C 11 username not exit exception test .
*
* @throws Exception the exception
*/
@Test
public void c11_logoutUsernameNotExitExceptionTest() throws Exception {
String reqData = "{\"ver\":2,\"cryptoType\":0,\"timeStamp\":1587604300195," +
"\"msgContent\":\"{\\\"userName\\\":\\\"a\\\"}\"}";
String ret = mockMvc.perform(MockMvcRequestBuilders
.post("/auth/logout")
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", GlobalVar.STRING_HTTP_AUTH_HEAD + getLogToken())
.content(reqData))
.andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(ErrorCode.ERR_USERNOTFOUND.getHttpCode()))
.andReturn()
.getResponse()
.getContentAsString();
ReturnStatus rspInfo = objectMapper.readValue(verifyResp(ret), ReturnStatus.class) ;
Assert.assertNotNull(rspInfo.getMessage());
Assert.assertNotNull(rspInfo.getStatus());
Assert.assertEquals(Long.valueOf(rspInfo.getStatus()), Long.valueOf(ErrorCode.ERR_USERNOTFOUND.getCode()));
Assert.assertEquals(rspInfo.getMessage(), ErrorCode.ERR_USERNOTFOUND.getMsg());
}
} }

View File

@ -1,9 +1,9 @@
package com.dispose.test.controller; package com.dispose.test.controller;
import com.dispose.test.Global.InitTestEnvironment;
import com.dispose.common.ErrorCode; import com.dispose.common.ErrorCode;
import com.dispose.pojo.po.ReturnStatus; import com.dispose.pojo.po.ReturnStatus;
import com.dispose.pojo.vo.auth.LoginRsp; import com.dispose.pojo.vo.auth.LoginRsp;
import com.dispose.test.Global.InitTestEnvironment;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.junit.Assert; import org.junit.Assert;

View File

@ -1,9 +1,8 @@
package com.dispose.test.controller; package com.dispose.test.controller;
import com.dispose.common.GlobalVar;
import com.dispose.test.Global.InitTestEnvironment;
import com.dispose.common.DisposeTaskStatus; import com.dispose.common.DisposeTaskStatus;
import com.dispose.common.ErrorCode; import com.dispose.common.ErrorCode;
import com.dispose.common.GlobalVar;
import com.dispose.mapper.DisposeTaskMapper; import com.dispose.mapper.DisposeTaskMapper;
import com.dispose.pojo.po.ReturnStatus; import com.dispose.pojo.po.ReturnStatus;
import com.dispose.pojo.vo.common.DisposeCapacity; import com.dispose.pojo.vo.common.DisposeCapacity;
@ -13,6 +12,7 @@ import com.dispose.pojo.vo.information.DisposeNodeData;
import com.dispose.pojo.vo.information.DisposeNodeListRsp; import com.dispose.pojo.vo.information.DisposeNodeListRsp;
import com.dispose.pojo.vo.information.NodeTaskData; import com.dispose.pojo.vo.information.NodeTaskData;
import com.dispose.pojo.vo.information.NodeTaskRsp; import com.dispose.pojo.vo.information.NodeTaskRsp;
import com.dispose.test.Global.InitTestEnvironment;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.junit.Assert; import org.junit.Assert;
@ -231,17 +231,8 @@ public class DeviceNodeInfoControllerSmokeTest extends InitTestEnvironment {
Assert.assertNotNull(dpData); Assert.assertNotNull(dpData);
Assert.assertNotNull(dpData.getId()); Assert.assertNotNull(dpData.getId());
//Assert.assertNotNull(dpData.getType());
Assert.assertNotNull(dpData.getIp());
Assert.assertNotNull(dpData.getStatus()); Assert.assertNotNull(dpData.getStatus());
Assert.assertNotNull(dpData.getMessage()); Assert.assertNotNull(dpData.getMessage());
Assert.assertNotNull(dpData.getCapacity());
DisposeCapacity taskInfoData = dpData.getCapacity().get(0);
Assert.assertNotNull(taskInfoData);
Assert.assertNotNull(taskInfoData.getType());
Assert.assertNotNull(taskInfoData.getDisposeIp());
} }
/** /**

View File

@ -1,9 +1,8 @@
package com.dispose.test.controller; package com.dispose.test.controller;
import com.dispose.common.GlobalVar;
import com.dispose.test.Global.InitTestEnvironment;
import com.dispose.common.ConstValue; import com.dispose.common.ConstValue;
import com.dispose.common.ErrorCode; import com.dispose.common.ErrorCode;
import com.dispose.common.GlobalVar;
import com.dispose.mapper.DisposeDeviceMapper; import com.dispose.mapper.DisposeDeviceMapper;
import com.dispose.pojo.dto.ProtocolReqDTO; import com.dispose.pojo.dto.ProtocolReqDTO;
import com.dispose.pojo.entity.DisposeDevice; import com.dispose.pojo.entity.DisposeDevice;
@ -24,6 +23,7 @@ import com.dispose.pojo.vo.information.VersionListRsp;
import com.dispose.pojo.vo.information.VersionRsp; import com.dispose.pojo.vo.information.VersionRsp;
import com.dispose.service.DisposeNodeManager; import com.dispose.service.DisposeNodeManager;
import com.dispose.service.UserAccountService; import com.dispose.service.UserAccountService;
import com.dispose.test.Global.InitTestEnvironment;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Assert; import org.junit.Assert;
import org.junit.FixMethodOrder; import org.junit.FixMethodOrder;
@ -160,12 +160,18 @@ public class DeviceNodeInfoControllerTest extends InitTestEnvironment {
for (VersionRsp versionRsp : verList for (VersionRsp versionRsp : verList
) { ) {
if (verifyDeviceIdExists(versionRsp.getId())) { Assert.assertNotNull(versionRsp);
Assert.assertEquals(Long.valueOf(versionRsp.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertNotNull(versionRsp.getId()); Assert.assertNotNull(versionRsp.getId());
Assert.assertNotNull(versionRsp.getStatus());
Assert.assertNotNull(versionRsp.getMessage());
if (verifyDeviceIdExists(versionRsp.getId())) {
Assert.assertNotNull(versionRsp.getVersion()); Assert.assertNotNull(versionRsp.getVersion());
Assert.assertEquals(Long.valueOf(versionRsp.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertEquals(versionRsp.getMessage(), ErrorCode.ERR_OK.getMsg());
} else { } else {
Assert.assertNotEquals(Long.valueOf(versionRsp.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertNotEquals(Long.valueOf(versionRsp.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertNotEquals(versionRsp.getMessage(), ErrorCode.ERR_OK.getMsg());
} }
} }
} }
@ -208,17 +214,22 @@ public class DeviceNodeInfoControllerTest extends InitTestEnvironment {
for (VersionRsp versionRsp : verList for (VersionRsp versionRsp : verList
) { ) {
if (verifyDeviceIdExists(versionRsp.getId())) { Assert.assertNotNull(versionRsp);
Assert.assertEquals(Long.valueOf(versionRsp.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertNotNull(versionRsp.getId()); Assert.assertNotNull(versionRsp.getId());
Assert.assertNotNull(versionRsp.getStatus());
Assert.assertNotNull(versionRsp.getMessage());
if (verifyDeviceIdExists(versionRsp.getId())) {
Assert.assertNotNull(versionRsp.getVersion()); Assert.assertNotNull(versionRsp.getVersion());
Assert.assertEquals(Long.valueOf(versionRsp.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertEquals(versionRsp.getMessage(), ErrorCode.ERR_OK.getMsg());
} else { } else {
Assert.assertNotEquals(Long.valueOf(versionRsp.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertNotEquals(Long.valueOf(versionRsp.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertNotEquals(versionRsp.getMessage(), ErrorCode.ERR_OK.getMsg());
} }
} }
} }
/** /**
* T 2 get device info. * T 2 get device info.
* *
@ -257,16 +268,20 @@ public class DeviceNodeInfoControllerTest extends InitTestEnvironment {
List<DeviceInfoData> deviceInfoList = deviceInfoRsp.getItems(); List<DeviceInfoData> deviceInfoList = deviceInfoRsp.getItems();
for (DeviceInfoData d : deviceInfoList for (DeviceInfoData d : deviceInfoList
) { ) {
if (verifyDeviceIdExists(d.getId())) { Assert.assertNotNull(d);
Assert.assertNotNull(d.getId()); Assert.assertNotNull(d.getId());
Assert.assertEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertNotNull(String.valueOf(d.getStatus()));
} else { Assert.assertNotNull(d.getMessage());
Assert.assertNotNull(d.getId());
Assert.assertNotEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
}
}
}
if (verifyDeviceIdExists(d.getId())) {
Assert.assertEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertEquals(d.getMessage(), ErrorCode.ERR_OK.getMsg());
} else {
Assert.assertNotEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertNotEquals(d.getMessage(), ErrorCode.ERR_OK.getMsg());
}
}
}
/** /**
* T 2 get device info all. * T 2 get device info all.
@ -306,16 +321,20 @@ public class DeviceNodeInfoControllerTest extends InitTestEnvironment {
List<DeviceInfoData> deviceInfoList = deviceInfoRsp.getItems(); List<DeviceInfoData> deviceInfoList = deviceInfoRsp.getItems();
for (DeviceInfoData d : deviceInfoList for (DeviceInfoData d : deviceInfoList
) { ) {
if (verifyDeviceIdExists(d.getId())) { Assert.assertNotNull(d);
Assert.assertNotNull(d.getId()); Assert.assertNotNull(d.getId());
Assert.assertEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertNotNull(String.valueOf(d.getStatus()));
} else { Assert.assertNotNull(d.getMessage());
Assert.assertNotNull(d.getId());
Assert.assertNotEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
}
}
}
if (verifyDeviceIdExists(d.getId())) {
Assert.assertEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertEquals(d.getMessage(), ErrorCode.ERR_OK.getMsg());
} else {
Assert.assertNotEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertNotEquals(d.getMessage(), ErrorCode.ERR_OK.getMsg());
}
}
}
/** /**
* T 3 get device capacity. * T 3 get device capacity.
@ -355,18 +374,24 @@ public class DeviceNodeInfoControllerTest extends InitTestEnvironment {
List<DeviceCapacityData> deviceCapacityList = deviceCapacityRsp.getItems(); List<DeviceCapacityData> deviceCapacityList = deviceCapacityRsp.getItems();
for (DeviceCapacityData d : deviceCapacityList for (DeviceCapacityData d : deviceCapacityList
) { ) {
if (verifyDeviceIdExists(d.getId())) { Assert.assertNotNull(d);
Assert.assertNotNull(d.getId()); Assert.assertNotNull(d.getId());
Assert.assertEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertNotNull(String.valueOf(d.getStatus()));
if (d.getCapacity().size() != 0) { Assert.assertNotNull(d.getMessage());
if (verifyDeviceIdExists(d.getId())) {
if (d.getCapacity().size() > 0) {
for (DisposeCapacity cap : d.getCapacity() for (DisposeCapacity cap : d.getCapacity()
) { ) {
Assert.assertNotNull(cap.getType()); Assert.assertNotNull(cap.getType());
} }
Assert.assertEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertEquals(d.getMessage(), ErrorCode.ERR_OK.getMsg());
} }
} else { } else {
Assert.assertNotNull(d.getId());
Assert.assertNotEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertNotEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertNotEquals(d.getMessage(), ErrorCode.ERR_OK.getMsg());
} }
} }
} }
@ -410,18 +435,24 @@ public class DeviceNodeInfoControllerTest extends InitTestEnvironment {
List<DeviceCapacityData> deviceCapacityList = deviceCapacityRsp.getItems(); List<DeviceCapacityData> deviceCapacityList = deviceCapacityRsp.getItems();
for (DeviceCapacityData d : deviceCapacityList for (DeviceCapacityData d : deviceCapacityList
) { ) {
if (verifyDeviceIdExists(d.getId())) { Assert.assertNotNull(d);
Assert.assertNotNull(d.getId()); Assert.assertNotNull(d.getId());
Assert.assertEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertNotNull(String.valueOf(d.getStatus()));
if (d.getCapacity().size() != 0) { Assert.assertNotNull(d.getMessage());
if (verifyDeviceIdExists(d.getId())) {
if (d.getCapacity().size() > 0) {
for (DisposeCapacity cap : d.getCapacity() for (DisposeCapacity cap : d.getCapacity()
) { ) {
Assert.assertNotNull(cap.getType()); Assert.assertNotNull(cap.getType());
} }
Assert.assertEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertEquals(d.getMessage(), ErrorCode.ERR_OK.getMsg());
} }
} else { } else {
Assert.assertNotNull(d.getId());
Assert.assertNotEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertNotEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertNotEquals(d.getMessage(), ErrorCode.ERR_OK.getMsg());
} }
} }
} }
@ -455,7 +486,6 @@ public class DeviceNodeInfoControllerTest extends InitTestEnvironment {
.getResponse() .getResponse()
.getContentAsString(); .getContentAsString();
//String regex = "\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z";
String msgContent = verifyRep(protectedIp, reqTimeStamp); String msgContent = verifyRep(protectedIp, reqTimeStamp);
System.out.print("msgContent=" + msgContent); System.out.print("msgContent=" + msgContent);
@ -465,23 +495,25 @@ public class DeviceNodeInfoControllerTest extends InitTestEnvironment {
List<DeviceCapacityData> deviceCapacityList = deviceCapacityRsp.getItems(); List<DeviceCapacityData> deviceCapacityList = deviceCapacityRsp.getItems();
for (DeviceCapacityData d : deviceCapacityList for (DeviceCapacityData d : deviceCapacityList
) { ) {
if (verifyDeviceIdExists(d.getId())) { Assert.assertNotNull(d);
Assert.assertNotNull(d.getId()); Assert.assertNotNull(d.getId());
Assert.assertEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertNotNull(String.valueOf(d.getStatus()));
if (d.getCapacity().size() != 0) { Assert.assertNotNull(d.getMessage());
if (verifyDeviceIdExists(d.getId())) {
if (d.getCapacity().size() > 0) {
for (DisposeCapacity cap : d.getCapacity() for (DisposeCapacity cap : d.getCapacity()
) { ) {
Assert.assertNotNull(cap.getType()); Assert.assertNotNull(cap.getType());
Assert.assertNotNull(cap.getDisposeIp()); Assert.assertNotNull(cap.getDisposeIp());
//String[] disposeIps = cap.getDisposeIp().split(",");
//for (String disposeIp : disposeIps) {
//Assert.assertTrue(disposeIp.matches(regex));
//}
} }
Assert.assertEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertEquals(d.getMessage(), ErrorCode.ERR_OK.getMsg());
} }
} else { } else {
Assert.assertNotNull(d.getId());
Assert.assertNotEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertNotEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertNotEquals(d.getMessage(), ErrorCode.ERR_OK.getMsg());
} }
} }
} }
@ -515,7 +547,6 @@ public class DeviceNodeInfoControllerTest extends InitTestEnvironment {
.getResponse() .getResponse()
.getContentAsString(); .getContentAsString();
//String regex = "\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z";
String msgContent = verifyRep(protectedIpAll, reqTimeStamp); String msgContent = verifyRep(protectedIpAll, reqTimeStamp);
System.out.print("msgContent=" + msgContent); System.out.print("msgContent=" + msgContent);
@ -525,27 +556,28 @@ public class DeviceNodeInfoControllerTest extends InitTestEnvironment {
List<DeviceCapacityData> deviceCapacityList = deviceCapacityRsp.getItems(); List<DeviceCapacityData> deviceCapacityList = deviceCapacityRsp.getItems();
for (DeviceCapacityData d : deviceCapacityList for (DeviceCapacityData d : deviceCapacityList
) { ) {
if (verifyDeviceIdExists(d.getId())) { Assert.assertNotNull(d);
Assert.assertNotNull(d.getId()); Assert.assertNotNull(d.getId());
Assert.assertEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertNotNull(String.valueOf(d.getStatus()));
if (d.getCapacity().size() != 0) { Assert.assertNotNull(d.getMessage());
if (verifyDeviceIdExists(d.getId())) {
if (d.getCapacity().size() > 0) {
for (DisposeCapacity cap : d.getCapacity() for (DisposeCapacity cap : d.getCapacity()
) { ) {
Assert.assertNotNull(cap.getType()); Assert.assertNotNull(cap.getType());
Assert.assertNotNull(cap.getDisposeIp()); Assert.assertNotNull(cap.getDisposeIp());
//String[] disposeIps = cap.getDisposeIp().split(",");
//for (String disposeIp : disposeIps) {
//Assert.assertTrue(disposeIp.matches(regex));
//}
}
}
} else {
Assert.assertNotNull(d.getId());
Assert.assertNotEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
}
}
} }
Assert.assertEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertEquals(d.getMessage(), ErrorCode.ERR_OK.getMsg());
}
} else {
Assert.assertNotEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertNotEquals(d.getMessage(), ErrorCode.ERR_OK.getMsg());
}
}
}
/** /**
* T 3 get dispose node list. * T 3 get dispose node list.
@ -576,7 +608,6 @@ public class DeviceNodeInfoControllerTest extends InitTestEnvironment {
.getResponse() .getResponse()
.getContentAsString(); .getContentAsString();
String regex = "\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z";
String msgContent = verifyRep(nodeList, reqTimeStamp); String msgContent = verifyRep(nodeList, reqTimeStamp);
System.out.print("msgContent=" + msgContent); System.out.print("msgContent=" + msgContent);
@ -586,16 +617,20 @@ public class DeviceNodeInfoControllerTest extends InitTestEnvironment {
List<DisposeNodeData> disposeNodeDataList = disposeNodeListRsp.getItems(); List<DisposeNodeData> disposeNodeDataList = disposeNodeListRsp.getItems();
for (DisposeNodeData d : disposeNodeDataList for (DisposeNodeData d : disposeNodeDataList
) { ) {
if (verifyDeviceIdExists(d.getId())) { Assert.assertNotNull(d);
Assert.assertNotNull(d.getId()); Assert.assertNotNull(d.getId());
Assert.assertEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertNotNull(String.valueOf(d.getStatus()));
Assert.assertNotNull(d.getMessage());
if (verifyDeviceIdExists(d.getId())) {
Assert.assertNotNull(String.valueOf(d.getType())); Assert.assertNotNull(String.valueOf(d.getType()));
Assert.assertNotNull(d.getIp()); Assert.assertNotNull(d.getIp());
Assert.assertTrue(d.getIp().matches(regex));
Assert.assertNotNull(d.getName()); Assert.assertNotNull(d.getName());
Assert.assertEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertEquals(d.getMessage(), ErrorCode.ERR_OK.getMsg());
} else { } else {
Assert.assertNotNull(d.getId());
Assert.assertNotEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertNotEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertNotEquals(d.getMessage(), ErrorCode.ERR_OK.getMsg());
} }
} }
} }
@ -629,7 +664,6 @@ public class DeviceNodeInfoControllerTest extends InitTestEnvironment {
.getResponse() .getResponse()
.getContentAsString(); .getContentAsString();
String regex = "\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z";
String msgContent = verifyRep(nodeListAll, reqTimeStamp); String msgContent = verifyRep(nodeListAll, reqTimeStamp);
System.out.print("msgContent=" + msgContent); System.out.print("msgContent=" + msgContent);
@ -639,16 +673,20 @@ public class DeviceNodeInfoControllerTest extends InitTestEnvironment {
List<DisposeNodeData> disposeNodeDataList = disposeNodeListRsp.getItems(); List<DisposeNodeData> disposeNodeDataList = disposeNodeListRsp.getItems();
for (DisposeNodeData d : disposeNodeDataList for (DisposeNodeData d : disposeNodeDataList
) { ) {
if (verifyDeviceIdExists(d.getId())) { Assert.assertNotNull(d);
Assert.assertNotNull(d.getId()); Assert.assertNotNull(d.getId());
Assert.assertEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertNotNull(String.valueOf(d.getStatus()));
Assert.assertNotNull(d.getMessage());
if (verifyDeviceIdExists(d.getId())) {
Assert.assertNotNull(String.valueOf(d.getType())); Assert.assertNotNull(String.valueOf(d.getType()));
Assert.assertNotNull(d.getIp()); Assert.assertNotNull(d.getIp());
Assert.assertTrue(d.getIp().matches(regex));
Assert.assertNotNull(d.getName()); Assert.assertNotNull(d.getName());
Assert.assertEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertEquals(d.getMessage(), ErrorCode.ERR_OK.getMsg());
} else { } else {
Assert.assertNotNull(d.getId());
Assert.assertNotEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertNotEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertNotEquals(d.getMessage(), ErrorCode.ERR_OK.getMsg());
} }
} }
} }
@ -682,7 +720,6 @@ public class DeviceNodeInfoControllerTest extends InitTestEnvironment {
.getResponse() .getResponse()
.getContentAsString(); .getContentAsString();
String regex = "\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z";
String msgContent = verifyRep(disposeNodeDetails, reqTimeStamp); String msgContent = verifyRep(disposeNodeDetails, reqTimeStamp);
System.out.print("msgContent=" + msgContent); System.out.print("msgContent=" + msgContent);
@ -692,21 +729,26 @@ public class DeviceNodeInfoControllerTest extends InitTestEnvironment {
List<DisposeNodeData> disposeNodeDataList = nodeDetailsRsp.getItems(); List<DisposeNodeData> disposeNodeDataList = nodeDetailsRsp.getItems();
for (DisposeNodeData d : disposeNodeDataList for (DisposeNodeData d : disposeNodeDataList
) { ) {
if (verifyDeviceIdExists(d.getId())) { Assert.assertNotNull(d);
Assert.assertNotNull(d.getId()); Assert.assertNotNull(d.getId());
Assert.assertEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertNotNull(String.valueOf(d.getStatus()));
Assert.assertNotNull(d.getMessage());
if (verifyDeviceIdExists(d.getId())) {
Assert.assertNotNull(String.valueOf(d.getType())); Assert.assertNotNull(String.valueOf(d.getType()));
Assert.assertNotNull(d.getIp()); Assert.assertNotNull(d.getIp());
Assert.assertTrue(d.getIp().matches(regex));
Assert.assertNotNull(d.getName()); Assert.assertNotNull(d.getName());
for (DisposeCapacity cap : d.getCapacity() for (DisposeCapacity cap : d.getCapacity()
) { ) {
Assert.assertNotNull(cap.getType()); Assert.assertNotNull(cap.getType());
Assert.assertNotNull(cap.getDisposeIp()); Assert.assertNotNull(cap.getDisposeIp());
} }
Assert.assertEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertEquals(d.getMessage(), ErrorCode.ERR_OK.getMsg());
} else { } else {
Assert.assertNotNull(d.getId());
Assert.assertNotEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertNotEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertNotEquals(d.getMessage(), ErrorCode.ERR_OK.getMsg());
} }
} }
} }
@ -740,7 +782,6 @@ public class DeviceNodeInfoControllerTest extends InitTestEnvironment {
.getResponse() .getResponse()
.getContentAsString(); .getContentAsString();
String regex = "\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z";
String msgContent = verifyRep(disposeNodeDetailsAll, reqTimeStamp); String msgContent = verifyRep(disposeNodeDetailsAll, reqTimeStamp);
System.out.print("msgContent=" + msgContent); System.out.print("msgContent=" + msgContent);
@ -750,21 +791,26 @@ public class DeviceNodeInfoControllerTest extends InitTestEnvironment {
List<DisposeNodeData> disposeNodeDataList = nodeDetailsRsp.getItems(); List<DisposeNodeData> disposeNodeDataList = nodeDetailsRsp.getItems();
for (DisposeNodeData d : disposeNodeDataList for (DisposeNodeData d : disposeNodeDataList
) { ) {
if (verifyDeviceIdExists(d.getId())) { Assert.assertNotNull(d);
Assert.assertNotNull(d.getId()); Assert.assertNotNull(d.getId());
Assert.assertEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertNotNull(String.valueOf(d.getStatus()));
Assert.assertNotNull(d.getMessage());
if (verifyDeviceIdExists(d.getId())) {
Assert.assertNotNull(String.valueOf(d.getType())); Assert.assertNotNull(String.valueOf(d.getType()));
Assert.assertNotNull(d.getIp()); Assert.assertNotNull(d.getIp());
Assert.assertTrue(d.getIp().matches(regex));
Assert.assertNotNull(d.getName()); Assert.assertNotNull(d.getName());
for (DisposeCapacity cap : d.getCapacity() for (DisposeCapacity cap : d.getCapacity()
) { ) {
Assert.assertNotNull(cap.getType()); Assert.assertNotNull(cap.getType());
Assert.assertNotNull(cap.getDisposeIp()); Assert.assertNotNull(cap.getDisposeIp());
} }
Assert.assertEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertEquals(d.getMessage(), ErrorCode.ERR_OK.getMsg());
} else { } else {
Assert.assertNotNull(d.getId());
Assert.assertNotEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertNotEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertNotEquals(d.getMessage(), ErrorCode.ERR_OK.getMsg());
} }
} }
} }
@ -796,21 +842,25 @@ public class DeviceNodeInfoControllerTest extends InitTestEnvironment {
String msgContent = verifyRep(linkstatus, reqTimeStamp); String msgContent = verifyRep(linkstatus, reqTimeStamp);
System.out.print("msgContent=" + msgContent); System.out.print("msgContent=" + msgContent);
// List<LinkStatusRsp> linkStatusList = objectMapper.readValue(msgContent, new TypeReference<List<LinkStatusRsp>>() {
// });
LinkStatusListRsp linkStatusListRsp = objectMapper.readValue(msgContent, LinkStatusListRsp.class); LinkStatusListRsp linkStatusListRsp = objectMapper.readValue(msgContent, LinkStatusListRsp.class);
List<LinkStatusRsp> linkStatusList = linkStatusListRsp.getItems(); List<LinkStatusRsp> linkStatusList = linkStatusListRsp.getItems();
for (LinkStatusRsp linkStatusRsp : linkStatusList for (LinkStatusRsp linkStatusRsp : linkStatusList
) { ) {
if (verifyDeviceIdExists(linkStatusRsp.getId())) { Assert.assertNotNull(linkStatusRsp);
Assert.assertEquals(Long.valueOf(linkStatusRsp.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertNotNull(linkStatusRsp.getId()); Assert.assertNotNull(linkStatusRsp.getId());
Assert.assertNotNull(String.valueOf(linkStatusRsp.getOnline())); Assert.assertNotNull(String.valueOf(linkStatusRsp.getOnline()));
Assert.assertNotNull(String.valueOf(linkStatusRsp.getStatus()));
Assert.assertNotNull(linkStatusRsp.getMessage());
if (verifyDeviceIdExists(linkStatusRsp.getId())) {
Assert.assertEquals(String.valueOf(linkStatusRsp.getOnline()), "1"); Assert.assertEquals(String.valueOf(linkStatusRsp.getOnline()), "1");
Assert.assertEquals(Long.valueOf(linkStatusRsp.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertEquals(linkStatusRsp.getMessage(), ErrorCode.ERR_OK.getMsg());
} else { } else {
Assert.assertNotEquals(Long.valueOf(linkStatusRsp.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertEquals(String.valueOf(linkStatusRsp.getOnline()), "0"); Assert.assertEquals(String.valueOf(linkStatusRsp.getOnline()), "0");
Assert.assertNotEquals(Long.valueOf(linkStatusRsp.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertNotEquals(linkStatusRsp.getMessage(), ErrorCode.ERR_OK.getMsg());
} }
} }
} }
@ -850,14 +900,20 @@ public class DeviceNodeInfoControllerTest extends InitTestEnvironment {
for (LinkStatusRsp linkStatusRsp : linkStatusList for (LinkStatusRsp linkStatusRsp : linkStatusList
) { ) {
if (verifyDeviceIdExists(linkStatusRsp.getId())) { Assert.assertNotNull(linkStatusRsp);
Assert.assertEquals(Long.valueOf(linkStatusRsp.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertNotNull(linkStatusRsp.getId()); Assert.assertNotNull(linkStatusRsp.getId());
Assert.assertNotNull(String.valueOf(linkStatusRsp.getOnline())); Assert.assertNotNull(String.valueOf(linkStatusRsp.getOnline()));
Assert.assertNotNull(String.valueOf(linkStatusRsp.getStatus()));
Assert.assertNotNull(linkStatusRsp.getMessage());
if (verifyDeviceIdExists(linkStatusRsp.getId())) {
Assert.assertEquals(String.valueOf(linkStatusRsp.getOnline()), "1"); Assert.assertEquals(String.valueOf(linkStatusRsp.getOnline()), "1");
Assert.assertEquals(Long.valueOf(linkStatusRsp.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertEquals(linkStatusRsp.getMessage(), ErrorCode.ERR_OK.getMsg());
} else { } else {
Assert.assertNotEquals(Long.valueOf(linkStatusRsp.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertEquals(String.valueOf(linkStatusRsp.getOnline()), "0"); Assert.assertEquals(String.valueOf(linkStatusRsp.getOnline()), "0");
Assert.assertNotEquals(Long.valueOf(linkStatusRsp.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertNotEquals(linkStatusRsp.getMessage(), ErrorCode.ERR_OK.getMsg());
} }
} }
} }
@ -894,15 +950,19 @@ public class DeviceNodeInfoControllerTest extends InitTestEnvironment {
List<NodeTaskData> nodeTaskData = runTaskRsp.getItems(); List<NodeTaskData> nodeTaskData = runTaskRsp.getItems();
for (NodeTaskData d : nodeTaskData for (NodeTaskData d : nodeTaskData
) { ) {
if (verifyDeviceIdExists(d.getId())) { Assert.assertNotNull(d);
Assert.assertNotNull(d.getId()); Assert.assertNotNull(d.getId());
Assert.assertNotNull(String.valueOf(d.getStatus()));
Assert.assertNotNull(d.getMessage());
if (verifyDeviceIdExists(d.getId())) {
// no task // no task
if (d.getTaskArray().size() == 0) { if (d.getTaskArray().size() == 0) {
Assert.assertNotEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertNotEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
} else { } else {
Assert.assertEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
} }
Assert.assertNotEquals(d.getMessage(), ErrorCode.ERR_OK.getMsg());
Assert.assertNotNull(d.getTaskArray()); Assert.assertNotNull(d.getTaskArray());
for (TaskInfoData task : d.getTaskArray() for (TaskInfoData task : d.getTaskArray()
@ -913,9 +973,10 @@ public class DeviceNodeInfoControllerTest extends InitTestEnvironment {
Assert.assertNotNull(task.getDisposeTime()); Assert.assertNotNull(task.getDisposeTime());
Assert.assertNotNull(task.getDisposeIp()); Assert.assertNotNull(task.getDisposeIp());
} }
} else { } else {
Assert.assertNotNull(d.getId());
Assert.assertNotEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertNotEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertNotEquals(d.getMessage(), ErrorCode.ERR_OK.getMsg());
} }
} }
} }
@ -953,15 +1014,19 @@ public class DeviceNodeInfoControllerTest extends InitTestEnvironment {
List<NodeTaskData> nodeTaskData = runTaskRsp.getItems(); List<NodeTaskData> nodeTaskData = runTaskRsp.getItems();
for (NodeTaskData d : nodeTaskData for (NodeTaskData d : nodeTaskData
) { ) {
if (verifyDeviceIdExists(d.getId())) { Assert.assertNotNull(d);
Assert.assertNotNull(d.getId()); Assert.assertNotNull(d.getId());
Assert.assertNotNull(String.valueOf(d.getStatus()));
Assert.assertNotNull(d.getMessage());
if (verifyDeviceIdExists(d.getId())) {
// no task // no task
if (d.getTaskArray().size() == 0) { if (d.getTaskArray().size() == 0) {
Assert.assertNotEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertNotEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
} else { } else {
Assert.assertEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
} }
Assert.assertNotEquals(d.getMessage(), ErrorCode.ERR_OK.getMsg());
Assert.assertNotNull(d.getTaskArray()); Assert.assertNotNull(d.getTaskArray());
for (TaskInfoData task : d.getTaskArray() for (TaskInfoData task : d.getTaskArray()
@ -972,9 +1037,10 @@ public class DeviceNodeInfoControllerTest extends InitTestEnvironment {
Assert.assertNotNull(task.getDisposeTime()); Assert.assertNotNull(task.getDisposeTime());
Assert.assertNotNull(task.getDisposeIp()); Assert.assertNotNull(task.getDisposeIp());
} }
} else { } else {
Assert.assertNotNull(d.getId());
Assert.assertNotEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertNotEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertNotEquals(d.getMessage(), ErrorCode.ERR_OK.getMsg());
} }
} }
} }
@ -1012,11 +1078,18 @@ public class DeviceNodeInfoControllerTest extends InitTestEnvironment {
List<NodeTaskData> allTaskData = allTaskRsp.getItems(); List<NodeTaskData> allTaskData = allTaskRsp.getItems();
for (NodeTaskData d : allTaskData for (NodeTaskData d : allTaskData
) { ) {
if (verifyDeviceIdExists(d.getId())) { Assert.assertNotNull(d);
Assert.assertNotNull(d.getId()); Assert.assertNotNull(d.getId());
Assert.assertNotNull(String.valueOf(d.getStatus()));
Assert.assertNotNull(d.getMessage());
if (verifyDeviceIdExists(d.getId())) {
// no task // no task
if (d.getTaskArray().size() == 0) {
Assert.assertNotEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
} else {
Assert.assertEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
}
Assert.assertNotNull(d.getTaskArray()); Assert.assertNotNull(d.getTaskArray());
for (TaskInfoData task : d.getTaskArray() for (TaskInfoData task : d.getTaskArray()
@ -1029,9 +1102,8 @@ public class DeviceNodeInfoControllerTest extends InitTestEnvironment {
Assert.assertNotNull(task.getDisposeIp()); Assert.assertNotNull(task.getDisposeIp());
} }
} else { } else {
Assert.assertNotNull(d.getId());
Assert.assertNotEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertNotEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertNotNull(d.getTaskArray()); Assert.assertNotEquals(d.getMessage(), ErrorCode.ERR_OK.getMsg());
} }
} }
} }
@ -1069,11 +1141,18 @@ public class DeviceNodeInfoControllerTest extends InitTestEnvironment {
List<NodeTaskData> allTaskData = allTaskRsp.getItems(); List<NodeTaskData> allTaskData = allTaskRsp.getItems();
for (NodeTaskData d : allTaskData for (NodeTaskData d : allTaskData
) { ) {
if (verifyDeviceIdExists(d.getId())) { Assert.assertNotNull(d);
Assert.assertNotNull(d.getId()); Assert.assertNotNull(d.getId());
Assert.assertNotNull(String.valueOf(d.getStatus()));
Assert.assertNotNull(d.getMessage());
if (verifyDeviceIdExists(d.getId())) {
// no task // no task
if (d.getTaskArray().size() == 0) {
Assert.assertNotEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
} else {
Assert.assertEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
}
Assert.assertNotNull(d.getTaskArray()); Assert.assertNotNull(d.getTaskArray());
for (TaskInfoData task : d.getTaskArray() for (TaskInfoData task : d.getTaskArray()
@ -1086,9 +1165,8 @@ public class DeviceNodeInfoControllerTest extends InitTestEnvironment {
Assert.assertNotNull(task.getDisposeIp()); Assert.assertNotNull(task.getDisposeIp());
} }
} else { } else {
Assert.assertNotNull(d.getId()); Assert.assertNotEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertEquals(Long.valueOf(d.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertNotEquals(d.getMessage(), ErrorCode.ERR_OK.getMsg());
Assert.assertNotNull(d.getTaskArray());
} }
} }
} }

View File

@ -1,11 +1,14 @@
package com.dispose.test.controller; package com.dispose.test.controller;
import com.dispose.common.GlobalVar;
import com.dispose.pojo.vo.device.AddNodeRsp;
import com.dispose.test.Global.InitTestEnvironment;
import com.dispose.common.ErrorCode; import com.dispose.common.ErrorCode;
import com.dispose.common.GlobalVar;
import com.dispose.pojo.entity.DisposeDevice;
import com.dispose.pojo.vo.common.IDReturnStatus;
import com.dispose.pojo.vo.device.AddNodeRetData; import com.dispose.pojo.vo.device.AddNodeRetData;
import com.dispose.pojo.vo.device.AddNodeRsp;
import com.dispose.service.DisposeNodeManager; import com.dispose.service.DisposeNodeManager;
import com.dispose.test.Global.InitTestEnvironment;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.junit.Assert; import org.junit.Assert;
@ -24,7 +27,6 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.util.List; import java.util.List;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
@ -276,6 +278,214 @@ public class DeviceNodeManagerControllerQATest extends InitTestEnvironment {
} }
/**
* A 10 add device node ver json exception test.
*
* @throws Exception the exception
*/
@Test
public void a10_addDeviceNodeVerJsonExceptionTest() throws Exception {
String reqData = "{\"ver\":\"cryptoType\":0,\"timeStamp\":1587628826908," +
"\"msgContent\":\"{\\\"items\\\":[{\\\"areaCode\\\":0,\\\"ipAddr\\\":\\\"10.88.77.15\\\"," +
"\\\"manufacturer\\\":\\\"DPTech\\\",\\\"model\\\":\\\"UMC\\\",\\\"name\\\":\\\"中移杭研实验室清洗设备\\\"," +
"\\\"readme\\\":\\\"实验室测试设备\\\",\\\"type\\\":0,\\\"version\\\":\\\"5.7.13\\\"}]}\"}";
String ret = mockMvc.perform(MockMvcRequestBuilders
.put("/manager/device")
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", "Bearer " + getLogToken())
.content(reqData))
.andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(ErrorCode.ERR_PARAMEXCEPTION.getHttpCode()))
.andReturn()
.getResponse()
.getContentAsString();
AddNodeRetData rspInfo = objectMapper.readValue(verifyResp(ret), AddNodeRetData.class);
Assert.assertNotNull(rspInfo.getMessage());
Assert.assertNotNull(rspInfo.getStatus());
Assert.assertEquals(Long.valueOf(rspInfo.getStatus()), Long.valueOf(ErrorCode.ERR_PARAMEXCEPTION.getCode()));
}
/**
* A 11 add device node ver null exception test.
*
* @throws Exception the exception
*/
@Test
public void a11_addDeviceNodeVerNullExceptionTest() throws Exception {
String reqData = "{\"ver\":null,\"cryptoType\":0,\"timeStamp\":1587628826908," +
"\"msgContent\":\"{\\\"items\\\":[{\\\"areaCode\\\":0,\\\"ipAddr\\\":\\\"10.88.77.15\\\"," +
"\\\"manufacturer\\\":\\\"DPTech\\\",\\\"model\\\":\\\"UMC\\\",\\\"name\\\":\\\"中移杭研实验室清洗设备\\\"," +
"\\\"readme\\\":\\\"实验室测试设备\\\",\\\"type\\\":0,\\\"version\\\":\\\"5.7.13\\\"}]}\"}";
String ret = mockMvc.perform(MockMvcRequestBuilders
.put("/manager/device")
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", "Bearer " + getLogToken())
.content(reqData))
.andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(ErrorCode.ERR_PARAMEXCEPTION.getHttpCode()))
.andReturn()
.getResponse()
.getContentAsString();
AddNodeRetData rspInfo = objectMapper.readValue(verifyResp(ret), AddNodeRetData.class);
Assert.assertNotNull(rspInfo.getMessage());
Assert.assertNotNull(rspInfo.getStatus());
Assert.assertEquals(Long.valueOf(rspInfo.getStatus()), Long.valueOf(ErrorCode.ERR_PARAMEXCEPTION.getCode()));
}
/**
* A 12 add device node ver string exception test.
*
* @throws Exception the exception
*/
@Test
public void a12_addDeviceNodeVerStingChaExceptionTest() throws Exception {
String reqData = "{\"ver\":\"a\",\"cryptoType\":0,\"timeStamp\":1587628826908," +
"\"msgContent\":\"{\\\"items\\\":[{\\\"areaCode\\\":0,\\\"ipAddr\\\":\\\"10.88.77.15\\\"," +
"\\\"manufacturer\\\":\\\"DPTech\\\",\\\"model\\\":\\\"UMC\\\",\\\"name\\\":\\\"中移杭研实验室清洗设备\\\"," +
"\\\"readme\\\":\\\"实验室测试设备\\\",\\\"type\\\":0,\\\"version\\\":\\\"5.7.13\\\"}]}\"}";
String ret = mockMvc.perform(MockMvcRequestBuilders
.put("/manager/device")
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", "Bearer " + getLogToken())
.content(reqData))
.andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(ErrorCode.ERR_PARAMEXCEPTION.getHttpCode()))
.andReturn()
.getResponse()
.getContentAsString();
AddNodeRetData rspInfo = objectMapper.readValue(verifyResp(ret), AddNodeRetData.class);
Assert.assertNotNull(rspInfo.getMessage());
Assert.assertNotNull(rspInfo.getStatus());
Assert.assertEquals(Long.valueOf(rspInfo.getStatus()), Long.valueOf(ErrorCode.ERR_PARAMEXCEPTION.getCode()));
}
/**
* A 13 add device node ver string exception test.
*
* @throws Exception the exception
*/
@Test
public void a13_addDeviceNodeVerStingNumExceptionTest() throws Exception {
String reqData = "{\"ver\":\"1\",\"cryptoType\":0,\"timeStamp\":1587628826908," +
"\"msgContent\":\"{\\\"items\\\":[{\\\"areaCode\\\":0,\\\"ipAddr\\\":\\\"10.88.77.15\\\"," +
"\\\"manufacturer\\\":\\\"DPTech\\\",\\\"model\\\":\\\"UMC\\\",\\\"name\\\":\\\"中移杭研实验室清洗设备\\\"," +
"\\\"readme\\\":\\\"实验室测试设备\\\",\\\"type\\\":0,\\\"version\\\":\\\"5.7.13\\\"}]}\"}";
String ret = mockMvc.perform(MockMvcRequestBuilders
.put("/manager/device")
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", "Bearer " + getLogToken())
.content(reqData))
.andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(ErrorCode.ERR_VERSION.getHttpCode()))
.andReturn()
.getResponse()
.getContentAsString();
AddNodeRetData rspInfo = objectMapper.readValue(verifyResp(ret), AddNodeRetData.class);
Assert.assertNotNull(rspInfo.getMessage());
Assert.assertNotNull(rspInfo.getStatus());
Assert.assertEquals(Long.valueOf(rspInfo.getStatus()), Long.valueOf(ErrorCode.ERR_VERSION.getCode()));
}
/**
* A 14 add device node crypto json exception test.
*
* @throws Exception the exception
*/
@Test
public void a14_addDeviceNodeCryptoJsonExceptionTest() throws Exception {
String reqData = "{\"ver\":2,\"cryptoType\":\"timeStamp\":1587628826908," +
"\"msgContent\":\"{\\\"items\\\":[{\\\"areaCode\\\":0,\\\"ipAddr\\\":\\\"10.88.77.15\\\"," +
"\\\"manufacturer\\\":\\\"DPTech\\\",\\\"model\\\":\\\"UMC\\\",\\\"name\\\":\\\"中移杭研实验室清洗设备\\\"," +
"\\\"readme\\\":\\\"实验室测试设备\\\",\\\"type\\\":0,\\\"version\\\":\\\"5.7.13\\\"}]}\"}";
String ret = mockMvc.perform(MockMvcRequestBuilders
.put("/manager/device")
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", "Bearer " + getLogToken())
.content(reqData))
.andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(ErrorCode.ERR_PARAMEXCEPTION.getHttpCode()))
.andReturn()
.getResponse()
.getContentAsString();
AddNodeRetData rspInfo = objectMapper.readValue(verifyResp(ret), AddNodeRetData.class);
Assert.assertNotNull(rspInfo.getMessage());
Assert.assertNotNull(rspInfo.getStatus());
Assert.assertEquals(Long.valueOf(rspInfo.getStatus()), Long.valueOf(ErrorCode.ERR_PARAMEXCEPTION.getCode()));
}
/**
* A 15 add device node crypto null exception test.
*
* @throws Exception the exception
*/
@Test
public void a15_addDeviceNodeCryptoNullExceptionTest() throws Exception {
String reqData = "{\"ver\":2,\"cryptoType\":null,\"timeStamp\":1587628826908," +
"\"msgContent\":\"{\\\"items\\\":[{\\\"areaCode\\\":0,\\\"ipAddr\\\":\\\"10.88.77.15\\\"," +
"\\\"manufacturer\\\":\\\"DPTech\\\",\\\"model\\\":\\\"UMC\\\",\\\"name\\\":\\\"中移杭研实验室清洗设备\\\"," +
"\\\"readme\\\":\\\"实验室测试设备\\\",\\\"type\\\":0,\\\"version\\\":\\\"5.7.13\\\"}]}\"}";
String ret = mockMvc.perform(MockMvcRequestBuilders
.put("/manager/device")
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", "Bearer " + getLogToken())
.content(reqData))
.andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(ErrorCode.ERR_PARAMEXCEPTION.getHttpCode()))
.andReturn()
.getResponse()
.getContentAsString();
AddNodeRetData rspInfo = objectMapper.readValue(verifyResp(ret), AddNodeRetData.class);
Assert.assertNotNull(rspInfo.getMessage());
Assert.assertNotNull(rspInfo.getStatus());
Assert.assertEquals(Long.valueOf(rspInfo.getStatus()), Long.valueOf(ErrorCode.ERR_PARAMEXCEPTION.getCode()));
}
/**
* A 16 add device node crypto string exception test.
*
* @throws Exception the exception
*/
@Test
public void a16_addDeviceNodeCryptoStringExceptionTest() throws Exception {
String reqData = "{\"ver\":2,\"cryptoType\":\"a\",\"timeStamp\":1587628826908," +
"\"msgContent\":\"{\\\"items\\\":[{\\\"areaCode\\\":0,\\\"ipAddr\\\":\\\"10.88.77.15\\\"," +
"\\\"manufacturer\\\":\\\"DPTech\\\",\\\"model\\\":\\\"UMC\\\",\\\"name\\\":\\\"中移杭研实验室清洗设备\\\"," +
"\\\"readme\\\":\\\"实验室测试设备\\\",\\\"type\\\":0,\\\"version\\\":\\\"5.7.13\\\"}]}\"}";
String ret = mockMvc.perform(MockMvcRequestBuilders
.put("/manager/device")
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", "Bearer " + getLogToken())
.content(reqData))
.andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(ErrorCode.ERR_PARAMEXCEPTION.getHttpCode()))
.andReturn()
.getResponse()
.getContentAsString();
AddNodeRetData rspInfo = objectMapper.readValue(verifyResp(ret), AddNodeRetData.class);
Assert.assertNotNull(rspInfo.getMessage());
Assert.assertNotNull(rspInfo.getStatus());
Assert.assertEquals(Long.valueOf(rspInfo.getStatus()), Long.valueOf(ErrorCode.ERR_PARAMEXCEPTION.getCode()));
}
/** /**
* B 2 del device node Msg Empty exception test. * B 2 del device node Msg Empty exception test.
* *
@ -367,7 +577,7 @@ public class DeviceNodeManagerControllerQATest extends InitTestEnvironment {
String reqData = "{\"ver\":2,\"cryptoType\":0,\"timeStamp\":1587604308040,\"msgContent\":\"{\\\"id\\\":123}\"}"; String reqData = "{\"ver\":2,\"cryptoType\":0,\"timeStamp\":1587604308040,\"msgContent\":\"{\\\"id\\\":123}\"}";
String ret = mockMvc.perform(MockMvcRequestBuilders String ret = mockMvc.perform(MockMvcRequestBuilders
.put("/manager/device") .delete("/manager/device")
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.header("Authorization", GlobalVar.STRING_HTTP_AUTH_HEAD + getLogToken()) .header("Authorization", GlobalVar.STRING_HTTP_AUTH_HEAD + getLogToken())
.content(reqData)) .content(reqData))
@ -377,10 +587,134 @@ public class DeviceNodeManagerControllerQATest extends InitTestEnvironment {
.getResponse() .getResponse()
.getContentAsString(); .getContentAsString();
AddNodeRetData rspInfo = objectMapper.readValue(verifyResp(ret), AddNodeRetData.class); IDReturnStatus rspInfo = objectMapper.readValue(verifyResp(ret), IDReturnStatus.class);
Assert.assertNotNull(rspInfo.getMessage()); Assert.assertNotNull(rspInfo.getMessage());
Assert.assertNotNull(rspInfo.getStatus()); Assert.assertNotNull(rspInfo.getStatus());
Assert.assertEquals(Long.valueOf(rspInfo.getStatus()), Long.valueOf(ErrorCode.ERR_PARAMEXCEPTION.getCode())); Assert.assertEquals(Long.valueOf(rspInfo.getStatus()), Long.valueOf(ErrorCode.ERR_PARAMEXCEPTION.getCode()));
Assert.assertEquals(rspInfo.getMessage(), ErrorCode.ERR_PARAMEXCEPTION.getMsg());
}
/**
* B 6 del device node id empty exception test.
*
* @throws Exception the exception
*/
@Test
public void b6_delDeviceNodeIdEmptyExceptionTest() throws Exception {
String reqData = "{\"ver\":2,\"cryptoType\":0,\"timeStamp\":1587604308040,\"msgContent\":\"{\\\"id\\\":[]}\"}";
String ret = mockMvc.perform(MockMvcRequestBuilders
.delete("/manager/device")
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", GlobalVar.STRING_HTTP_AUTH_HEAD + getLogToken())
.content(reqData))
.andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(ErrorCode.ERR_PARAMEXCEPTION.getHttpCode()))
.andReturn()
.getResponse()
.getContentAsString();
IDReturnStatus rspInfo = objectMapper.readValue(verifyResp(ret), IDReturnStatus.class);
Assert.assertNotNull(rspInfo.getMessage());
Assert.assertNotNull(rspInfo.getStatus());
Assert.assertEquals(Long.valueOf(rspInfo.getStatus()), Long.valueOf(ErrorCode.ERR_PARAMEXCEPTION.getCode()));
Assert.assertEquals(rspInfo.getMessage(), ErrorCode.ERR_PARAMEXCEPTION.getMsg());
}
/**
* B 7 del device node id not exit exception test.
*
* @throws Exception the exception
*/
@Test
public void b7_delDeviceNodeIdNotExitExceptionTest() throws Exception {
//String reqData = "{\"ver\":2,\"cryptoType\":0,\"timeStamp\":1587604308040,\"msgContent\":\"{\\\"id\\\":[\\\"1\\\",\\\"666\\\"]}\"}";
String reqData = "{\"ver\":2,\"cryptoType\":0,\"timeStamp\":1587604308040,\"msgContent\":\"{\\\"id\\\":[\\\"555\\\"]}\"}";
String ret = mockMvc.perform(MockMvcRequestBuilders
.delete("/manager/device")
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", GlobalVar.STRING_HTTP_AUTH_HEAD + getLogToken())
.content(reqData))
.andDo(print()).andExpect(status().isOk())
//.andExpect(jsonPath("$.code").value(ErrorCode.ERR_PARAMEXCEPTION.getHttpCode()))
.andExpect(jsonPath("$.code").value(ErrorCode.ERR_OK.getHttpCode()))
.andReturn()
.getResponse()
.getContentAsString();
List<IDReturnStatus> delNodeList = objectMapper.readValue(verifyResp(ret), new TypeReference<List<IDReturnStatus>>() {});
for (IDReturnStatus rspInfo : delNodeList) {
Assert.assertNotNull(rspInfo);
Assert.assertNotNull(rspInfo.getId());
Assert.assertNotNull(rspInfo.getMessage());
Assert.assertNotNull(rspInfo.getStatus());
if (verifyDeviceIdExists(rspInfo.getId())) {
Assert.assertEquals(String.valueOf(rspInfo.getStatus()), String.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertEquals(rspInfo.getMessage(), ErrorCode.ERR_OK.getMsg());
} else {
Assert.assertEquals(String.valueOf(rspInfo.getStatus()), String.valueOf(ErrorCode.ERR_NOSUCHDEVICE.getCode()));
Assert.assertEquals(rspInfo.getMessage(), ErrorCode.ERR_NOSUCHDEVICE.getMsg());
}
// if (rspInfo.getStatus() == 0) {
// Assert.assertEquals(Long.valueOf(rspInfo.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
// Assert.assertEquals(rspInfo.getMessage(), ErrorCode.ERR_OK.getMsg());
// } else if (rspInfo.getStatus() == 19) {
// Assert.assertEquals(Long.valueOf(rspInfo.getStatus()), Long.valueOf(ErrorCode.ERR_NOSUCHDEVICE.getCode()));
// Assert.assertEquals(rspInfo.getMessage(), ErrorCode.ERR_NOSUCHDEVICE.getMsg());
// }
}
}
/**
* B 8 del device node id string character exception test.
*
* @throws Exception the exception
*/
@Test
public void b8_delDeviceNodeIdStingChaExceptionTest() throws Exception {
String reqData = "{\"ver\":2,\"cryptoType\":0,\"timeStamp\":1587604308040,\"msgContent\":\"{\\\"id\\\":[\\\"bbb\\\"]}\"}";
String ret = mockMvc.perform(MockMvcRequestBuilders
.delete("/manager/device")
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", GlobalVar.STRING_HTTP_AUTH_HEAD + getLogToken())
.content(reqData))
.andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(ErrorCode.ERR_PARAMEXCEPTION.getHttpCode()))
.andReturn()
.getResponse()
.getContentAsString();
IDReturnStatus rspInfo = objectMapper.readValue(verifyResp(ret), IDReturnStatus.class);
Assert.assertNotNull(rspInfo.getMessage());
Assert.assertNotNull(rspInfo.getStatus());
Assert.assertEquals(Long.valueOf(rspInfo.getStatus()), Long.valueOf(ErrorCode.ERR_PARAMEXCEPTION.getCode()));
Assert.assertEquals(rspInfo.getMessage(), ErrorCode.ERR_PARAMEXCEPTION.getMsg());
}
/**
* Verify device id exists boolean.
*
* @param deviceId the device id
* @return the boolean
*/
public boolean verifyDeviceIdExists(String deviceId) {
boolean exists = false;
List<DisposeDevice> decs = disposeNodeManager.getAllDisposeDevice();
if (decs != null && decs.size() > 0) {
for (DisposeDevice d : decs) {
if (String.valueOf(d.getId()).equals(deviceId)) {
exists = true;
break;
}
}
}
return exists;
} }
} }

View File

@ -1,14 +1,14 @@
package com.dispose.test.controller; package com.dispose.test.controller;
import com.dispose.common.GlobalVar;
import com.dispose.test.Global.InitTestEnvironment;
import com.dispose.common.ErrorCode; import com.dispose.common.ErrorCode;
import com.dispose.common.GlobalVar;
import com.dispose.pojo.entity.DisposeDevice; import com.dispose.pojo.entity.DisposeDevice;
import com.dispose.pojo.po.MulReturnType; import com.dispose.pojo.po.MulReturnType;
import com.dispose.pojo.vo.common.IDReturnStatus; import com.dispose.pojo.vo.common.IDReturnStatus;
import com.dispose.pojo.vo.device.AddNodeRetData; import com.dispose.pojo.vo.device.AddNodeRetData;
import com.dispose.pojo.vo.device.AddNodeRsp; import com.dispose.pojo.vo.device.AddNodeRsp;
import com.dispose.service.DisposeNodeManager; import com.dispose.service.DisposeNodeManager;
import com.dispose.test.Global.InitTestEnvironment;
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;

View File

@ -1,10 +1,9 @@
package com.dispose.test.controller; package com.dispose.test.controller;
import com.dispose.common.GlobalVar;
import com.dispose.test.Global.InitTestEnvironment;
import com.dispose.common.ConstValue; import com.dispose.common.ConstValue;
import com.dispose.common.DisposeDeviceType; import com.dispose.common.DisposeDeviceType;
import com.dispose.common.ErrorCode; import com.dispose.common.ErrorCode;
import com.dispose.common.GlobalVar;
import com.dispose.pojo.dto.ProtocolReqDTO; import com.dispose.pojo.dto.ProtocolReqDTO;
import com.dispose.pojo.entity.DisposeDevice; import com.dispose.pojo.entity.DisposeDevice;
import com.dispose.pojo.po.MulReturnType; import com.dispose.pojo.po.MulReturnType;
@ -15,6 +14,7 @@ import com.dispose.pojo.vo.device.AddNodeReq;
import com.dispose.pojo.vo.device.AddNodeRetData; import com.dispose.pojo.vo.device.AddNodeRetData;
import com.dispose.pojo.vo.device.AddNodeRsp; import com.dispose.pojo.vo.device.AddNodeRsp;
import com.dispose.service.DisposeNodeManager; import com.dispose.service.DisposeNodeManager;
import com.dispose.test.Global.InitTestEnvironment;
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@ -281,7 +281,7 @@ public class DeviceNodeManagerControllerTest extends InitTestEnvironment {
.header("Authorization", GlobalVar.STRING_HTTP_AUTH_HEAD + getLogToken()) .header("Authorization", GlobalVar.STRING_HTTP_AUTH_HEAD + getLogToken())
.content(objectMapper.writeValueAsString(reqInfo))) .content(objectMapper.writeValueAsString(reqInfo)))
.andDo(print()).andExpect(status().isOk()) .andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(525)) .andExpect(jsonPath("$.code").value(ErrorCode.ERR_OK.getHttpCode()))
.andReturn() .andReturn()
.getResponse() .getResponse()
.getContentAsString(); .getContentAsString();

View File

@ -1,11 +1,11 @@
package com.dispose.test.controller; package com.dispose.test.controller;
import com.dispose.common.GlobalVar;
import com.dispose.test.Global.InitTestEnvironment;
import com.dispose.common.ErrorCode; import com.dispose.common.ErrorCode;
import com.dispose.common.GlobalVar;
import com.dispose.pojo.vo.common.TaskInfoData; import com.dispose.pojo.vo.common.TaskInfoData;
import com.dispose.pojo.vo.task.StartTaskRsp; import com.dispose.pojo.vo.task.StartTaskRsp;
import com.dispose.pojo.vo.task.TaskInfoRsp; import com.dispose.pojo.vo.task.TaskInfoRsp;
import com.dispose.test.Global.InitTestEnvironment;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.junit.Assert; import org.junit.Assert;
@ -51,7 +51,7 @@ public class TaskControllerSmokeTest extends InitTestEnvironment {
private ObjectMapper objectMapper; private ObjectMapper objectMapper;
@Test @Test
public void t1_NormalTaskTest() throws Exception { public void t1_BroadcastNormalTaskTest() throws Exception {
String reqData = "{\"ver\":2,\"cryptoType\":0,\"timeStamp\":1587604296988," + String reqData = "{\"ver\":2,\"cryptoType\":0,\"timeStamp\":1587604296988," +
"\"msgContent\":\"{\\\"id\\\":-1," + "\"msgContent\":\"{\\\"id\\\":-1," +
"\\\"type\\\":0, " + "\\\"type\\\":0, " +
@ -80,14 +80,59 @@ public class TaskControllerSmokeTest extends InitTestEnvironment {
Assert.assertNotNull(startTaskRsp.getId()); Assert.assertNotNull(startTaskRsp.getId());
Assert.assertNotNull(startTaskRsp.getTaskId()); Assert.assertNotNull(startTaskRsp.getTaskId());
Assert.assertEquals(Long.valueOf(startTaskRsp.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertEquals(Long.valueOf(startTaskRsp.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertEquals(startTaskRsp.getMessage(), ErrorCode.ERR_OK.getMsg());
} else if (startTaskRsp.getStatus() == 26) { } else if (startTaskRsp.getStatus() == 26) {
Assert.assertEquals(Long.valueOf(startTaskRsp.getStatus()), Long.valueOf(ErrorCode.ERR_TASKRUNNING.getCode())); Assert.assertEquals(Long.valueOf(startTaskRsp.getStatus()), Long.valueOf(ErrorCode.ERR_TASKRUNNING.getCode()));
Assert.assertEquals(startTaskRsp.getMessage(), ErrorCode.ERR_TASKRUNNING.getMsg());
}
}
@Test
public void t2_DesignatedDeviceNormalTaskTest() throws Exception {
String reqData = "{\"ver\":2,\"cryptoType\":0,\"timeStamp\":1587604296988," +
"\"msgContent\":\"{\\\"id\\\":1," +
"\\\"type\\\":0, " +
"\\\"disposeIp\\\":\\\"192.168.4.2\\\", " +
"\\\"disposeTime\\\":120}\"}";
String taskStart = mockMvc.perform(MockMvcRequestBuilders
.post("/task/start")
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", GlobalVar.STRING_HTTP_AUTH_HEAD + getLogToken())
.content(reqData))
.andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(ErrorCode.ERR_OK.getHttpCode()))
.andReturn()
.getResponse()
.getContentAsString();
StartTaskRsp startTaskRsp = objectMapper.readValue(verifyResp(taskStart), StartTaskRsp.class);
Assert.assertNotNull(startTaskRsp);
Assert.assertNotNull(startTaskRsp.getStatus());
Assert.assertNotNull(startTaskRsp.getMessage());
System.out.println(startTaskRsp.getStatus());
if (startTaskRsp.getStatus() == 0) {
Assert.assertNotNull(String.valueOf(startTaskRsp.getExpireTime()));
Assert.assertNotNull(startTaskRsp.getId());
Assert.assertNotNull(startTaskRsp.getTaskId());
Assert.assertEquals(Long.valueOf(startTaskRsp.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertEquals(startTaskRsp.getMessage(), ErrorCode.ERR_OK.getMsg());
} else if (startTaskRsp.getStatus() == 26) {
Assert.assertEquals(Long.valueOf(startTaskRsp.getStatus()), Long.valueOf(ErrorCode.ERR_TASKRUNNING.getCode()));
Assert.assertEquals(startTaskRsp.getMessage(), ErrorCode.ERR_TASKRUNNING.getMsg());
}else if(startTaskRsp.getStatus() == 19){
Assert.assertEquals(Long.valueOf(startTaskRsp.getStatus()), Long.valueOf(ErrorCode.ERR_NOSUCHDEVICE.getCode()));
Assert.assertEquals(startTaskRsp.getMessage(), ErrorCode.ERR_NOSUCHDEVICE.getMsg());
} }
} }
@Test @Test
public void t2_NormalStopTaskTest() throws Exception { public void t3_NormalStopTaskTest() throws Exception {
String reqData = "{\"ver\":2,\"cryptoType\":0,\"timeStamp\":1587604296988," + String reqData = "{\"ver\":2,\"cryptoType\":0,\"timeStamp\":1587604296988," +
"\"msgContent\":\"{\\\"taskId\\\":[\\\"60\\\", \\\"2\\\" ]}\"}"; "\"msgContent\":\"{\\\"taskId\\\":[\\\"60\\\", \\\"2\\\" ]}\"}";
@ -113,15 +158,17 @@ public class TaskControllerSmokeTest extends InitTestEnvironment {
Assert.assertNotNull(task.getId()); Assert.assertNotNull(task.getId());
Assert.assertNotNull(task.getTaskId()); Assert.assertNotNull(task.getTaskId());
Assert.assertEquals(Long.valueOf(task.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertEquals(Long.valueOf(task.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertEquals(task.getMessage(), ErrorCode.ERR_OK.getMsg());
} else if (task.getStatus() == 30) { } else if (task.getStatus() == 30) {
Assert.assertEquals(Long.valueOf(task.getStatus()), Long.valueOf(ErrorCode.ERR_NOSUCHTASK.getCode())); Assert.assertEquals(Long.valueOf(task.getStatus()), Long.valueOf(ErrorCode.ERR_NOSUCHTASK.getCode()));
Assert.assertEquals(task.getMessage(), ErrorCode.ERR_NOSUCHTASK.getMsg());
} }
} }
} }
@Test @Test
public void t3_NormalStopTaskByDisposeIpTest() throws Exception { public void t4_NormalStopTaskByDisposeIpTest() throws Exception {
String reqData = "{\"ver\":2,\"cryptoType\":0,\"timeStamp\":1587604296988,\"msgContent\": \"{\\\"items\\\":" + String reqData = "{\"ver\":2,\"cryptoType\":0,\"timeStamp\":1587604296988,\"msgContent\": \"{\\\"items\\\":" +
"[{\\\"id\\\":\\\"1\\\",\\\"type\\\":0,\\\"disposeIp\\\":\\\"192.168.3.3\\\"}]}\"}"; "[{\\\"id\\\":\\\"1\\\",\\\"type\\\":0,\\\"disposeIp\\\":\\\"192.168.3.3\\\"}]}\"}";
@ -147,14 +194,16 @@ public class TaskControllerSmokeTest extends InitTestEnvironment {
Assert.assertNotNull(task.getId()); Assert.assertNotNull(task.getId());
Assert.assertNotNull(task.getTaskId()); Assert.assertNotNull(task.getTaskId());
Assert.assertEquals(Long.valueOf(task.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertEquals(Long.valueOf(task.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertEquals(task.getMessage(), ErrorCode.ERR_OK.getMsg());
} else if (task.getStatus() == 30) { } else if (task.getStatus() == 30) {
Assert.assertEquals(Long.valueOf(task.getStatus()), Long.valueOf(ErrorCode.ERR_NOSUCHTASK.getCode())); Assert.assertEquals(Long.valueOf(task.getStatus()), Long.valueOf(ErrorCode.ERR_NOSUCHTASK.getCode()));
Assert.assertEquals(task.getMessage(), ErrorCode.ERR_NOSUCHTASK.getMsg());
} }
} }
} }
@Test @Test
public void t4_NormalGetNodeDetailedInfoTest() throws Exception { public void t5_NormalGetNodeDetailedInfoTest() throws Exception {
String reqData = "{\"ver\":2,\"cryptoType\":0,\"timeStamp\":1587604296988," + String reqData = "{\"ver\":2,\"cryptoType\":0,\"timeStamp\":1587604296988," +
"\"msgContent\":\"{\\\"taskId\\\":[\\\"60\\\", \\\"2\\\"]}\"}"; "\"msgContent\":\"{\\\"taskId\\\":[\\\"60\\\", \\\"2\\\"]}\"}";
@ -183,8 +232,47 @@ public class TaskControllerSmokeTest extends InitTestEnvironment {
Assert.assertNotNull(task.getStartTime()); Assert.assertNotNull(task.getStartTime());
Assert.assertNotNull(task.getDisposeTime()); Assert.assertNotNull(task.getDisposeTime());
Assert.assertEquals(Long.valueOf(task.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertEquals(Long.valueOf(task.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertEquals(task.getMessage(), ErrorCode.ERR_OK.getMsg());
} else if (task.getStatus() == 30) { } else if (task.getStatus() == 30) {
Assert.assertEquals(Long.valueOf(task.getStatus()), Long.valueOf(ErrorCode.ERR_NOSUCHTASK.getCode())); Assert.assertEquals(Long.valueOf(task.getStatus()), Long.valueOf(ErrorCode.ERR_NOSUCHTASK.getCode()));
Assert.assertEquals(task.getMessage(), ErrorCode.ERR_NOSUCHTASK.getMsg());
}
}
}
/**
* t6 stop all clean task test.
*/
@Test
public void t6_NormalStopAllCleanTaskTest() throws Exception {
String reqData = "{\"ver\":2,\"cryptoType\":0,\"timeStamp\":1587604296988,\"msgContent\":\"{\\\"type\\\":0}\"}";
String ret = mockMvc.perform(MockMvcRequestBuilders
.post("/task/stop_all")
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", GlobalVar.STRING_HTTP_AUTH_HEAD + getLogToken())
.content(reqData))
.andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(ErrorCode.ERR_OK.getHttpCode()))
.andReturn()
.getResponse()
.getContentAsString();
TaskInfoRsp taskStopByIpRsp = objectMapper.readValue(verifyResp(ret), TaskInfoRsp.class);
List<TaskInfoData> taskInfoList = taskStopByIpRsp.getItems();
for (TaskInfoData task : taskInfoList
) {
Assert.assertNotNull(task.getStatus());
Assert.assertNotNull(task.getMessage());
if (task.getStatus() == 0) {
Assert.assertNotNull(task.getId());
Assert.assertNotNull(task.getTaskId());
Assert.assertEquals(Long.valueOf(task.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertEquals(task.getMessage(), ErrorCode.ERR_OK.getMsg());
} else {
Assert.assertNotEquals(Long.valueOf(task.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertNotEquals(task.getMessage(), ErrorCode.ERR_OK.getMsg());
} }
} }
} }

View File

@ -1,13 +1,11 @@
package com.dispose.test.controller; package com.dispose.test.controller;
import com.dispose.common.DisposeTaskStatus;
import com.dispose.common.FlowDirection;
import com.dispose.common.GlobalVar;
import com.dispose.service.TaskService;
import com.dispose.test.Global.InitTestEnvironment;
import com.dispose.common.ConstValue; import com.dispose.common.ConstValue;
import com.dispose.common.DeviceCapacity; import com.dispose.common.DeviceCapacity;
import com.dispose.common.DisposeTaskStatus;
import com.dispose.common.ErrorCode; import com.dispose.common.ErrorCode;
import com.dispose.common.FlowDirection;
import com.dispose.common.GlobalVar;
import com.dispose.common.IPAddrType; import com.dispose.common.IPAddrType;
import com.dispose.manager.TaskCacheManager; import com.dispose.manager.TaskCacheManager;
import com.dispose.mapper.DisposeDeviceMapper; import com.dispose.mapper.DisposeDeviceMapper;
@ -24,6 +22,8 @@ import com.dispose.pojo.vo.task.StartTaskRsp;
import com.dispose.pojo.vo.task.StopTaskData; import com.dispose.pojo.vo.task.StopTaskData;
import com.dispose.pojo.vo.task.StopTaskReq; import com.dispose.pojo.vo.task.StopTaskReq;
import com.dispose.pojo.vo.task.TaskInfoRsp; import com.dispose.pojo.vo.task.TaskInfoRsp;
import com.dispose.service.TaskService;
import com.dispose.test.Global.InitTestEnvironment;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.junit.Assert; import org.junit.Assert;
@ -162,10 +162,11 @@ public class TaskControllerTest extends InitTestEnvironment {
Assert.assertNotNull(startTaskRsp.getId()); Assert.assertNotNull(startTaskRsp.getId());
Assert.assertNotNull(startTaskRsp.getTaskId()); Assert.assertNotNull(startTaskRsp.getTaskId());
Assert.assertNotNull(String.valueOf(startTaskRsp.getExpireTime())); Assert.assertNotNull(String.valueOf(startTaskRsp.getExpireTime()));
Assert.assertNotEquals(String.valueOf(startTaskRsp.getExpireTime()), -1);
Assert.assertEquals(Long.valueOf(startTaskRsp.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertEquals(Long.valueOf(startTaskRsp.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertEquals(startTaskRsp.getMessage(), ErrorCode.ERR_OK.getMsg());
} else { } else {
Assert.assertNotEquals(Long.valueOf(startTaskRsp.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertNotEquals(Long.valueOf(startTaskRsp.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertNotEquals(startTaskRsp.getMessage(), ErrorCode.ERR_OK.getMsg());
} }
} }
@ -216,8 +217,10 @@ public class TaskControllerTest extends InitTestEnvironment {
Assert.assertNotNull(task.getId()); Assert.assertNotNull(task.getId());
Assert.assertNotNull(task.getTaskId()); Assert.assertNotNull(task.getTaskId());
Assert.assertEquals(Long.valueOf(task.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertEquals(Long.valueOf(task.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertEquals(task.getMessage(), ErrorCode.ERR_OK.getMsg());
} else { } else {
Assert.assertNotEquals(Long.valueOf(task.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertNotEquals(Long.valueOf(task.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertNotEquals(task.getMessage(), ErrorCode.ERR_OK.getMsg());
} }
} }
} }
@ -267,8 +270,10 @@ public class TaskControllerTest extends InitTestEnvironment {
Assert.assertNotNull(task.getId()); Assert.assertNotNull(task.getId());
Assert.assertNotNull(task.getTaskId()); Assert.assertNotNull(task.getTaskId());
Assert.assertEquals(Long.valueOf(task.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertEquals(Long.valueOf(task.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertEquals(task.getMessage(), ErrorCode.ERR_OK.getMsg());
} else { } else {
Assert.assertNotEquals(Long.valueOf(task.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertNotEquals(Long.valueOf(task.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertNotEquals(task.getMessage(), ErrorCode.ERR_OK.getMsg());
} }
} }
} }
@ -329,8 +334,10 @@ public class TaskControllerTest extends InitTestEnvironment {
Assert.assertNotNull(task.getId()); Assert.assertNotNull(task.getId());
Assert.assertNotNull(task.getTaskId()); Assert.assertNotNull(task.getTaskId());
Assert.assertEquals(Long.valueOf(task.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertEquals(Long.valueOf(task.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertEquals(task.getMessage(), ErrorCode.ERR_OK.getMsg());
} else { } else {
Assert.assertNotEquals(Long.valueOf(task.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertNotEquals(Long.valueOf(task.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertNotEquals(task.getMessage(), ErrorCode.ERR_OK.getMsg());
} }
} }
} }
@ -387,8 +394,10 @@ public class TaskControllerTest extends InitTestEnvironment {
Assert.assertNotNull(task.getId()); Assert.assertNotNull(task.getId());
Assert.assertNotNull(task.getTaskId()); Assert.assertNotNull(task.getTaskId());
Assert.assertEquals(Long.valueOf(task.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertEquals(Long.valueOf(task.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertEquals(task.getMessage(), ErrorCode.ERR_OK.getMsg());
} else { } else {
Assert.assertNotEquals(Long.valueOf(task.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertNotEquals(Long.valueOf(task.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertNotEquals(task.getMessage(), ErrorCode.ERR_OK.getMsg());
} }
} }
} }
@ -445,12 +454,13 @@ public class TaskControllerTest extends InitTestEnvironment {
Assert.assertNotNull(task.getMessage()); Assert.assertNotNull(task.getMessage());
if (task.getStatus() == ErrorCode.ERR_OK.getCode()) { if (task.getStatus() == ErrorCode.ERR_OK.getCode()) {
Assert.assertEquals((int) task.getStatus(), ErrorCode.ERR_OK.getCode());
Assert.assertEquals(task.getMessage(), ErrorCode.ERR_OK.getMsg());
Assert.assertNotNull(task.getId()); Assert.assertNotNull(task.getId());
Assert.assertNotNull(task.getTaskId()); Assert.assertNotNull(task.getTaskId());
Assert.assertEquals((int) task.getStatus(), ErrorCode.ERR_OK.getCode());
Assert.assertEquals(task.getMessage(), ErrorCode.ERR_OK.getMsg());
} else { } else {
Assert.assertNotEquals((int) task.getStatus(), ErrorCode.ERR_OK.getCode()); Assert.assertNotEquals((int) task.getStatus(), ErrorCode.ERR_OK.getCode());
Assert.assertNotEquals(task.getMessage(), ErrorCode.ERR_OK.getMsg());
} }
} }
} }
@ -513,12 +523,13 @@ public class TaskControllerTest extends InitTestEnvironment {
Assert.assertNotNull(task.getMessage()); Assert.assertNotNull(task.getMessage());
if (task.getStatus() == ErrorCode.ERR_OK.getCode()) { if (task.getStatus() == ErrorCode.ERR_OK.getCode()) {
Assert.assertEquals((int) task.getStatus(), ErrorCode.ERR_OK.getCode());
Assert.assertEquals(task.getMessage(), ErrorCode.ERR_OK.getMsg());
Assert.assertNotNull(task.getId()); Assert.assertNotNull(task.getId());
Assert.assertNotNull(task.getTaskId()); Assert.assertNotNull(task.getTaskId());
Assert.assertEquals((int) task.getStatus(), ErrorCode.ERR_OK.getCode());
Assert.assertEquals(task.getMessage(), ErrorCode.ERR_OK.getMsg());
} else { } else {
Assert.assertNotEquals((int) task.getStatus(), ErrorCode.ERR_OK.getCode()); Assert.assertNotEquals((int) task.getStatus(), ErrorCode.ERR_OK.getCode());
Assert.assertNotEquals(task.getMessage(), ErrorCode.ERR_OK.getMsg());
} }
} }
} }
@ -575,12 +586,13 @@ public class TaskControllerTest extends InitTestEnvironment {
Assert.assertNotNull(task.getMessage()); Assert.assertNotNull(task.getMessage());
if (task.getStatus() == ErrorCode.ERR_OK.getCode()) { if (task.getStatus() == ErrorCode.ERR_OK.getCode()) {
Assert.assertEquals((int) task.getStatus(), ErrorCode.ERR_OK.getCode());
Assert.assertEquals(task.getMessage(), ErrorCode.ERR_OK.getMsg());
Assert.assertNotNull(task.getId()); Assert.assertNotNull(task.getId());
Assert.assertNotNull(task.getTaskId()); Assert.assertNotNull(task.getTaskId());
Assert.assertEquals((int) task.getStatus(), ErrorCode.ERR_OK.getCode());
Assert.assertEquals(task.getMessage(), ErrorCode.ERR_OK.getMsg());
} else { } else {
Assert.assertNotEquals((int) task.getStatus(), ErrorCode.ERR_OK.getCode()); Assert.assertNotEquals((int) task.getStatus(), ErrorCode.ERR_OK.getCode());
Assert.assertNotEquals(task.getMessage(), ErrorCode.ERR_OK.getMsg());
} }
} }
} }
@ -633,12 +645,13 @@ public class TaskControllerTest extends InitTestEnvironment {
Assert.assertNotNull(task.getMessage()); Assert.assertNotNull(task.getMessage());
if (task.getStatus() == ErrorCode.ERR_OK.getCode()) { if (task.getStatus() == ErrorCode.ERR_OK.getCode()) {
Assert.assertEquals((int) task.getStatus(), ErrorCode.ERR_OK.getCode());
Assert.assertEquals(task.getMessage(), ErrorCode.ERR_OK.getMsg());
Assert.assertNotNull(task.getId()); Assert.assertNotNull(task.getId());
Assert.assertNotNull(task.getTaskId()); Assert.assertNotNull(task.getTaskId());
Assert.assertEquals((int) task.getStatus(), ErrorCode.ERR_OK.getCode());
Assert.assertEquals(task.getMessage(), ErrorCode.ERR_OK.getMsg());
} else { } else {
Assert.assertNotEquals((int) task.getStatus(), ErrorCode.ERR_OK.getCode()); Assert.assertNotEquals((int) task.getStatus(), ErrorCode.ERR_OK.getCode());
Assert.assertNotEquals(task.getMessage(), ErrorCode.ERR_OK.getMsg());
} }
} }
} }
@ -687,12 +700,13 @@ public class TaskControllerTest extends InitTestEnvironment {
Assert.assertNotNull(task.getMessage()); Assert.assertNotNull(task.getMessage());
if (task.getStatus() == ErrorCode.ERR_OK.getCode()) { if (task.getStatus() == ErrorCode.ERR_OK.getCode()) {
Assert.assertEquals((int) task.getStatus(), ErrorCode.ERR_OK.getCode());
Assert.assertEquals(task.getMessage(), ErrorCode.ERR_OK.getMsg());
Assert.assertNotNull(task.getId()); Assert.assertNotNull(task.getId());
Assert.assertNotNull(task.getTaskId()); Assert.assertNotNull(task.getTaskId());
Assert.assertEquals((int) task.getStatus(), ErrorCode.ERR_OK.getCode());
Assert.assertEquals(task.getMessage(), ErrorCode.ERR_OK.getMsg());
} else { } else {
Assert.assertNotEquals((int) task.getStatus(), ErrorCode.ERR_OK.getCode()); Assert.assertNotEquals((int) task.getStatus(), ErrorCode.ERR_OK.getCode());
Assert.assertNotEquals(task.getMessage(), ErrorCode.ERR_OK.getMsg());
} }
} }
} }
@ -739,12 +753,13 @@ public class TaskControllerTest extends InitTestEnvironment {
Assert.assertNotNull(task.getMessage()); Assert.assertNotNull(task.getMessage());
if (task.getStatus() == ErrorCode.ERR_OK.getCode()) { if (task.getStatus() == ErrorCode.ERR_OK.getCode()) {
Assert.assertEquals((int) task.getStatus(), ErrorCode.ERR_OK.getCode());
Assert.assertEquals(task.getMessage(), ErrorCode.ERR_OK.getMsg());
Assert.assertNotNull(task.getId()); Assert.assertNotNull(task.getId());
Assert.assertNotNull(task.getTaskId()); Assert.assertNotNull(task.getTaskId());
Assert.assertEquals((int) task.getStatus(), ErrorCode.ERR_OK.getCode());
Assert.assertEquals(task.getMessage(), ErrorCode.ERR_OK.getMsg());
} else { } else {
Assert.assertNotEquals((int) task.getStatus(), ErrorCode.ERR_OK.getCode()); Assert.assertNotEquals((int) task.getStatus(), ErrorCode.ERR_OK.getCode());
Assert.assertNotEquals(task.getMessage(), ErrorCode.ERR_OK.getMsg());
} }
} }
} }
@ -780,7 +795,6 @@ public class TaskControllerTest extends InitTestEnvironment {
.getResponse() .getResponse()
.getContentAsString(); .getContentAsString();
String regex = "\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z";
String msgContent = verifyRep(getTask, reqTimeStamp); String msgContent = verifyRep(getTask, reqTimeStamp);
System.out.print("msgContent=" + msgContent); System.out.print("msgContent=" + msgContent);
@ -804,13 +818,14 @@ public class TaskControllerTest extends InitTestEnvironment {
Assert.assertNotNull(task.getStartTime()); Assert.assertNotNull(task.getStartTime());
Assert.assertNotNull(task.getStartTime()); Assert.assertNotNull(task.getStartTime());
Assert.assertNotNull(task.getDisposeIp()); Assert.assertNotNull(task.getDisposeIp());
Assert.assertTrue(task.getDisposeIp().matches(regex));
} }
} }
Assert.assertEquals(Long.valueOf(taskNode.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertEquals(Long.valueOf(taskNode.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertEquals(taskNode.getMessage(), ErrorCode.ERR_OK.getMsg());
} else { } else {
Assert.assertNotEquals(Long.valueOf(taskNode.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertNotEquals(Long.valueOf(taskNode.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertNotEquals(taskNode.getMessage(), ErrorCode.ERR_OK.getMsg());
} }
} }
} }
@ -844,7 +859,6 @@ public class TaskControllerTest extends InitTestEnvironment {
.getResponse() .getResponse()
.getContentAsString(); .getContentAsString();
String regex = "\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z";
String msgContent = verifyRep(getTask, reqTimeStamp); String msgContent = verifyRep(getTask, reqTimeStamp);
System.out.print("msgContent=" + msgContent); System.out.print("msgContent=" + msgContent);
@ -868,13 +882,14 @@ public class TaskControllerTest extends InitTestEnvironment {
Assert.assertNotNull(task.getStartTime()); Assert.assertNotNull(task.getStartTime());
Assert.assertNotNull(task.getStartTime()); Assert.assertNotNull(task.getStartTime());
Assert.assertNotNull(task.getDisposeIp()); Assert.assertNotNull(task.getDisposeIp());
Assert.assertTrue(task.getDisposeIp().matches(regex));
} }
} }
Assert.assertEquals(Long.valueOf(taskNode.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertEquals(Long.valueOf(taskNode.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertEquals(taskNode.getMessage(), ErrorCode.ERR_OK.getMsg());
} else { } else {
Assert.assertNotEquals(Long.valueOf(taskNode.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode())); Assert.assertNotEquals(Long.valueOf(taskNode.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertNotEquals(taskNode.getMessage(), ErrorCode.ERR_OK.getMsg());
} }
} }
} }
@ -890,13 +905,14 @@ public class TaskControllerTest extends InitTestEnvironment {
.taskId(new String[]{String.valueOf(getExistsTaskId()), "123"}) .taskId(new String[]{String.valueOf(getExistsTaskId()), "123"})
.build(); .build();
Long reqTimeStamp = System.currentTimeMillis();
ProtocolReqDTO reqInfo = new ProtocolReqDTO(); ProtocolReqDTO reqInfo = new ProtocolReqDTO();
reqInfo.setVer(ConstValue.Protocol.VERSION); reqInfo.setVer(ConstValue.Protocol.VERSION);
reqInfo.setCryptoType(ConstValue.Protocol.CRYPTO_NONE); reqInfo.setCryptoType(ConstValue.Protocol.CRYPTO_NONE);
reqInfo.setTimeStamp(System.currentTimeMillis()); reqInfo.setTimeStamp(reqTimeStamp);
reqInfo.setMsgContent(objectMapper.writeValueAsString(reqData)); reqInfo.setMsgContent(objectMapper.writeValueAsString(reqData));
mockMvc.perform(MockMvcRequestBuilders String getTask = mockMvc.perform(MockMvcRequestBuilders
.post("/task/get") .post("/task/get")
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.header("Authorization", GlobalVar.STRING_HTTP_AUTH_HEAD + getLogToken()) .header("Authorization", GlobalVar.STRING_HTTP_AUTH_HEAD + getLogToken())
@ -906,6 +922,32 @@ public class TaskControllerTest extends InitTestEnvironment {
.andReturn() .andReturn()
.getResponse() .getResponse()
.getContentAsString(); .getContentAsString();
String msgContent = verifyRep(getTask, reqTimeStamp);
System.out.print("msgContent=" + msgContent);
//将json字符串转为TaskInfoRsp类
TaskInfoRsp taskInfoRsp = objectMapper.readValue(msgContent, TaskInfoRsp.class);
List<TaskInfoData> taskInfoList = taskInfoRsp.getItems();
for (TaskInfoData taskInfoData : taskInfoList
) {
Assert.assertNotNull(taskInfoData);
Assert.assertNotNull(taskInfoData.getStatus());
Assert.assertNotNull(taskInfoData.getMessage());
if (taskInfoData.getStatus() == 0) {
Assert.assertNotNull(taskInfoData.getId());
Assert.assertNotNull(taskInfoData.getTaskId());
Assert.assertNotNull(taskInfoData.getStartTime());
Assert.assertNotNull(taskInfoData.getDisposeTime());
Assert.assertEquals(Long.valueOf(taskInfoData.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertEquals(taskInfoData.getMessage(), ErrorCode.ERR_OK.getMsg());
} else if (taskInfoData.getStatus() == 30) {
Assert.assertEquals(Long.valueOf(taskInfoData.getStatus()), Long.valueOf(ErrorCode.ERR_NOSUCHTASK.getCode()));
Assert.assertEquals(taskInfoData.getMessage(), ErrorCode.ERR_NOSUCHTASK.getMsg());
}
}
} }
/** /**
@ -919,13 +961,14 @@ public class TaskControllerTest extends InitTestEnvironment {
.taskId(new String[]{}) .taskId(new String[]{})
.build(); .build();
Long reqTimeStamp = System.currentTimeMillis();
ProtocolReqDTO reqInfo = new ProtocolReqDTO(); ProtocolReqDTO reqInfo = new ProtocolReqDTO();
reqInfo.setVer(ConstValue.Protocol.VERSION); reqInfo.setVer(ConstValue.Protocol.VERSION);
reqInfo.setCryptoType(ConstValue.Protocol.CRYPTO_NONE); reqInfo.setCryptoType(ConstValue.Protocol.CRYPTO_NONE);
reqInfo.setTimeStamp(System.currentTimeMillis()); reqInfo.setTimeStamp(reqTimeStamp);
reqInfo.setMsgContent(objectMapper.writeValueAsString(reqData)); reqInfo.setMsgContent(objectMapper.writeValueAsString(reqData));
mockMvc.perform(MockMvcRequestBuilders String getTask = mockMvc.perform(MockMvcRequestBuilders
.post("/task/get") .post("/task/get")
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.header("Authorization", GlobalVar.STRING_HTTP_AUTH_HEAD + getLogToken()) .header("Authorization", GlobalVar.STRING_HTTP_AUTH_HEAD + getLogToken())
@ -935,7 +978,28 @@ public class TaskControllerTest extends InitTestEnvironment {
.andReturn() .andReturn()
.getResponse() .getResponse()
.getContentAsString(); .getContentAsString();
String msgContent = verifyRep(getTask, reqTimeStamp);
System.out.print("msgContent=" + msgContent);
//将json字符串转为TaskInfoRsp类
TaskInfoRsp taskInfoRsp = objectMapper.readValue(msgContent, TaskInfoRsp.class);
List<TaskInfoData> taskInfoList = taskInfoRsp.getItems();
for (TaskInfoData taskInfoData : taskInfoList
) {
Assert.assertNotNull(taskInfoData);
Assert.assertNotNull(taskInfoData.getId());
Assert.assertNotNull(taskInfoData.getTaskId());
Assert.assertNotNull(taskInfoData.getStartTime());
Assert.assertNotNull(taskInfoData.getDisposeTime());
Assert.assertNotNull(taskInfoData.getStatus());
Assert.assertNotNull(taskInfoData.getMessage());
Assert.assertEquals(Long.valueOf(taskInfoData.getStatus()), Long.valueOf(ErrorCode.ERR_OK.getCode()));
Assert.assertEquals(taskInfoData.getMessage(), ErrorCode.ERR_OK.getMsg());
} }
}
/** /**
* T 8 add task error test. * T 8 add task error test.

View File

@ -1,22 +1,32 @@
package com.dispose.test.debug; package com.dispose.test.debug;
import com.dispose.common.IPAddrType;
import com.dispose.pojo.vo.common.IDArrayReq; import com.dispose.pojo.vo.common.IDArrayReq;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import inet.ipaddr.AddressStringException;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringRunner;
/**
* The type Demo.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
@Slf4j @Slf4j
public class demo { public class demo {
/**
* A 1 idid array req test.
*
* @throws JsonProcessingException the json processing exception
*/
@Test @Test
public void a1_IDIDArrayReqTest() throws JsonProcessingException { public void a1_IDIDArrayReqTest() throws JsonProcessingException {
String json = "{\"id\":[\"1\", \"123\", \"1234\", \"1234\"]}"; String json = "{\"id\":[\"1\", \"123\", \"1234\", \"1234\"]}";
String json2 = "{\"id\":[\"1\", \"123\", \"1234\"]}"; String json2 = "{\"id\":[\"1\", \"123\", \"1234\"]}";
String json3 = "{\"id\":[\"\", \"1\", \"123\", \"1234\"]}"; String json3 = "{\"id\":[\"\", \"1\", \"123\", \"1234\"]}";
String json4 = "{\"id\":[\"1\", \"123\", \"1234\", null]}"; //String json4 = "{\"id\":[\"1\", \"123\", \"1234\", null]}";
IDArrayReq id = new ObjectMapper().readValue(json3, IDArrayReq.class); IDArrayReq id = new ObjectMapper().readValue(json3, IDArrayReq.class);
@ -28,6 +38,20 @@ public class demo {
id = new ObjectMapper().readValue(json, IDArrayReq.class); id = new ObjectMapper().readValue(json, IDArrayReq.class);
Assert.assertEquals(id.getId().length, 3); Assert.assertEquals(id.getId().length, 3);
id = new ObjectMapper().readValue(json4, IDArrayReq.class); //id = new ObjectMapper().readValue(json4, IDArrayReq.class);
}
/**
* A 2 ip range test.
*
* @throws AddressStringException the address string exception
*/
@Test
public void a2_ipRangeTest() throws AddressStringException {
Assert.assertTrue(IPAddrType.ipInRange("192.168.0.1-192.168.0.100", "192.168.0.30"));
Assert.assertTrue(IPAddrType.ipInRange("192.168.0.30", "192.168.0.30"));
Assert.assertTrue(IPAddrType.ipInRange("192.168.0.40-192.168.0.40", "192.168.0.40"));
Assert.assertTrue(IPAddrType.ipInRange("0.0.0.0-255.255.255.255", "192.168.0.30"));
Assert.assertTrue(IPAddrType.ipInRange("", "192.168.0.30"));
} }
} }

View File

@ -1,12 +1,12 @@
package com.dispose.test.dptech; package com.dispose.test.dptech;
import com.dispose.test.Global.InitTestEnvironment;
import com.dispose.common.DeviceCapacity; import com.dispose.common.DeviceCapacity;
import com.dispose.common.DisposeDeviceType; import com.dispose.common.DisposeDeviceType;
import com.dispose.common.ErrorCode; import com.dispose.common.ErrorCode;
import com.dispose.dispose.DeviceRouter; import com.dispose.dispose.DeviceRouter;
import com.dispose.dispose.DisposeEntryManager; import com.dispose.dispose.DisposeEntryManager;
import com.dispose.pojo.po.DisposeDeviceCapacity; import com.dispose.pojo.po.DisposeDeviceCapacity;
import com.dispose.test.Global.InitTestEnvironment;
import com.dptech.dispose.DetectionObjectDataForService; import com.dptech.dispose.DetectionObjectDataForService;
import com.dptech.dispose.ProtectionObjectDataForService; import com.dptech.dispose.ProtectionObjectDataForService;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
@ -49,7 +49,7 @@ public class DPTechInterfaceTestCase extends InitTestEnvironment {
try { try {
DisposeEntryManager dp = DisposeEntryManager dp =
DeviceRouter.deviceRouterFactory(DisposeDeviceType.DPTECH_UMC.getCode(), "10.88.77.15"); DeviceRouter.getDeviceRouterFactory(DisposeDeviceType.DPTECH_UMC.getCode(), "10.88.77.15");
List<DetectionObjectDataForService> detDevs = dp.getAllDetectionObject(); List<DetectionObjectDataForService> detDevs = dp.getAllDetectionObject();
@ -70,7 +70,7 @@ public class DPTechInterfaceTestCase extends InitTestEnvironment {
try { try {
DisposeEntryManager dp = DisposeEntryManager dp =
DeviceRouter.deviceRouterFactory(DisposeDeviceType.DPTECH_UMC.getCode(), "10.88.77.15"); DeviceRouter.getDeviceRouterFactory(DisposeDeviceType.DPTECH_UMC.getCode(), "10.88.77.15");
String proDevs = dp.getProtectDevices(); String proDevs = dp.getProtectDevices();
@ -91,7 +91,7 @@ public class DPTechInterfaceTestCase extends InitTestEnvironment {
try { try {
DisposeEntryManager dp = DisposeEntryManager dp =
DeviceRouter.deviceRouterFactory(DisposeDeviceType.DPTECH_UMC.getCode(), "10.88.77.15"); DeviceRouter.getDeviceRouterFactory(DisposeDeviceType.DPTECH_UMC.getCode(), "10.88.77.15");
List<ProtectionObjectDataForService> proObjs = dp.getAllProtectionObject(); List<ProtectionObjectDataForService> proObjs = dp.getAllProtectionObject();
@ -110,7 +110,7 @@ public class DPTechInterfaceTestCase extends InitTestEnvironment {
@Test @Test
public void t4_getLinkStatus() { public void t4_getLinkStatus() {
DisposeEntryManager dp = DeviceRouter.deviceRouterFactory(DisposeDeviceType.DPTECH_UMC.getCode(), DisposeEntryManager dp = DeviceRouter.getDeviceRouterFactory(DisposeDeviceType.DPTECH_UMC.getCode(),
"10.88.77.15"); "10.88.77.15");
Assert.assertTrue(dp.getDeviceLinkStatus()); Assert.assertTrue(dp.getDeviceLinkStatus());
@ -124,7 +124,7 @@ public class DPTechInterfaceTestCase extends InitTestEnvironment {
@Test @Test
public void t5_getDeviceCapacity() throws JsonProcessingException { public void t5_getDeviceCapacity() throws JsonProcessingException {
DisposeEntryManager dp = DeviceRouter.deviceRouterFactory(DisposeDeviceType.DPTECH_UMC.getCode(), DisposeEntryManager dp = DeviceRouter.getDeviceRouterFactory(DisposeDeviceType.DPTECH_UMC.getCode(),
"10.88.77.15"); "10.88.77.15");
List<DisposeDeviceCapacity> capList = dp.getDeviceCapacity(); List<DisposeDeviceCapacity> capList = dp.getDeviceCapacity();
@ -136,17 +136,17 @@ public class DPTechInterfaceTestCase extends InitTestEnvironment {
@Test @Test
public void t6_runDisposeTest() { public void t6_runDisposeTest() {
DisposeEntryManager dp = DeviceRouter.deviceRouterFactory(DisposeDeviceType.DPTECH_UMC.getCode(), DisposeEntryManager dp = DeviceRouter.getDeviceRouterFactory(DisposeDeviceType.DPTECH_UMC.getCode(),
"10.88.77.15"); "10.88.77.15");
Assert.assertEquals(dp.runDispose("192.168.3.5", DeviceCapacity.CLEANUP), ErrorCode.ERR_OK); Assert.assertEquals(dp.runDispose("192.168.3.5", DeviceCapacity.CLEANUP, -1L).getFirstParam(), ErrorCode.ERR_OK);
} }
@Test @Test
public void t7_stopDisposeTest() { public void t7_stopDisposeTest() {
DisposeEntryManager dp = DeviceRouter.deviceRouterFactory(DisposeDeviceType.DPTECH_UMC.getCode(), DisposeEntryManager dp = DeviceRouter.getDeviceRouterFactory(DisposeDeviceType.DPTECH_UMC.getCode(),
"10.88.77.15"); "10.88.77.15");
Assert.assertEquals(dp.stopDispose("192.168.3.5", DeviceCapacity.CLEANUP), ErrorCode.ERR_OK); Assert.assertEquals(dp.stopDispose("192.168.3.5", DeviceCapacity.CLEANUP, -1L).getFirstParam(), ErrorCode.ERR_OK);
} }
} }

View File

@ -1,11 +1,15 @@
package com.dispose.test.exception; package com.dispose.test.exception;
import com.dispose.test.Global.InitTestEnvironment;
import com.dispose.common.ConstValue; import com.dispose.common.ConstValue;
import com.dispose.common.ErrorCode;
import com.dispose.common.GlobalVar;
import com.dispose.pojo.dto.ProtocolReqDTO; import com.dispose.pojo.dto.ProtocolReqDTO;
import com.dispose.pojo.po.ReturnStatus;
import com.dispose.pojo.vo.auth.LoginReq; import com.dispose.pojo.vo.auth.LoginReq;
import com.dispose.test.Global.InitTestEnvironment;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.FixMethodOrder; import org.junit.FixMethodOrder;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
@ -53,13 +57,6 @@ public class ExceptionTest extends InitTestEnvironment {
@Resource @Resource
private ObjectMapper objectMapper; private ObjectMapper objectMapper;
/**
* User login.
*/
@Override
public void userLogin() {
}
/** /**
* T 1 input exception. * T 1 input exception.
* *
@ -78,15 +75,22 @@ public class ExceptionTest extends InitTestEnvironment {
reqInfo.setTimeStamp(System.currentTimeMillis()); reqInfo.setTimeStamp(System.currentTimeMillis());
reqInfo.setMsgContent(objectMapper.writeValueAsString(logReq)); reqInfo.setMsgContent(objectMapper.writeValueAsString(logReq));
mockMvc.perform(MockMvcRequestBuilders String ret = mockMvc.perform(MockMvcRequestBuilders
.post("/auth/login") .post("/auth/login")
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(reqInfo))) .content(objectMapper.writeValueAsString(reqInfo)))
.andDo(print()).andExpect(status().isOk()) .andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(521)) .andExpect(jsonPath("$.code").value(ErrorCode.ERR_PARAMEXCEPTION.getHttpCode()))
.andReturn() .andReturn()
.getResponse() .getResponse()
.getContentAsString(); .getContentAsString();
ReturnStatus rspInfo = objectMapper.readValue(verifyResp(ret), ReturnStatus.class);
Assert.assertNotNull(rspInfo.getMessage());
Assert.assertNotNull(rspInfo.getStatus());
Assert.assertEquals(Long.valueOf(rspInfo.getStatus()), Long.valueOf(ErrorCode.ERR_PARAMEXCEPTION.getCode()));
Assert.assertEquals(rspInfo.getMessage(), ErrorCode.ERR_PARAMEXCEPTION.getMsg());
} }
/** /**
@ -94,24 +98,183 @@ public class ExceptionTest extends InitTestEnvironment {
* *
* @throws Exception the exception * @throws Exception the exception
*/ */
@Test(expected = Exception.class) @Test(expected = Throwable.class)
public void t2_globalException() throws Exception { public void t2_globalException() throws Exception {
expectedEx.expect(Exception.class); expectedEx.expect(Throwable.class);
expectedEx.expectMessage("Expected exception: java.lang.Throwable");
ProtocolReqDTO reqInfo = new ProtocolReqDTO(); ProtocolReqDTO reqInfo = new ProtocolReqDTO();
reqInfo.setVer(ConstValue.Protocol.VERSION); reqInfo.setVer(ConstValue.Protocol.VERSION);
reqInfo.setCryptoType(ConstValue.Protocol.CRYPTO_NONE); reqInfo.setCryptoType(ConstValue.Protocol.CRYPTO_NONE);
reqInfo.setTimeStamp(System.currentTimeMillis()); reqInfo.setTimeStamp(System.currentTimeMillis());
reqInfo.setMsgContent("{}"); reqInfo.setMsgContent(null);
mockMvc.perform(MockMvcRequestBuilders String ret = mockMvc.perform(MockMvcRequestBuilders
.post("/information/protected_ip") .post("/information/protected_ip")
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.content("{}")) .header("Authorization", GlobalVar.STRING_HTTP_AUTH_HEAD + getLogToken())
.content(objectMapper.writeValueAsString(reqInfo)))
.andDo(print()).andExpect(status().isOk()) .andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(521)) .andExpect(jsonPath("$.code").value(ErrorCode.ERR_PARAMEXCEPTION.getHttpCode()))
.andReturn() .andReturn()
.getResponse() .getResponse()
.getContentAsString(); .getContentAsString();
ReturnStatus rspInfo = objectMapper.readValue(verifyResp(ret), ReturnStatus.class);
Assert.assertNotNull(rspInfo.getMessage());
Assert.assertNotNull(rspInfo.getStatus());
Assert.assertEquals(Long.valueOf(rspInfo.getStatus()), Long.valueOf(ErrorCode.ERR_PARAMEXCEPTION.getCode()));
Assert.assertEquals(rspInfo.getMessage(), ErrorCode.ERR_PARAMEXCEPTION.getMsg());
}
/**
* T 3 global exception.
*
* @throws Exception the exception
*/
@Test(expected = Throwable.class)
public void t3_globalException() throws Exception {
expectedEx.expect(Throwable.class);
expectedEx.expectMessage("Expected exception: java.lang.Throwable");
String reqData = "{\"id\":null}";
ProtocolReqDTO reqInfo = new ProtocolReqDTO();
reqInfo.setVer(ConstValue.Protocol.VERSION);
reqInfo.setCryptoType(ConstValue.Protocol.CRYPTO_NONE);
reqInfo.setTimeStamp(System.currentTimeMillis());
reqInfo.setMsgContent(reqData);
String ret = mockMvc.perform(MockMvcRequestBuilders
.post("/information/version")
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", GlobalVar.STRING_HTTP_AUTH_HEAD + getLogToken())
.content(objectMapper.writeValueAsString(reqInfo)))
.andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(ErrorCode.ERR_PARAMEXCEPTION.getHttpCode()))
.andReturn()
.getResponse()
.getContentAsString();
ReturnStatus rspInfo = objectMapper.readValue(verifyResp(ret), ReturnStatus.class);
Assert.assertNotNull(rspInfo.getMessage());
Assert.assertNotNull(rspInfo.getStatus());
Assert.assertEquals(Long.valueOf(rspInfo.getStatus()), Long.valueOf(ErrorCode.ERR_PARAMEXCEPTION.getCode()));
Assert.assertEquals(rspInfo.getMessage(), ErrorCode.ERR_PARAMEXCEPTION.getMsg());
}
/**
* T 4 global exception.
*
* @throws Exception the exception
*/
@Test(expected = Throwable.class)
public void t4_globalException() throws Exception {
expectedEx.expect(Throwable.class);
expectedEx.expectMessage("Expected exception: java.lang.Throwable");
String reqData = "{\"id\":1}";
ProtocolReqDTO reqInfo = new ProtocolReqDTO();
reqInfo.setVer(ConstValue.Protocol.VERSION);
reqInfo.setCryptoType(ConstValue.Protocol.CRYPTO_NONE);
reqInfo.setTimeStamp(System.currentTimeMillis());
reqInfo.setMsgContent(reqData);
String ret = mockMvc.perform(MockMvcRequestBuilders
.post("/information/version")
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", GlobalVar.STRING_HTTP_AUTH_HEAD + getLogToken())
.content(objectMapper.writeValueAsString(reqInfo)))
.andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(ErrorCode.ERR_PARAMEXCEPTION.getHttpCode()))
.andReturn()
.getResponse()
.getContentAsString();
ReturnStatus rspInfo = objectMapper.readValue(verifyResp(ret), ReturnStatus.class);
Assert.assertNotNull(rspInfo.getMessage());
Assert.assertNotNull(rspInfo.getStatus());
Assert.assertEquals(Long.valueOf(rspInfo.getStatus()), Long.valueOf(ErrorCode.ERR_PARAMEXCEPTION.getCode()));
Assert.assertEquals(rspInfo.getMessage(), ErrorCode.ERR_PARAMEXCEPTION.getMsg());
}
/**
* T 5 input exception.
*
* @throws Exception the exception
*/
@Test(expected = Throwable.class)
public void t5_inputException() throws Exception {
expectedEx.expect(Throwable.class);
expectedEx.expectMessage("Expected exception: java.lang.Throwable");
LoginReq logReq = null;
ProtocolReqDTO reqInfo = new ProtocolReqDTO();
reqInfo.setVer(ConstValue.Protocol.VERSION);
reqInfo.setCryptoType(ConstValue.Protocol.CRYPTO_NONE);
reqInfo.setTimeStamp(System.currentTimeMillis());
reqInfo.setMsgContent(objectMapper.writeValueAsString(logReq));
String ret = mockMvc.perform(MockMvcRequestBuilders
.post("/auth/logout")
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", GlobalVar.STRING_HTTP_AUTH_HEAD + getLogToken())
.content(objectMapper.writeValueAsString(reqInfo)))
.andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(ErrorCode.ERR_PARAMEXCEPTION.getHttpCode()))
.andReturn()
.getResponse()
.getContentAsString();
ReturnStatus rspInfo = objectMapper.readValue(verifyResp(ret), ReturnStatus.class);
Assert.assertNotNull(rspInfo.getMessage());
Assert.assertNotNull(rspInfo.getStatus());
Assert.assertEquals(Long.valueOf(rspInfo.getStatus()), Long.valueOf(ErrorCode.ERR_PARAMEXCEPTION.getCode()));
Assert.assertEquals(rspInfo.getMessage(), ErrorCode.ERR_PARAMEXCEPTION.getMsg());
}
/**
* T 6 input exception.
*
* @throws Exception the exception
*/
@Test(expected = Throwable.class)
public void t6_inputException() throws Exception {
expectedEx.expect(Throwable.class);
expectedEx.expectMessage("Expected exception: java.lang.Throwable");
LoginReq logReq = null;
ProtocolReqDTO reqInfo = new ProtocolReqDTO();
reqInfo.setVer(ConstValue.Protocol.VERSION);
reqInfo.setCryptoType(ConstValue.Protocol.CRYPTO_NONE);
reqInfo.setTimeStamp(System.currentTimeMillis());
reqInfo.setMsgContent(objectMapper.writeValueAsString(logReq));
String ret = mockMvc.perform(MockMvcRequestBuilders
.post("/task/start")
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", GlobalVar.STRING_HTTP_AUTH_HEAD + getLogToken())
.content(objectMapper.writeValueAsString(reqInfo)))
.andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(ErrorCode.ERR_PARAMEXCEPTION.getHttpCode()))
.andReturn()
.getResponse()
.getContentAsString();
ReturnStatus rspInfo = objectMapper.readValue(verifyResp(ret), ReturnStatus.class);
Assert.assertNotNull(rspInfo.getMessage());
Assert.assertNotNull(rspInfo.getStatus());
Assert.assertEquals(Long.valueOf(rspInfo.getStatus()), Long.valueOf(ErrorCode.ERR_PARAMEXCEPTION.getCode()));
Assert.assertEquals(rspInfo.getMessage(), ErrorCode.ERR_PARAMEXCEPTION.getMsg());
} }
} }

View File

@ -0,0 +1,60 @@
package com.dispose.test.haohan;
/**
* The enum Error code.
*
* @author <chenlinghy@cmhi.chinamoblie.com>
*/
public enum HaoHanErrorCode {
/**
* Err ok error code.
*/
ERR_OK("成功"),
/**
* Err whitelist error code.
*/
ERR_WHITELIST("ip已存在清洗ip白名单中不允许添加"),
/**
* Err ip format error code.
*/
ERR_DISPOSEIPFORMAT("IP地址格式有误"),
/**
* Err ip format error code.
*/
ERR_DURATIONFORMAT("清洗时长参数格式不正确,请检查!"),
/**
* Err orderFrom format error code.
*/
ERR_ORDERFROMFORMA("厂家信息参数格式不正确,请检查!"),
/**
* Err cleanTaskId format error code.
*/
ERR_CLEANTASKIDFORMA("清洗任务id参数格式不正确请检查"),
/**
* Err no running task error code.
*/
ERR_NORUNNINGTASK("没有正在清洗的ip"),
/**
* Err task does not existed or task is running error code.
*/
ERR_TASKNOEND("请检查清洗任务是否存在或清洗状态是否为结束!"),
/**
* Err task does not existed error code.
*/
ERR_NOTASK("该清洗任务不存在!"),
;
private final String errMsg;
HaoHanErrorCode(String msg) {
this.errMsg = msg;
}
/**
* Gets msg.
*
* @return the msg
*/
public String getMsg() {
return errMsg;
}
}

View File

@ -0,0 +1,290 @@
package com.dispose.test.haohan;
import com.dispose.common.Http;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
@RunWith(SpringRunner.class)
@Slf4j
@SpringBootTest
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class HaoHanInterfaceTestCase {
@Resource
private ObjectMapper objectMapper;
@Test
public void a1_sendTowWhitelistTest() throws JsonProcessingException {
String jsonRequest = "{\"ip\":\"192.168.1.1\",\"orderFrom\":\"hangyan\"}";
String svrReturn = Http.postJson("http://10.88.77.88:18080/DDoSClean/clean/sendTow",
null,
jsonRequest);
log.info("Server Return: [{}]", svrReturn);
sendTowResult result = objectMapper.readValue(svrReturn, sendTowResult.class);
Assert.assertNotNull(result);
Assert.assertEquals(result.getMsg(), HaoHanErrorCode.ERR_WHITELIST.getMsg());
Assert.assertEquals(result.getState(), Integer.valueOf(1));
}
@Test
public void a2_sendTowWhitelistContainsDurationTest() throws JsonProcessingException {
String jsonRequest = "{\"ip\":\"192.168.1.1\",\"duration\":20, \"orderFrom\":\"hangyan\"}";
String svrReturn = Http.postJson("http://10.88.77.88:18080/DDoSClean/clean/sendTow",
null,
jsonRequest);
log.info("Server Return: [{}]", svrReturn);
sendTowResult result = objectMapper.readValue(svrReturn, sendTowResult.class);
Assert.assertNotNull(result);
Assert.assertEquals(result.getMsg(), HaoHanErrorCode.ERR_WHITELIST.getMsg());
Assert.assertEquals(result.getState(), Integer.valueOf(1));
}
@Test
public void a3_normalSendTowTest() throws JsonProcessingException {
String jsonRequest = "{\"ip\":\"192.168.1.2\",\"orderFrom\":\"hangyan\"}";
String svrReturn = Http.postJson("http://10.88.77.88:18080/DDoSClean/clean/sendTow",
null,
jsonRequest);
log.info("Server Return: [{}]", svrReturn);
sendTowResult result = objectMapper.readValue(svrReturn, sendTowResult.class);
Assert.assertNotNull(result);
if (result.getState() == 0) {
Assert.assertEquals(result.getMsg(), HaoHanErrorCode.ERR_OK.getMsg());
Assert.assertNotNull(result.getCleanTaskId());
} else {
Assert.assertNotEquals(result.getMsg(), HaoHanErrorCode.ERR_OK.getMsg());
}
}
@Test
public void a4_normalSendTowContainsDurationTest() throws JsonProcessingException {
String jsonRequest = "{\"ip\":\"192.168.1.20\",\"duration\":20,\"orderFrom\":\"hangyan\"}";
String svrReturn = Http.postJson("http://10.88.77.88:18080/DDoSClean/clean/sendTow",
null,
jsonRequest);
log.info("Server Return: [{}]", svrReturn);
sendTowResult result = objectMapper.readValue(svrReturn, sendTowResult.class);
Assert.assertNotNull(result);
if (result.getState() == 0) {
Assert.assertEquals(result.getMsg(), HaoHanErrorCode.ERR_OK.getMsg());
Assert.assertNotNull(result.getCleanTaskId());
} else {
Assert.assertNotEquals(result.getMsg(), HaoHanErrorCode.ERR_OK.getMsg());
}
}
@Test
public void a5_sendTowIpErrorTest() throws JsonProcessingException {
String jsonRequest = "{\"ip\":\"192.168.120\",\"duration\":20,\"orderFrom\":\"hangyan\"}";
String svrReturn = Http.postJson("http://10.88.77.88:18080/DDoSClean/clean/sendTow",
null,
jsonRequest);
log.info("Server Return: [{}]", svrReturn);
sendTowResult result = objectMapper.readValue(svrReturn, sendTowResult.class);
Assert.assertNotNull(result);
Assert.assertEquals(result.getMsg(), HaoHanErrorCode.ERR_DISPOSEIPFORMAT.getMsg());
Assert.assertEquals(result.getState(), Integer.valueOf(1));
}
@Test
public void a6_sendTowDurationErrorTest() throws JsonProcessingException {
String jsonRequest = "{\"ip\":\"192.168.1.20\",\"duration\":\"20\",\"orderFrom\":\"hangyan\"}";
String svrReturn = Http.postJson("http://10.88.77.88:18080/DDoSClean/clean/sendTow",
null,
jsonRequest);
log.info("Server Return: [{}]", svrReturn);
sendTowResult result = objectMapper.readValue(svrReturn, sendTowResult.class);
Assert.assertNotNull(result);
Assert.assertEquals(result.getMsg(), HaoHanErrorCode.ERR_DURATIONFORMAT.getMsg());
Assert.assertEquals(result.getState(), Integer.valueOf(1));
}
@Test
public void a7_sendTowOrderFromErrorTest() throws JsonProcessingException {
String jsonRequest = "{\"ip\":\"192.168.1.20\",\"duration\":20,\"orderFrom\":123}";
String svrReturn = Http.postJson("http://10.88.77.88:18080/DDoSClean/clean/sendTow",
null,
jsonRequest);
log.info("Server Return: [{}]", svrReturn);
sendTowResult result = objectMapper.readValue(svrReturn, sendTowResult.class);
Assert.assertNotNull(result);
Assert.assertEquals(result.getMsg(), HaoHanErrorCode.ERR_ORDERFROMFORMA.getMsg());
Assert.assertEquals(result.getState(), Integer.valueOf(1));
}
@Test
public void b1_delTowTest() throws JsonProcessingException {
String jsonRequest = "{\"cleanTaskId\":105,\"orderFrom\":\"hangyan\"}";
String svrReturn = Http.postJson("http://10.88.77.88:18080/DDoSClean/clean/delTow",
null,
jsonRequest);
log.info("Server Return: [{}]", svrReturn);
sendTowResult result = objectMapper.readValue(svrReturn, sendTowResult.class);
Assert.assertNotNull(result);
if (result.getState() == 0) {
Assert.assertEquals(result.getMsg(), HaoHanErrorCode.ERR_OK.getMsg());
} else {
Assert.assertNotEquals(result.getMsg(), HaoHanErrorCode.ERR_OK.getMsg());
}
}
@Test
public void b2_delTowCleanTaskIdErrorTest() throws JsonProcessingException {
String jsonRequest = "{\"cleanTaskId\":\"105\",\"orderFrom\":\"hangyan\"}";
String svrReturn = Http.postJson("http://10.88.77.88:18080/DDoSClean/clean/delTow",
null,
jsonRequest);
log.info("Server Return: [{}]", svrReturn);
sendTowResult result = objectMapper.readValue(svrReturn, sendTowResult.class);
Assert.assertNotNull(result);
Assert.assertEquals(result.getMsg(), HaoHanErrorCode.ERR_CLEANTASKIDFORMA.getMsg());
Assert.assertEquals(result.getState(), Integer.valueOf(1));
}
@Test
public void b3_delTowOrderFromErrorTest() throws JsonProcessingException {
String jsonRequest = "{\"cleanTaskId\":105,\"orderFrom\":123}";
String svrReturn = Http.postJson("http://10.88.77.88:18080/DDoSClean/clean/delTow",
null,
jsonRequest);
log.info("Server Return: [{}]", svrReturn);
sendTowResult result = objectMapper.readValue(svrReturn, sendTowResult.class);
Assert.assertNotNull(result);
Assert.assertEquals(result.getMsg(), HaoHanErrorCode.ERR_ORDERFROMFORMA.getMsg());
Assert.assertEquals(result.getState(), Integer.valueOf(1));
}
@Test
public void c1_allIpFlowTest() throws JsonProcessingException {
String jsonRequest = "{\"orderFrom\":\"hangyan\"}";
String svrReturn = Http.postJson("http://10.88.77.88:18080/DDoSClean/clean/allIpFlow",
null,
jsonRequest);
log.info("Server Return: [{}]", svrReturn);
allIpFlowResult result = objectMapper.readValue(svrReturn, allIpFlowResult.class);
Assert.assertNotNull(result);
if (result.getState() == 0) {
Assert.assertEquals(result.getMsg(), HaoHanErrorCode.ERR_OK.getMsg());
for (allIpFlowData data : result.getData()
) {
Assert.assertNotNull(data.getIp());
}
} else {
Assert.assertEquals(result.getMsg(), HaoHanErrorCode.ERR_NORUNNINGTASK.getMsg());
}
}
@Test
public void c2_allIpFlowTest() throws JsonProcessingException {
String jsonRequest = "{\"orderFrom\":123}";
String svrReturn = Http.postJson("http://10.88.77.88:18080/DDoSClean/clean/allIpFlow",
null,
jsonRequest);
log.info("Server Return: [{}]", svrReturn);
allIpFlowResult result = objectMapper.readValue(svrReturn, allIpFlowResult.class);
Assert.assertNotNull(result);
Assert.assertEquals(result.getMsg(), HaoHanErrorCode.ERR_ORDERFROMFORMA.getMsg());
Assert.assertEquals(result.getState(), Integer.valueOf(1));
}
@Test
public void d1_cleanTaskFlowTest() throws JsonProcessingException {
String jsonRequest = "{\"cleanTaskId\":119}";
String svrReturn = Http.postJson("http://10.88.77.88:18080/DDoSClean/clean/cleanTaskFlow",
null,
jsonRequest);
log.info("Server Return: [{}]", svrReturn);
allIpFlowResult result = objectMapper.readValue(svrReturn, allIpFlowResult.class);
Assert.assertNotNull(result);
if (result.getState() == 0) {
Assert.assertEquals(result.getMsg(), HaoHanErrorCode.ERR_OK.getMsg());
for (allIpFlowData data : result.getData()
) {
Assert.assertNotNull(data.getIp());
}
} else {
Assert.assertEquals(result.getMsg(), HaoHanErrorCode.ERR_TASKNOEND.getMsg());
}
}
@Test
public void d2_cleanTaskFlowTest() throws JsonProcessingException {
String jsonRequest = "{\"cleanTaskId\":\"abc\"}";
String svrReturn = Http.postJson("http://10.88.77.88:18080/DDoSClean/clean/cleanTaskFlow",
null,
jsonRequest);
log.info("Server Return: [{}]", svrReturn);
allIpFlowResult result = objectMapper.readValue(svrReturn, allIpFlowResult.class);
Assert.assertNotNull(result);
Assert.assertEquals(result.getMsg(), HaoHanErrorCode.ERR_CLEANTASKIDFORMA.getMsg());
}
@Test
public void e1_getCleanTaskStateTest() throws JsonProcessingException {
String jsonRequest = "{\"cleanTaskId\":119}";
String svrReturn = Http.postJson("http://10.88.77.88:18080/DDoSClean/clean/getCleanTaskState",
null,
jsonRequest);
log.info("Server Return: [{}]", svrReturn);
sendTowResult result = objectMapper.readValue(svrReturn, sendTowResult.class);
Assert.assertNotNull(result);
if (result.getState() == 0) {
Assert.assertEquals(result.getMsg(), HaoHanErrorCode.ERR_OK.getMsg());
} else {
Assert.assertEquals(result.getMsg(), HaoHanErrorCode.ERR_NOTASK.getMsg());
}
}
@Test
public void e2_getCleanTaskStateTest() throws JsonProcessingException {
String jsonRequest = "{\"cleanTaskId\":\"adb\"}";
String svrReturn = Http.postJson("http://10.88.77.88:18080/DDoSClean/clean/getCleanTaskState",
null,
jsonRequest);
log.info("Server Return: [{}]", svrReturn);
sendTowResult result = objectMapper.readValue(svrReturn, sendTowResult.class);
Assert.assertNotNull(result);
Assert.assertEquals(result.getMsg(), HaoHanErrorCode.ERR_CLEANTASKIDFORMA.getMsg());
}
}

View File

@ -0,0 +1,14 @@
package com.dispose.test.haohan;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class allIpFlowData {
String ip; //ip地址
Double inFlow; //输入流量
Integer inPackets; //输入包数
Double outFlow; //输出流量
Integer outPackets; //输出包数
}

View File

@ -0,0 +1,15 @@
package com.dispose.test.haohan;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
@Getter
@Setter
public class allIpFlowResult {
private Integer state;
private String msg;
private List<allIpFlowData> data;
}

View File

@ -0,0 +1,13 @@
package com.dispose.test.haohan;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class sendTowResult {
private Integer state;
private String msg;
private Integer cleanTaskId;
private Integer cleanTaskState;
}

View File

@ -0,0 +1,37 @@
package com.dispose.test.manager;
import com.dispose.common.ErrorCode;
import com.dispose.mapper.TaskInfoMapper;
import com.dispose.test.Global.InitTestEnvironment;
import lombok.extern.slf4j.Slf4j;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
@RunWith(SpringRunner.class)
@Slf4j
@SpringBootTest
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@Transactional
@Rollback
public class TaskInfoMapperTest extends InitTestEnvironment {
@Resource
private TaskInfoMapper taskInfoMapper;
@Override
public void userLogin() {
}
@Test
public void a1_addNewTaskInfoTest() {
taskInfoMapper.addNewTaskInfo(152L, 1L, null, (long) ErrorCode.ERR_OK.getCode());
taskInfoMapper.addNewTaskInfo(152L, 2L, 12L, (long) ErrorCode.ERR_OK.getCode());
}
}

View File

@ -1,10 +1,10 @@
package com.dispose.test.manager; package com.dispose.test.manager;
import com.dispose.test.Global.InitTestEnvironment;
import com.dispose.common.ErrorCode; import com.dispose.common.ErrorCode;
import com.dispose.manager.UserAccountCacheManager; import com.dispose.manager.UserAccountCacheManager;
import com.dispose.pojo.po.MulReturnType; import com.dispose.pojo.po.MulReturnType;
import com.dispose.service.UserAccountService; import com.dispose.service.UserAccountService;
import com.dispose.test.Global.InitTestEnvironment;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.junit.Assert; import org.junit.Assert;
@ -98,6 +98,8 @@ public class UserAccountManagerTest extends InitTestEnvironment {
ErrorCode.ERR_LOGOUT); ErrorCode.ERR_LOGOUT);
Assert.assertEquals(userAccountCacheManager.verifyUserLogin(getUSER_NAME(), userToken + "13245"), Assert.assertEquals(userAccountCacheManager.verifyUserLogin(getUSER_NAME(), userToken + "13245"),
ErrorCode.ERR_TOKENNOTFOUND); ErrorCode.ERR_TOKENNOTFOUND);
Assert.assertEquals(userAccountCacheManager.verifyUserLogin(getUSER_NAME() + "3213", userToken + "13245"),
ErrorCode.ERR_LOGOUT);
} }
/** /**

View File

@ -1,10 +1,10 @@
package com.dispose.test.mapper; package com.dispose.test.mapper;
import com.dispose.test.Global.InitTestEnvironment;
import com.dispose.common.DisposeDeviceType; import com.dispose.common.DisposeDeviceType;
import com.dispose.mapper.DisposeDeviceMapper; import com.dispose.mapper.DisposeDeviceMapper;
import com.dispose.pojo.entity.DisposeDevice; import com.dispose.pojo.entity.DisposeDevice;
import com.dispose.pojo.po.DisposeDeviceCapacity; import com.dispose.pojo.po.DisposeDeviceCapacity;
import com.dispose.test.Global.InitTestEnvironment;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@ -135,22 +135,65 @@ public class DisposeDeviceMapperTest extends InitTestEnvironment {
}); });
} }
// @Test
// public void t0_delDisposeDeviceByIp() throws JsonProcessingException {
// String ipAddr = "10.88.77.15";
// disposeDeviceMapper.delDisposeDeviceByIp(ipAddr);
//
// List<DisposeDevice> dp = disposeDeviceMapper.selectAll();
// log.info(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(dp));
// dp.forEach(v -> {
// if (v.getIpAddr().equals(ipAddr)) {
// Assert.fail();
// }
// });
// }
/** /**
* T 0 del dispose device by ip. * T 6 get dispose device by ip is not existed.
* *
* @throws JsonProcessingException the json processing exception * @throws JsonProcessingException the json processing exception
*/ */
@Test @Test
public void t0_delDisposeDeviceByIp() throws JsonProcessingException { public void t6_getDeviceNotExistsByIp() throws JsonProcessingException {
String ipAddr = "10.88.77.15"; String ipAddr = "10.88.77.16";
disposeDeviceMapper.delDisposeDeviceByIp(ipAddr); DisposeDevice dev = disposeDeviceMapper.getDeviceByIp(ipAddr);
log.info(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(dev));
Assert.assertNull(dev);
}
List<DisposeDevice> dp = disposeDeviceMapper.selectAll(); /**
log.info(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(dp)); * T 7 get device exists by id is not existed.
dp.forEach(v -> { *
if (v.getIpAddr().equals(ipAddr)) { * @throws JsonProcessingException the json processing exception
Assert.fail(); */
@Test
public void t7_getDeviceNotExistsById() throws JsonProcessingException {
Long devId = -1L;
DisposeDevice dev = disposeDeviceMapper.getDeviceById(devId);
log.info(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(dev));
Assert.assertNull(dev);
} }
});
/**
* T 8 is device exists by ip is not existed.
*/
@Test
public void t8_isDeviceNotExistsByIp() {
String ipAddr = "10.88.77.16";
Assert.assertEquals(disposeDeviceMapper.isDeviceExistsByIp(ipAddr), 0);
}
/**
* T 9 is device exists by id is not existed.
*/
@Test
public void t9_isDeviceNotExistsById() {
Long devId = -1L;
Assert.assertEquals(disposeDeviceMapper.isDeviceExistsById(devId), 0);
} }
} }

View File

@ -1,6 +1,5 @@
package com.dispose.test.mapper; package com.dispose.test.mapper;
import com.dispose.test.Global.InitTestEnvironment;
import com.dispose.common.DeviceCapacity; import com.dispose.common.DeviceCapacity;
import com.dispose.common.DisposeTaskStatus; import com.dispose.common.DisposeTaskStatus;
import com.dispose.common.FlowDirection; import com.dispose.common.FlowDirection;
@ -8,6 +7,7 @@ import com.dispose.mapper.DisposeDeviceMapper;
import com.dispose.mapper.DisposeTaskMapper; import com.dispose.mapper.DisposeTaskMapper;
import com.dispose.mapper.UserAccountMapper; import com.dispose.mapper.UserAccountMapper;
import com.dispose.pojo.vo.common.TaskInfoDetail; import com.dispose.pojo.vo.common.TaskInfoDetail;
import com.dispose.test.Global.InitTestEnvironment;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@ -97,19 +97,16 @@ public class DisposeTaskMapperTest extends InitTestEnvironment {
disposeTaskMapper.addNewTask(taskData); disposeTaskMapper.addNewTask(taskData);
Assert.assertNotEquals(java.util.Optional.ofNullable(taskData.getId()), -1L); Assert.assertNotEquals(java.util.Optional.ofNullable(taskData.getId()), -1L);
Assert.assertNotNull(disposeTaskMapper.getTaskInfoById(taskData.getId())); Assert.assertNotNull(disposeTaskMapper.getTaskById(taskData.getId()));
} }
/** // @Test
* Remove task test. // public void t99_removeTaskTest() {
*/ // disposeTaskMapper.selectAll().forEach(v -> {
@Test // disposeTaskMapper.removeTaskById(v.getId());
public void t99_removeTaskTest() { // Assert.assertNull(disposeTaskMapper.getTaskById(v.getId()));
disposeTaskMapper.selectAll().forEach(v -> { // });
disposeTaskMapper.removeTaskById(v.getId()); // }
Assert.assertNull(disposeTaskMapper.getTaskInfoById(v.getId()));
});
}
/** /**
* T 2 change task status test. * T 2 change task status test.
@ -135,7 +132,7 @@ public class DisposeTaskMapperTest extends InitTestEnvironment {
@Test @Test
public void t3_getTaskInfoByIdTest() { public void t3_getTaskInfoByIdTest() {
disposeTaskMapper.selectAll().forEach(v -> { disposeTaskMapper.selectAll().forEach(v -> {
TaskInfoDetail taskInfo = disposeTaskMapper.getTaskInfoById(v.getId()); TaskInfoDetail taskInfo = disposeTaskMapper.getTaskById(v.getId());
Assert.assertNotNull(taskInfo); Assert.assertNotNull(taskInfo);
Assert.assertEquals(taskInfo.getId(), v.getId()); Assert.assertEquals(taskInfo.getId(), v.getId());
try { try {
@ -223,28 +220,10 @@ public class DisposeTaskMapperTest extends InitTestEnvironment {
} }
/** /**
* T 8 get all task by ip test. * T 8 get all task by status test.
*/ */
@Test @Test
public void t8_getAllTaskByIpTest() { public void t8_getAllTaskByStatusTest() {
disposeTaskMapper.selectAll().forEach(v -> disposeTaskMapper
.getAllTaskByDisposeIp(v.getDisposeIp())
.forEach(k -> {
Assert.assertEquals(k.getDisposeIp(), v.getDisposeIp());
try {
log.info(objMapper.writerWithDefaultPrettyPrinter().writeValueAsString(k));
} catch (JsonProcessingException e) {
e.printStackTrace();
Assert.fail();
}
}));
}
/**
* T 9 get all task by status test.
*/
@Test
public void t9_getAllTaskByStatusTest() {
disposeTaskMapper.selectAll().forEach(v -> disposeTaskMapper disposeTaskMapper.selectAll().forEach(v -> disposeTaskMapper
.getAllTaskByStatus(v.getCurrentStatus()) .getAllTaskByStatus(v.getCurrentStatus())
.forEach(k -> { .forEach(k -> {
@ -257,4 +236,43 @@ public class DisposeTaskMapperTest extends InitTestEnvironment {
} }
})); }));
} }
/**
* T 9 get task by task information test.
*/
@Test
public void t9_getTaskByTaskInfoTest() {
disposeTaskMapper.selectAll().forEach(v -> disposeTaskMapper
.getTaskByTaskDetail(v.getDeviceId(),v.getAccountId(),v.getDisposeIp(),v.getType())
.forEach(k -> {
Assert.assertEquals(k.getDeviceId(), v.getDeviceId());
Assert.assertEquals(k.getAccountId(), v.getAccountId());
Assert.assertEquals(k.getDisposeIp(), v.getDisposeIp());
Assert.assertEquals(k.getType(),v.getType());
try {
log.info(objMapper.writerWithDefaultPrettyPrinter().writeValueAsString(k));
} catch (JsonProcessingException e) {
e.printStackTrace();
Assert.fail();
}
}));
}
/**
* T 10 get task by type test.
*/
@Test
public void t10_getTaskByTypeTest() {
disposeTaskMapper.selectAll().forEach(v -> disposeTaskMapper
.getAllTaskByType(v.getType())
.forEach(k -> {
Assert.assertEquals(k.getType(),v.getType());
try {
log.info(objMapper.writerWithDefaultPrettyPrinter().writeValueAsString(k));
} catch (JsonProcessingException e) {
e.printStackTrace();
Assert.fail();
}
}));
}
} }

View File

@ -0,0 +1,185 @@
package com.dispose.test.mapper;
import com.dispose.common.DeviceCapacity;
import com.dispose.mapper.DisposeDeviceMapper;
import com.dispose.mapper.DisposeTaskMapper;
import com.dispose.mapper.TaskInfoMapper;
import com.dispose.pojo.entity.DisposeDevice;
import com.dispose.pojo.vo.common.TaskInfo;
import com.dispose.pojo.vo.common.TaskInfoDetail;
import com.dispose.test.Global.InitTestEnvironment;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
/**
* The type task information mapper test.
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@Transactional
@Rollback
public class TaskInfoMapperTest extends InitTestEnvironment {
/**
* The Object mapper.
*/
@Resource
private ObjectMapper objectMapper;
/**
* The task information mapper.
*/
@Resource
private TaskInfoMapper taskInfoMapper;
/**
* The Dispose task mapper.
*/
@Resource
private DisposeTaskMapper disposeTaskMapper;
/**
* The Dispose device mapper.
*/
@Resource
private DisposeDeviceMapper disposeDeviceMapper;
/**
* T 1 add new task information.
*
* @throws JsonProcessingException the json processing exception
*/
@Test
public void t1_addNewTaskInfo() throws JsonProcessingException {
Long beginTime = null;
Long endTime = null;
Long taskId = null;
DisposeDevice dev = disposeDeviceMapper.getDeviceByIp("10.88.77.15");
List<TaskInfoDetail> taskInfoDetailList = disposeTaskMapper.getAllTaskByType(DeviceCapacity.CLEANUP.getCode());
for (TaskInfoDetail task : taskInfoDetailList
) {
if (task.getDeviceId().equals(dev.getId())) {
taskId = task.getId();
log.info("taskId:{}", taskId);
break;
}
}
TaskInfo taskInfo = TaskInfo.builder()
.id(-1L)
.taskId(taskId)
.deviceId(dev.getId())
.externId(null)
.status(0L)
.beginTime(String.valueOf(beginTime))
.endTime(String.valueOf(endTime))
.build();
taskInfoMapper.addNewTaskInfo(taskInfo.getTaskId(), taskInfo.getDeviceId(), taskInfo.getExternId(), taskInfo.getStatus());
log.info(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(taskInfo));
List<TaskInfo> taskInfoList = taskInfoMapper.getTaskInfoByTaskId(taskInfo.getTaskId());
if (taskInfoList.size() > 0) {
Assert.assertNotEquals(taskInfoList.size(), 0);
log.info(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(taskInfoList));
}
}
/**
* T 2 get task information by taskId.
*
* @throws JsonProcessingException the json processing exception
*/
@Test
public void t2_getTaskInfoByTaskId() throws JsonProcessingException {
List<TaskInfoDetail> taskInfoDetailList = disposeTaskMapper.getAllTaskByType(DeviceCapacity.CLEANUP.getCode());
if (taskInfoDetailList.size() > 0) {
for (TaskInfoDetail task : taskInfoDetailList
) {
log.info("taskId:{}", task.getId());
List<TaskInfo> taskInfoList = taskInfoMapper.getTaskInfoByTaskId(task.getId());
if (taskInfoList.size() > 0) {
Assert.assertNotEquals(taskInfoList.size(), 0);
log.info(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(taskInfoList));
}
}
}
}
/**
* T 3 get task information by taskId and deviceId.
*
* @throws JsonProcessingException the json processing exception
*/
@Test
public void t3_getTaskInfo() throws JsonProcessingException {
List<TaskInfoDetail> taskInfoDetailList = disposeTaskMapper.getAllTaskByType(DeviceCapacity.CLEANUP.getCode());
if (taskInfoDetailList.size() > 0) {
for (TaskInfoDetail task : taskInfoDetailList
) {
log.info("taskId-->{}, deviceId-->{}", task.getId(), task.getDeviceId());
TaskInfo taskInfo = taskInfoMapper.getTaskInfo(task.getId(), task.getDeviceId());
if (taskInfo != null) {
Assert.assertNotNull(taskInfo);
log.info(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(taskInfo));
}
}
}
}
/**
* T 4 change Task Information Status.
*/
@Test
public void t4_changeTaskInfoStatus() {
List<TaskInfoDetail> taskInfoDetailList = disposeTaskMapper.getAllTaskByType(DeviceCapacity.CLEANUP.getCode());
if (taskInfoDetailList.size() > 0) {
for (TaskInfoDetail task : taskInfoDetailList
) {
log.info("taskId-->{}", task.getId());
List<TaskInfo> taskInfoList = taskInfoMapper.getTaskInfoByTaskId(task.getId());
if (taskInfoList.size() > 0) {
Assert.assertNotEquals(taskInfoList.size(), 0);
for (TaskInfo taskInfo : taskInfoList
) {
Assert.assertNotNull(taskInfo.getStatus());
Long beforeStatus = taskInfo.getStatus();
long changeStatus = 0;
if (beforeStatus == 0) {
changeStatus = 1L;
}
log.info("task_info table Id-->{}, before Status-->{}, change Stauts-->{}",
taskInfo.getId(), taskInfo.getStatus(), changeStatus);
taskInfoMapper.changeTaskInfoStatus(taskInfo.getId(), changeStatus);
Assert.assertNotEquals(beforeStatus, new Long((long) taskInfoMapper.getTaskInfoCurrentStatus(taskInfo.getId())));
}
}
}
}
}
}

View File

@ -1,9 +1,9 @@
package com.dispose.test.mapper; package com.dispose.test.mapper;
import com.dispose.test.Global.InitTestEnvironment;
import com.dispose.common.ConstValue; import com.dispose.common.ConstValue;
import com.dispose.mapper.UserAccountMapper; import com.dispose.mapper.UserAccountMapper;
import com.dispose.pojo.entity.UserAccount; import com.dispose.pojo.entity.UserAccount;
import com.dispose.test.Global.InitTestEnvironment;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;

View File

@ -1,11 +1,11 @@
package com.dispose.test.service; package com.dispose.test.service;
import com.dispose.test.Global.InitTestEnvironment;
import com.dispose.common.DeviceCapacity; import com.dispose.common.DeviceCapacity;
import com.dispose.common.ErrorCode; import com.dispose.common.ErrorCode;
import com.dispose.mapper.DisposeDeviceMapper; import com.dispose.mapper.DisposeDeviceMapper;
import com.dispose.pojo.po.MulReturnType; import com.dispose.pojo.po.MulReturnType;
import com.dispose.service.DisposeNodeManager; import com.dispose.service.DisposeNodeManager;
import com.dispose.test.Global.InitTestEnvironment;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@ -41,8 +41,7 @@ public class DisposeNodeManagerTest extends InitTestEnvironment {
* The Un used ip addr. * The Un used ip addr.
*/ */
private final String[] unUsedIpAddr = new String[]{"192.168.3.1", "192.168.3.6", private final String[] unUsedIpAddr = new String[]{"192.168.3.1", "192.168.3.6",
"192.168.6.8", "192.168.6.10", "192.168.6.8", "192.168.6.10", "255.255.255.255"};
"0.0.0.0", "255.255.255.255"};
/** /**
* The Object mapper. * The Object mapper.
*/ */
@ -86,7 +85,7 @@ public class DisposeNodeManagerTest extends InitTestEnvironment {
log.info("Test:{} --> {}", s, objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString( log.info("Test:{} --> {}", s, objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(
disposeNodeManager.getDisposeDevice(s, DeviceCapacity.CLEANUP) disposeNodeManager.getDisposeDevice(s, DeviceCapacity.CLEANUP)
)); ));
Assert.assertNull(disposeNodeManager.getDisposeDevice(s, DeviceCapacity.CLEANUP)); Assert.assertEquals(disposeNodeManager.getDisposeDevice(s, DeviceCapacity.CLEANUP).size(), 0);
} }
} }

View File

@ -1,6 +1,5 @@
package com.dispose.test.service; package com.dispose.test.service;
import com.dispose.test.Global.InitTestEnvironment;
import com.dispose.common.DeviceCapacity; import com.dispose.common.DeviceCapacity;
import com.dispose.common.DisposeTaskStatus; import com.dispose.common.DisposeTaskStatus;
import com.dispose.common.ErrorCode; import com.dispose.common.ErrorCode;
@ -8,6 +7,7 @@ import com.dispose.common.FlowDirection;
import com.dispose.mapper.DisposeTaskMapper; import com.dispose.mapper.DisposeTaskMapper;
import com.dispose.pojo.vo.common.TaskInfoDetail; import com.dispose.pojo.vo.common.TaskInfoDetail;
import com.dispose.service.TaskService; import com.dispose.service.TaskService;
import com.dispose.test.Global.InitTestEnvironment;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.junit.Assert; import org.junit.Assert;
import org.junit.FixMethodOrder; import org.junit.FixMethodOrder;
@ -73,6 +73,10 @@ public class TaskServiceTest extends InitTestEnvironment {
disposeTaskMapper.getAllTaskByStatus(DisposeTaskStatus.TASK_NEW.getCode()).forEach(v -> { disposeTaskMapper.getAllTaskByStatus(DisposeTaskStatus.TASK_NEW.getCode()).forEach(v -> {
ErrorCode err = taskService.startTask(v.getId()); ErrorCode err = taskService.startTask(v.getId());
Assert.assertEquals(err, ErrorCode.ERR_OK); Assert.assertEquals(err, ErrorCode.ERR_OK);
int currentStatus = disposeTaskMapper.getTaskCurrentStatus(v.getId());
log.info("current status:{}", currentStatus);
Assert.assertEquals(currentStatus, DisposeTaskStatus.TASK_RUNNING.getCode());
}); });
} }
@ -85,7 +89,13 @@ public class TaskServiceTest extends InitTestEnvironment {
disposeTaskMapper.getAllTaskByStatus(DisposeTaskStatus.TASK_RUNNING.getCode()).forEach(v -> { disposeTaskMapper.getAllTaskByStatus(DisposeTaskStatus.TASK_RUNNING.getCode()).forEach(v -> {
ErrorCode err = taskService.stopTask(v.getId()); ErrorCode err = taskService.stopTask(v.getId());
Assert.assertEquals(err, ErrorCode.ERR_OK); Assert.assertEquals(err, ErrorCode.ERR_OK);
int currentStatus = disposeTaskMapper.getTaskCurrentStatus(v.getId());
log.info("current status:{}", currentStatus);
Assert.assertEquals(currentStatus, DisposeTaskStatus.TASK_FINISH.getCode());
taskService.finishTask(v.getId()); taskService.finishTask(v.getId());
Assert.assertNotNull(taskService.getNodeAllTask(v.getDeviceId()));
}); });
} }

View File

@ -1,10 +1,10 @@
package com.dispose.test.service; package com.dispose.test.service;
import com.dispose.test.Global.InitTestEnvironment;
import com.dispose.common.ErrorCode; import com.dispose.common.ErrorCode;
import com.dispose.pojo.entity.UserAccount; import com.dispose.pojo.entity.UserAccount;
import com.dispose.pojo.po.MulReturnType; import com.dispose.pojo.po.MulReturnType;
import com.dispose.service.UserAccountService; import com.dispose.service.UserAccountService;
import com.dispose.test.Global.InitTestEnvironment;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
@ -80,6 +80,9 @@ public class UserAccountServiceTest extends InitTestEnvironment {
public void t2_logoutServiceTest() { public void t2_logoutServiceTest() {
ErrorCode err = userAccountService.logoutService(getUSER_NAME(), token); ErrorCode err = userAccountService.logoutService(getUSER_NAME(), token);
Assert.assertEquals(err, ErrorCode.ERR_OK); Assert.assertEquals(err, ErrorCode.ERR_OK);
err = userAccountService.logoutService(getUSER_NAME(), token + "1235");
Assert.assertEquals(err, ErrorCode.ERR_LOGOUT);
} }
/** /**
@ -98,5 +101,6 @@ public class UserAccountServiceTest extends InitTestEnvironment {
@Test @Test
public void t4_authTokenCheckTest() { public void t4_authTokenCheckTest() {
Assert.assertEquals(userAccountService.authTokenCheck(token), ErrorCode.ERR_OK); Assert.assertEquals(userAccountService.authTokenCheck(token), ErrorCode.ERR_OK);
Assert.assertEquals(userAccountService.authTokenCheck(token + "1235"), ErrorCode.ERR_LOGOUT);
} }
} }