diff --git a/pom.xml b/pom.xml index 2506812..e1de988 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.daxiang server - 0.7.7 + 0.7.8 jar diff --git a/src/main/java/com/daxiang/controller/ActionController.java b/src/main/java/com/daxiang/controller/ActionController.java index 57b475f..427968c 100644 --- a/src/main/java/com/daxiang/controller/ActionController.java +++ b/src/main/java/com/daxiang/controller/ActionController.java @@ -2,8 +2,11 @@ import com.daxiang.mbg.po.Action; import com.daxiang.model.PageRequest; +import com.daxiang.model.PagedData; import com.daxiang.model.Response; +import com.daxiang.model.dto.ActionTreeNode; import com.daxiang.model.request.ActionDebugRequest; +import com.daxiang.model.vo.ActionVo; import com.daxiang.service.ActionService; import com.daxiang.validator.group.SaveActionGroup; import com.daxiang.validator.group.UpdateGroup; @@ -27,32 +30,43 @@ public class ActionController { @PostMapping("/add") public Response add(@RequestBody @Validated({SaveActionGroup.class}) Action action) { - return actionService.add(action); + actionService.add(action); + return Response.success("添加成功"); } @PostMapping("/resetBasicAction") public Response resetBasicAction(@RequestBody List actions) { - return actionService.resetBasicAction(actions); + actionService.resetBasicAction(actions); + return Response.success(); } @DeleteMapping("/{actionId}") public Response delete(@PathVariable Integer actionId) { - return actionService.delete(actionId); + actionService.delete(actionId); + return Response.success("删除成功"); } @PostMapping("/update") public Response update(@RequestBody @Validated({SaveActionGroup.class, UpdateGroup.class}) Action action) { - return actionService.update(action); + actionService.update(action); + return Response.success("更新成功"); } @PostMapping("/list") - public Response list(Action action, PageRequest pageRequest) { - return actionService.list(action, pageRequest); + public Response list(Action query, String orderBy, PageRequest pageRequest) { + if (pageRequest.needPaging()) { + PagedData pagedData = actionService.list(query, orderBy, pageRequest); + return Response.success(pagedData); + } else { + List actionVos = actionService.getActionVos(query, orderBy); + return Response.success(actionVos); + } } @GetMapping("/cascader") public Response cascader(Integer projectId, Integer platform, Integer type) { - return actionService.cascader(projectId, platform, type); + List tree = actionService.cascader(projectId, platform, type); + return Response.success(tree); } @PostMapping("/debug") diff --git a/src/main/java/com/daxiang/controller/AgentController.java b/src/main/java/com/daxiang/controller/AgentController.java index a2c9841..76ef6eb 100644 --- a/src/main/java/com/daxiang/controller/AgentController.java +++ b/src/main/java/com/daxiang/controller/AgentController.java @@ -1,12 +1,15 @@ package com.daxiang.controller; import com.daxiang.model.Response; +import com.daxiang.model.vo.AgentVo; import com.daxiang.service.AgentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import java.util.List; + /** * Created by jiangyitao. @@ -18,14 +21,10 @@ public class AgentController { @Autowired private AgentService agentService; - /** - * 获取当前在线的agent信息 - * - * @return - */ @GetMapping("/online") public Response getOnlineAgents() { - return agentService.getOnlineAgents(); + List agents = agentService.getOnlineAgents(); + return Response.success(agents); } } diff --git a/src/main/java/com/daxiang/controller/AppController.java b/src/main/java/com/daxiang/controller/AppController.java index 0915210..1fc27c3 100644 --- a/src/main/java/com/daxiang/controller/AppController.java +++ b/src/main/java/com/daxiang/controller/AppController.java @@ -2,7 +2,9 @@ import com.daxiang.mbg.po.App; import com.daxiang.model.PageRequest; +import com.daxiang.model.PagedData; import com.daxiang.model.Response; +import com.daxiang.model.vo.AppVo; import com.daxiang.service.AppService; import com.daxiang.validator.group.UpdateGroup; import org.springframework.beans.factory.annotation.Autowired; @@ -11,6 +13,7 @@ import org.springframework.web.multipart.MultipartFile; import javax.validation.Valid; +import java.util.List; /** * Created by jiangyitao. @@ -24,26 +27,37 @@ public class AppController { @PostMapping("/upload") public Response upload(@Valid App app, MultipartFile file) { - return appService.upload(app, file); + appService.upload(app, file); + return Response.success("上传成功"); } @DeleteMapping("/{appId}") public Response delete(@PathVariable Integer appId) { - return appService.delete(appId); + appService.delete(appId); + return Response.success("删除成功"); } @PostMapping("/update") public Response update(@Validated({UpdateGroup.class}) @RequestBody App app) { - return appService.update(app); + appService.update(app); + return Response.success("更新成功"); } @PostMapping("/list") - public Response list(App app, PageRequest pageRequest) { - return appService.list(app, pageRequest); + public Response list(App query, String orderBy, PageRequest pageRequest) { + if (pageRequest.needPaging()) { + PagedData pagedData = appService.list(query, orderBy, pageRequest); + return Response.success(pagedData); + } else { + List appVos = appService.getAppVos(query, orderBy); + return Response.success(appVos); + } } @GetMapping("/{appId}/aaptDumpBadging") public Response aaptDumpBadging(@PathVariable Integer appId) { - return appService.aaptDumpBadging(appId); + appService.aaptDumpBadging(appId); + return Response.success("获取成功"); } + } diff --git a/src/main/java/com/daxiang/controller/ApplicationController.java b/src/main/java/com/daxiang/controller/ApplicationController.java index f0f803c..da9e3d0 100644 --- a/src/main/java/com/daxiang/controller/ApplicationController.java +++ b/src/main/java/com/daxiang/controller/ApplicationController.java @@ -21,4 +21,5 @@ public class ApplicationController { public Response version() { return Response.success(ImmutableMap.of("version", version)); } + } diff --git a/src/main/java/com/daxiang/controller/BrowserController.java b/src/main/java/com/daxiang/controller/BrowserController.java index 2984fcc..3fac3db 100644 --- a/src/main/java/com/daxiang/controller/BrowserController.java +++ b/src/main/java/com/daxiang/controller/BrowserController.java @@ -2,12 +2,14 @@ import com.daxiang.mbg.po.Browser; import com.daxiang.model.PageRequest; +import com.daxiang.model.PagedData; import com.daxiang.model.Response; import com.daxiang.service.BrowserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; +import java.util.List; /** * Created by jiangyitao. @@ -21,22 +23,31 @@ public class BrowserController { @PostMapping("/save") public Response save(@RequestBody @Valid Browser browser) { - return browserService.save(browser); + browserService.save(browser); + return Response.success("保存成功"); } @PostMapping("/list") - public Response list(Browser browser, PageRequest pageRequest) { - return browserService.list(browser, pageRequest); + public Response list(Browser query, String orderBy, PageRequest pageRequest) { + if (pageRequest.needPaging()) { + PagedData pagedData = browserService.list(query, orderBy, pageRequest); + return Response.success(pagedData); + } else { + List browsers = browserService.getBrowsers(query, orderBy); + return Response.success(browsers); + } } @GetMapping("/{browserId}/start") public Response start(@PathVariable String browserId) { - return browserService.start(browserId); + Browser browser = browserService.start(browserId); + return Response.success(browser); } @GetMapping("/online") public Response getOnlineBrowsers() { - return browserService.getOnlineBrowsers(); + List onlineBrowsers = browserService.getOnlineBrowsers(); + return Response.success(onlineBrowsers); } -} +} \ No newline at end of file diff --git a/src/main/java/com/daxiang/controller/CategoryController.java b/src/main/java/com/daxiang/controller/CategoryController.java index bd9d85a..158dda6 100644 --- a/src/main/java/com/daxiang/controller/CategoryController.java +++ b/src/main/java/com/daxiang/controller/CategoryController.java @@ -2,14 +2,18 @@ import com.daxiang.mbg.po.Category; import com.daxiang.model.PageRequest; +import com.daxiang.model.PagedData; import com.daxiang.model.Response; +import com.daxiang.model.vo.CategoryVo; import com.daxiang.service.CategoryService; +import com.daxiang.utils.Tree; import com.daxiang.validator.group.UpdateGroup; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; +import java.util.List; /** * Created by jiangyitao. @@ -23,27 +27,37 @@ public class CategoryController { @PostMapping("/add") public Response add(@RequestBody @Valid Category category) { - return categoryService.add(category); + categoryService.add(category); + return Response.success("添加成功"); } @DeleteMapping("/{categoryId}/type/{type}/project/{projectId}") public Response delete(@PathVariable Integer categoryId, @PathVariable Integer type, @PathVariable Integer projectId) { - return categoryService.delete(categoryId, type, projectId); + categoryService.delete(categoryId, type, projectId); + return Response.success("删除成功"); } @PostMapping("/update") public Response update(@RequestBody @Validated({UpdateGroup.class}) Category category) { - return categoryService.update(category); + categoryService.update(category); + return Response.success("更新成功"); } @PostMapping("/list") - public Response list(Category category, PageRequest pageRequest) { - return categoryService.list(category, pageRequest); + public Response list(Category query, String orderBy, PageRequest pageRequest) { + if (pageRequest.needPaging()) { + PagedData pagedData = categoryService.list(query, orderBy, pageRequest); + return Response.success(pagedData); + } else { + List categoryVos = categoryService.getCategoryVos(query, orderBy); + return Response.success(categoryVos); + } } @GetMapping("/tree") public Response getCategoryTree(Integer projectId, Integer type) { - return categoryService.getCategoryTreeByProjectIdAndType(projectId, type); + List tree = categoryService.getCategoryTreeByProjectIdAndType(projectId, type); + return Response.success(tree); } -} +} \ No newline at end of file diff --git a/src/main/java/com/daxiang/controller/DeviceTestTaskController.java b/src/main/java/com/daxiang/controller/DeviceTestTaskController.java index 83c8613..90a56be 100644 --- a/src/main/java/com/daxiang/controller/DeviceTestTaskController.java +++ b/src/main/java/com/daxiang/controller/DeviceTestTaskController.java @@ -2,12 +2,17 @@ import com.daxiang.model.PageRequest; import com.daxiang.mbg.po.DeviceTestTask; +import com.daxiang.model.PagedData; import com.daxiang.model.Response; import com.daxiang.model.dto.Testcase; import com.daxiang.service.DeviceTestTaskService; +import com.daxiang.validator.group.UpdateGroup; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; +import java.util.List; + /** * Created by jiangyitao. */ @@ -19,40 +24,38 @@ public class DeviceTestTaskController { private DeviceTestTaskService deviceTestTaskService; @PostMapping("/update") - public Response update(@RequestBody DeviceTestTask deviceTestTask) { - return deviceTestTaskService.update(deviceTestTask); + public Response update(@RequestBody @Validated({UpdateGroup.class}) DeviceTestTask deviceTestTask) { + deviceTestTaskService.update(deviceTestTask); + return Response.success("更新成功"); } @PostMapping("/list") - public Response list(DeviceTestTask testTaskDevice, PageRequest pageRequest) { - return deviceTestTaskService.list(testTaskDevice, pageRequest); + public Response list(DeviceTestTask query, String orderBy, PageRequest pageRequest) { + if (pageRequest.needPaging()) { + PagedData pagedData = deviceTestTaskService.list(query, orderBy, pageRequest); + return Response.success(pagedData); + } else { + List deviceTestTasks = deviceTestTaskService.getDeviceTestTasks(query, orderBy); + return Response.success(deviceTestTasks); + } } - /** - * 更新device的测试用例运行信息 - * - * @param deviceTestTaskId - * @param testcase - * @return - */ @PostMapping("/{deviceTestTaskId}/updateTestcase") public Response updateTestcase(@PathVariable Integer deviceTestTaskId, @RequestBody Testcase testcase) { - return deviceTestTaskService.updateTestcase(deviceTestTaskId, testcase); + deviceTestTaskService.updateTestcase(deviceTestTaskId, testcase); + return Response.success("更新成功"); } - /** - * 通过deviceId查询未开始的测试任务(最开始的一条) - * - * @return - */ @GetMapping("/firstUnStart/device/{deviceId}") public Response getFirstUnStartDeviceTestTask(@PathVariable String deviceId) { - return deviceTestTaskService.getFirstUnStartDeviceTestTask(deviceId); + DeviceTestTask deviceTestTask = deviceTestTaskService.getFirstUnStartDeviceTestTask(deviceId); + return Response.success(deviceTestTask); } @DeleteMapping("/{deviceTestTaskId}") public Response delete(@PathVariable Integer deviceTestTaskId) { - return deviceTestTaskService.delete(deviceTestTaskId); + deviceTestTaskService.delete(deviceTestTaskId); + return Response.success("删除成功"); } -} +} \ No newline at end of file diff --git a/src/main/java/com/daxiang/controller/DriverController.java b/src/main/java/com/daxiang/controller/DriverController.java index ee99b81..9ac063b 100644 --- a/src/main/java/com/daxiang/controller/DriverController.java +++ b/src/main/java/com/daxiang/controller/DriverController.java @@ -2,14 +2,18 @@ import com.daxiang.mbg.po.Driver; import com.daxiang.model.PageRequest; +import com.daxiang.model.PagedData; import com.daxiang.model.Response; +import com.daxiang.model.vo.DriverVo; import com.daxiang.service.DriverService; import com.daxiang.validator.group.UpdateGroup; +import com.google.common.collect.ImmutableMap; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; +import java.util.List; /** * Created by jiangyitao. @@ -23,26 +27,37 @@ public class DriverController { @PostMapping("/add") public Response add(@Valid @RequestBody Driver driver) { - return driverService.add(driver); + driverService.add(driver); + return Response.success("添加成功"); } @DeleteMapping("/{driverId}") public Response delete(@PathVariable Integer driverId) { - return driverService.delete(driverId); + driverService.delete(driverId); + return Response.success("删除成功"); } @PostMapping("/update") public Response update(@Validated({UpdateGroup.class}) @RequestBody Driver driver) { - return driverService.update(driver); + driverService.update(driver); + return Response.success("更新成功"); } @PostMapping("/list") - public Response list(Driver driver, PageRequest pageRequest) { - return driverService.list(driver, pageRequest); + public Response list(Driver query, String orderBy, PageRequest pageRequest) { + if (pageRequest.needPaging()) { + PagedData pagedData = driverService.list(query, orderBy, pageRequest); + return Response.success(pagedData); + } else { + List driverVos = driverService.getDriverVos(query, orderBy); + return Response.success(driverVos); + } } @PostMapping("/downloadUrl") public Response getDownloadUrl(Integer type, String deviceId, Integer platform) { - return driverService.getDownloadUrl(type, deviceId, platform); + String url = driverService.getDownloadUrl(type, deviceId, platform); + return Response.success(ImmutableMap.of("downloadUrl", url)); } -} + +} \ No newline at end of file diff --git a/src/main/java/com/daxiang/controller/EnvironmentController.java b/src/main/java/com/daxiang/controller/EnvironmentController.java index caae8d9..7939e78 100644 --- a/src/main/java/com/daxiang/controller/EnvironmentController.java +++ b/src/main/java/com/daxiang/controller/EnvironmentController.java @@ -2,7 +2,9 @@ import com.daxiang.mbg.po.Environment; import com.daxiang.model.PageRequest; +import com.daxiang.model.PagedData; import com.daxiang.model.Response; +import com.daxiang.model.vo.EnvironmentVo; import com.daxiang.service.EnvironmentService; import com.daxiang.validator.group.UpdateGroup; import org.springframework.beans.factory.annotation.Autowired; @@ -10,6 +12,7 @@ import org.springframework.web.bind.annotation.*; import javax.validation.Valid; +import java.util.List; /** * Created by jiangyitao. @@ -23,21 +26,30 @@ public class EnvironmentController { @PostMapping("/add") public Response add(@Valid @RequestBody Environment environment) { - return environmentService.add(environment); + environmentService.add(environment); + return Response.success("添加成功"); } @DeleteMapping("/{environmentId}") public Response delete(@PathVariable Integer environmentId) { - return environmentService.delete(environmentId); + environmentService.delete(environmentId); + return Response.success("删除成功"); } @PostMapping("/update") public Response update(@Validated({UpdateGroup.class}) @RequestBody Environment environment) { - return environmentService.update(environment); + environmentService.update(environment); + return Response.success("更新成功"); } @PostMapping("/list") - public Response list(Environment environment, PageRequest pageRequest) { - return environmentService.list(environment, pageRequest); + public Response list(Environment query, String orderBy, PageRequest pageRequest) { + if (pageRequest.needPaging()) { + PagedData pagedData = environmentService.list(query, orderBy, pageRequest); + return Response.success(pagedData); + } else { + List environmentVos = environmentService.getEnvironmentVos(query, orderBy); + return Response.success(environmentVos); + } } -} +} \ No newline at end of file diff --git a/src/main/java/com/daxiang/controller/GlobalExceptionHandler.java b/src/main/java/com/daxiang/controller/GlobalExceptionHandler.java index 1632677..d4113ee 100644 --- a/src/main/java/com/daxiang/controller/GlobalExceptionHandler.java +++ b/src/main/java/com/daxiang/controller/GlobalExceptionHandler.java @@ -1,6 +1,6 @@ package com.daxiang.controller; -import com.daxiang.exception.BusinessException; +import com.daxiang.exception.ServerException; import com.daxiang.model.Response; import lombok.extern.slf4j.Slf4j; import org.springframework.security.access.AccessDeniedException; @@ -44,14 +44,14 @@ public Response handleAccessDeniedException() { } /** - * BusinessException + * ServerException * * @param e * @return */ @ResponseBody - @ExceptionHandler(BusinessException.class) - public Response handleBusinessException(BusinessException e) { + @ExceptionHandler(ServerException.class) + public Response handleBusinessException(ServerException e) { return Response.fail(e.getMessage()); } diff --git a/src/main/java/com/daxiang/controller/GlobalVarController.java b/src/main/java/com/daxiang/controller/GlobalVarController.java index dee4a49..3797174 100644 --- a/src/main/java/com/daxiang/controller/GlobalVarController.java +++ b/src/main/java/com/daxiang/controller/GlobalVarController.java @@ -2,11 +2,12 @@ import com.daxiang.mbg.po.GlobalVar; import com.daxiang.model.PageRequest; +import com.daxiang.model.PagedData; import com.daxiang.model.Response; +import com.daxiang.model.vo.GlobalVarVo; import com.daxiang.service.GlobalVarService; import com.daxiang.validator.group.GlobalVarGroup; import com.daxiang.validator.group.UpdateGroup; -import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; @@ -18,9 +19,8 @@ /** * Created by jiangyitao. */ -@RestController -@Slf4j @Validated({GlobalVarGroup.class}) +@RestController @RequestMapping("/globalVar") public class GlobalVarController { @@ -29,27 +29,37 @@ public class GlobalVarController { @PostMapping("/add") public Response add(@RequestBody @Validated({GlobalVarGroup.class}) GlobalVar globalVar) { - return globalVarService.add(globalVar); + globalVarService.add(globalVar); + return Response.success("添加成功"); } @PostMapping("/addBatch") public Response addBatch(@RequestBody @NotEmpty(message = "全局变量不能为空") @Valid List globalVars) { - return globalVarService.addBatch(globalVars); + globalVarService.addBatch(globalVars); + return Response.success("添加成功"); } @DeleteMapping("/{globalVarId}") public Response delete(@PathVariable Integer globalVarId) { - return globalVarService.delete(globalVarId); + globalVarService.delete(globalVarId); + return Response.success("删除成功"); } @PostMapping("/update") public Response update(@RequestBody @Validated({GlobalVarGroup.class, UpdateGroup.class}) GlobalVar globalVar) { - return globalVarService.update(globalVar); + globalVarService.update(globalVar); + return Response.success("更新成功"); } @PostMapping("/list") - public Response list(GlobalVar globalVar, PageRequest pageRequest) { - return globalVarService.list(globalVar, pageRequest); + public Response list(GlobalVar query, String orderBy, PageRequest pageRequest) { + if (pageRequest.needPaging()) { + PagedData pagedData = globalVarService.list(query, orderBy, pageRequest); + return Response.success(pagedData); + } else { + List globalVarVos = globalVarService.getGlobalVarVos(query, orderBy); + return Response.success(globalVarVos); + } } } diff --git a/src/main/java/com/daxiang/controller/MobileController.java b/src/main/java/com/daxiang/controller/MobileController.java index 2245924..d0650b2 100644 --- a/src/main/java/com/daxiang/controller/MobileController.java +++ b/src/main/java/com/daxiang/controller/MobileController.java @@ -2,12 +2,15 @@ import com.daxiang.mbg.po.Mobile; import com.daxiang.model.PageRequest; +import com.daxiang.model.PagedData; import com.daxiang.model.Response; +import com.daxiang.model.vo.MobileVo; import com.daxiang.service.MobileService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; +import java.util.List; /** * Created by jiangyitao. @@ -21,22 +24,31 @@ public class MobileController { @PostMapping("/save") public Response save(@RequestBody @Valid Mobile mobile) { - return mobileService.save(mobile); + mobileService.save(mobile); + return Response.success("保存成功"); } @PostMapping("/list") - public Response list(Mobile mobile, PageRequest pageRequest) { - return mobileService.list(mobile, pageRequest); + public Response list(Mobile query, String orderBy, PageRequest pageRequest) { + if (pageRequest.needPaging()) { + PagedData pagedData = mobileService.list(query, orderBy, pageRequest); + return Response.success(pagedData); + } else { + List mobileVos = mobileService.getMobileVos(query, orderBy); + return Response.success(mobileVos); + } } @GetMapping("/{mobileId}/start") public Response start(@PathVariable String mobileId) { - return mobileService.start(mobileId); + Mobile mobile = mobileService.start(mobileId); + return Response.success(mobile); } @GetMapping("/online/platform/{platform}") public Response getOnlineMobiles(@PathVariable Integer platform) { - return mobileService.getOnlineMobiles(platform); + List onlineMobiles = mobileService.getOnlineMobiles(platform); + return Response.success(onlineMobiles); } } diff --git a/src/main/java/com/daxiang/controller/PageController.java b/src/main/java/com/daxiang/controller/PageController.java index a9ca735..4a65b19 100644 --- a/src/main/java/com/daxiang/controller/PageController.java +++ b/src/main/java/com/daxiang/controller/PageController.java @@ -2,7 +2,9 @@ import com.daxiang.mbg.po.Page; import com.daxiang.model.PageRequest; +import com.daxiang.model.PagedData; import com.daxiang.model.Response; +import com.daxiang.model.vo.PageVo; import com.daxiang.service.PageService; import com.daxiang.validator.group.UpdateGroup; import lombok.extern.slf4j.Slf4j; @@ -11,6 +13,7 @@ import org.springframework.web.bind.annotation.*; import javax.validation.Valid; +import java.util.List; /** * Created by jiangyitao. @@ -25,28 +28,37 @@ public class PageController { @PostMapping("/add") public Response add(@Valid @RequestBody Page page) { - return pageService.add(page); + pageService.add(page); + return Response.success("添加成功"); } @GetMapping("/{pageId}") public Response getPageVoById(@PathVariable Integer pageId) { - return pageService.getPageVoById(pageId); + PageVo pageVo = pageService.getPageVoById(pageId); + return Response.success(pageVo); } @DeleteMapping("/{pageId}") public Response delete(@PathVariable Integer pageId) { - return pageService.delete(pageId); + pageService.delete(pageId); + return Response.success("删除成功"); } @PostMapping("/update") public Response update(@Validated({UpdateGroup.class}) @RequestBody Page page) { - return pageService.update(page); + pageService.update(page); + return Response.success("更新成功"); } - @PostMapping("/list") - public Response list(Page page, PageRequest pageRequest) { - return pageService.list(page, pageRequest); + public Response list(Page query, String orderBy, PageRequest pageRequest) { + if (pageRequest.needPaging()) { + PagedData pagedData = pageService.listWithoutWindowHierarchy(query, orderBy, pageRequest); + return Response.success(pagedData); + } else { + List pageVos = pageService.getPageVosWithoutWindowHierarchy(query, orderBy); + return Response.success(pageVos); + } } } diff --git a/src/main/java/com/daxiang/controller/ProjectController.java b/src/main/java/com/daxiang/controller/ProjectController.java index 1f29714..4fb7393 100644 --- a/src/main/java/com/daxiang/controller/ProjectController.java +++ b/src/main/java/com/daxiang/controller/ProjectController.java @@ -1,7 +1,9 @@ package com.daxiang.controller; import com.daxiang.model.PageRequest; +import com.daxiang.model.PagedData; import com.daxiang.model.Response; +import com.daxiang.model.vo.ProjectVo; import com.daxiang.service.ProjectService; import com.daxiang.mbg.po.Project; import com.daxiang.validator.group.UpdateGroup; @@ -11,6 +13,7 @@ import org.springframework.web.bind.annotation.*; import javax.validation.Valid; +import java.util.List; /** * Created by jiangyitao. @@ -23,43 +26,32 @@ public class ProjectController { @Autowired private ProjectService projectService; - /** - * 新增项目 - * - * @return - */ @PostMapping("/add") public Response add(@Valid @RequestBody Project project) { - return projectService.add(project); + projectService.add(project); + return Response.success("添加成功"); } - /** - * 删除项目 - * - * @param projectId - * @return - */ @DeleteMapping("/{projectId}") public Response delete(@PathVariable Integer projectId) { - return projectService.delete(projectId); + projectService.delete(projectId); + return Response.success("删除成功"); } - /** - * 修改项目 - */ @PostMapping("/update") public Response update(@Validated({UpdateGroup.class}) @RequestBody Project project) { - return projectService.update(project); + projectService.update(project); + return Response.success("更新成功"); } - /** - * 查询项目列表 - * - * @return - */ @PostMapping("/list") - public Response list(Project project, PageRequest pageRequest) { - return projectService.list(project, pageRequest); + public Response list(Project query, String orderBy, PageRequest pageRequest) { + if (pageRequest.needPaging()) { + PagedData pagedData = projectService.list(query, orderBy, pageRequest); + return Response.success(pagedData); + } else { + List projectVos = projectService.getProjectVos(query, orderBy); + return Response.success(projectVos); + } } - } diff --git a/src/main/java/com/daxiang/controller/RoleController.java b/src/main/java/com/daxiang/controller/RoleController.java index 3fa7cea..fbddaf4 100644 --- a/src/main/java/com/daxiang/controller/RoleController.java +++ b/src/main/java/com/daxiang/controller/RoleController.java @@ -1,5 +1,6 @@ package com.daxiang.controller; +import com.daxiang.mbg.po.Role; import com.daxiang.model.Response; import com.daxiang.service.RoleService; import org.springframework.beans.factory.annotation.Autowired; @@ -7,6 +8,8 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import java.util.List; + /** * Created by jiangyitao. */ @@ -19,6 +22,7 @@ public class RoleController { @GetMapping("/list") public Response list() { - return roleService.list(); + List roles = roleService.list(); + return Response.success(roles); } } diff --git a/src/main/java/com/daxiang/controller/TestPlanController.java b/src/main/java/com/daxiang/controller/TestPlanController.java index 6c98fc9..3809d5a 100644 --- a/src/main/java/com/daxiang/controller/TestPlanController.java +++ b/src/main/java/com/daxiang/controller/TestPlanController.java @@ -2,7 +2,9 @@ import com.daxiang.mbg.po.TestPlan; import com.daxiang.model.PageRequest; +import com.daxiang.model.PagedData; import com.daxiang.model.Response; +import com.daxiang.model.vo.TestPlanVo; import com.daxiang.service.TestPlanService; import com.daxiang.validator.group.UpdateGroup; import org.springframework.beans.factory.annotation.Autowired; @@ -10,6 +12,7 @@ import org.springframework.web.bind.annotation.*; import javax.validation.Valid; +import java.util.List; /** * Created by jiangyitao. @@ -21,48 +24,32 @@ public class TestPlanController { @Autowired private TestPlanService testPlanService; - /** - * 添加测试计划 - * - * @param testPlan - * @return - */ @PostMapping("/add") public Response addTestPlan(@RequestBody @Valid TestPlan testPlan) { - return testPlanService.add(testPlan); + testPlanService.add(testPlan); + return Response.success("添加成功"); } - /** - * 删除测试计划 - * - * @param testPlanId - * @return - */ @DeleteMapping("/{testPlanId}") public Response deleteTestPlan(@PathVariable Integer testPlanId) { - return testPlanService.delete(testPlanId); + testPlanService.delete(testPlanId); + return Response.success("删除成功"); } - /** - * 更新测试计划 - * - * @param testPlan - * @return - */ @PostMapping("/update") public Response updateTestPlan(@RequestBody @Validated({UpdateGroup.class}) TestPlan testPlan) { - return testPlanService.update(testPlan); + testPlanService.update(testPlan); + return Response.success("更新成功"); } - /** - * 查询测试计划列表 - * - * @param testPlan - * @param pageRequest - * @return - */ @PostMapping("/list") - public Response list(TestPlan testPlan, PageRequest pageRequest) { - return testPlanService.list(testPlan, pageRequest); + public Response list(TestPlan query, String orderBy, PageRequest pageRequest) { + if (pageRequest.needPaging()) { + PagedData pagedData = testPlanService.list(query, orderBy, pageRequest); + return Response.success(pagedData); + } else { + List testPlanVos = testPlanService.getTestPlanVos(query, orderBy); + return Response.success(testPlanVos); + } } } diff --git a/src/main/java/com/daxiang/controller/TestSuiteController.java b/src/main/java/com/daxiang/controller/TestSuiteController.java index 2a8d05d..256048f 100644 --- a/src/main/java/com/daxiang/controller/TestSuiteController.java +++ b/src/main/java/com/daxiang/controller/TestSuiteController.java @@ -2,7 +2,9 @@ import com.daxiang.mbg.po.TestSuite; import com.daxiang.model.PageRequest; +import com.daxiang.model.PagedData; import com.daxiang.model.Response; +import com.daxiang.model.vo.TestSuiteVo; import com.daxiang.service.TestSuiteService; import com.daxiang.validator.group.UpdateGroup; import org.springframework.beans.factory.annotation.Autowired; @@ -10,6 +12,7 @@ import org.springframework.web.bind.annotation.*; import javax.validation.Valid; +import java.util.List; /** * Created by jiangyitao. @@ -23,22 +26,31 @@ public class TestSuiteController { @PostMapping("/add") public Response add(@Valid @RequestBody TestSuite testSuite) { - return testSuiteService.add(testSuite); + testSuiteService.add(testSuite); + return Response.success("添加成功"); } @DeleteMapping("/{testSuiteId}") public Response delete(@PathVariable Integer testSuiteId) { - return testSuiteService.delete(testSuiteId); + testSuiteService.delete(testSuiteId); + return Response.success("删除成功"); } @PostMapping("/update") public Response update(@RequestBody @Validated({UpdateGroup.class}) TestSuite testSuite) { - return testSuiteService.update(testSuite); + testSuiteService.update(testSuite); + return Response.success("更新成功"); } @PostMapping("/list") - public Response list(TestSuite testSuite, PageRequest pageRequest) { - return testSuiteService.list(testSuite, pageRequest); + public Response list(TestSuite query, String orderBy, PageRequest pageRequest) { + if (pageRequest.needPaging()) { + PagedData pagedData = testSuiteService.list(query, orderBy, pageRequest); + return Response.success(pagedData); + } else { + List testSuiteVos = testSuiteService.getTestSuiteVos(query, orderBy); + return Response.success(testSuiteVos); + } } } diff --git a/src/main/java/com/daxiang/controller/TestTaskController.java b/src/main/java/com/daxiang/controller/TestTaskController.java index 2b14094..44ce3b6 100644 --- a/src/main/java/com/daxiang/controller/TestTaskController.java +++ b/src/main/java/com/daxiang/controller/TestTaskController.java @@ -2,12 +2,17 @@ import com.daxiang.mbg.po.TestTask; import com.daxiang.model.PageRequest; +import com.daxiang.model.PagedData; import com.daxiang.model.Response; +import com.daxiang.model.vo.TestTaskSummary; +import com.daxiang.model.vo.TestTaskVo; import com.daxiang.security.SecurityUtil; import com.daxiang.service.TestTaskService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; +import java.util.List; + /** * Created by jiangyitao. @@ -19,41 +24,32 @@ public class TestTaskController { @Autowired private TestTaskService testTaskService; - /** - * 提交测试任务 - * - * @return - */ @GetMapping("/commit") public Response commit(Integer testPlanId) { - return testTaskService.commit(testPlanId, SecurityUtil.getCurrentUserId()); + testTaskService.commit(testPlanId, SecurityUtil.getCurrentUserId()); + return Response.success("提交成功"); } - /** - * 测试任务列表 - * - * @param testTask - * @param pageRequest - * @return - */ @PostMapping("/list") - public Response list(TestTask testTask, PageRequest pageRequest) { - return testTaskService.list(testTask, pageRequest); + public Response list(TestTask query, String orderBy, PageRequest pageRequest) { + if (pageRequest.needPaging()) { + PagedData pagedData = testTaskService.list(query, orderBy, pageRequest); + return Response.success(pagedData); + } else { + List testTaskVos = testTaskService.getTestTaskVos(query, orderBy); + return Response.success(testTaskVos); + } } - /** - * 测试任务概要 - * - * @param testTaskId - * @return - */ @GetMapping("/{testTaskId}/summary") public Response getTestTaskSummary(@PathVariable Integer testTaskId) { - return testTaskService.getTestTaskSummary(testTaskId); + TestTaskSummary testTaskSummary = testTaskService.getTestTaskSummary(testTaskId); + return Response.success(testTaskSummary); } @DeleteMapping("/{testTaskId}") public Response delete(@PathVariable Integer testTaskId) { - return testTaskService.delete(testTaskId); + testTaskService.delete(testTaskId); + return Response.success("删除成功"); } } diff --git a/src/main/java/com/daxiang/controller/UploadController.java b/src/main/java/com/daxiang/controller/UploadController.java index 51a7220..5af24a8 100644 --- a/src/main/java/com/daxiang/controller/UploadController.java +++ b/src/main/java/com/daxiang/controller/UploadController.java @@ -1,6 +1,7 @@ package com.daxiang.controller; import com.daxiang.model.Response; +import com.daxiang.model.UploadFile; import com.daxiang.service.UploadService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; @@ -23,6 +24,7 @@ public class UploadController { @PostMapping("/file/{fileType}") public Response uploadFile(MultipartFile file, @PathVariable Integer fileType) { - return uploadService.uploadFile(file, fileType); + UploadFile uploadFile = uploadService.upload(file, fileType); + return Response.success(uploadFile); } } diff --git a/src/main/java/com/daxiang/controller/UserController.java b/src/main/java/com/daxiang/controller/UserController.java index 1ec57fa..b2cea18 100644 --- a/src/main/java/com/daxiang/controller/UserController.java +++ b/src/main/java/com/daxiang/controller/UserController.java @@ -2,17 +2,21 @@ import com.daxiang.mbg.po.User; import com.daxiang.model.PageRequest; +import com.daxiang.model.PagedData; import com.daxiang.model.Response; import com.daxiang.model.dto.UserDto; +import com.daxiang.security.SecurityUtil; import com.daxiang.service.UserService; import com.daxiang.validator.group.SaveUserGroup; import com.daxiang.validator.group.UpdateGroup; +import com.google.common.collect.ImmutableMap; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; +import java.util.List; /** * Created by jiangyitao. @@ -27,40 +31,50 @@ public class UserController { @PreAuthorize("hasAuthority('admin')") @PostMapping("/add") public Response add(@Validated({SaveUserGroup.class}) @RequestBody UserDto userDto) { - return userService.add(userDto); + userService.add(userDto); + return Response.success("添加成功"); } @PreAuthorize("hasAuthority('admin')") @DeleteMapping("/{userId}") public Response delete(@PathVariable Integer userId) { - return userService.delete(userId); + userService.delete(userId); + return Response.success("删除成功"); } @PreAuthorize("hasAuthority('admin')") @PostMapping("/update") public Response update(@Validated({SaveUserGroup.class, UpdateGroup.class}) @RequestBody UserDto userDto) { - return userService.update(userDto); + userService.update(userDto); + return Response.success("更新成功"); } @PreAuthorize("hasAuthority('admin')") @PostMapping("/list") - public Response list(User user, PageRequest pageRequest) { - return userService.list(user, pageRequest); + public Response list(User query, String orderBy, PageRequest pageRequest) { + if (pageRequest.needPaging()) { + PagedData pagedData = userService.list(query, orderBy, pageRequest); + return Response.success(pagedData); + } else { + List userDtos = userService.getUserDtos(query, orderBy); + return Response.success(userDtos); + } } @PostMapping("/login") public Response login(@Valid @RequestBody User user) { - return userService.login(user); + String token = userService.login(user); + return Response.success("登陆成功", ImmutableMap.of("token", token)); } @GetMapping("/info") public Response getInfo() { - return userService.getInfo(); + return Response.success(SecurityUtil.getCurrentUserDto()); } @PostMapping("/logout") public Response logout() { - return userService.logout(); + return Response.success(); } } diff --git a/src/main/java/com/daxiang/exception/BusinessException.java b/src/main/java/com/daxiang/exception/BusinessException.java deleted file mode 100644 index 74c8a67..0000000 --- a/src/main/java/com/daxiang/exception/BusinessException.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.daxiang.exception; - -/** - * Created by jiangyitao. - */ -public class BusinessException extends RuntimeException { - public BusinessException(String msg) { - super(msg); - } -} diff --git a/src/main/java/com/daxiang/exception/ServerException.java b/src/main/java/com/daxiang/exception/ServerException.java new file mode 100644 index 0000000..ce9058f --- /dev/null +++ b/src/main/java/com/daxiang/exception/ServerException.java @@ -0,0 +1,14 @@ +package com.daxiang.exception; + +/** + * Created by jiangyitao. + */ +public class ServerException extends RuntimeException { + public ServerException(String msg) { + super(msg); + } + + public ServerException(Throwable cause) { + super(cause); + } +} diff --git a/src/main/java/com/daxiang/init/StartupRunner.java b/src/main/java/com/daxiang/init/StartupRunner.java index 9ded190..7b131c5 100644 --- a/src/main/java/com/daxiang/init/StartupRunner.java +++ b/src/main/java/com/daxiang/init/StartupRunner.java @@ -1,7 +1,6 @@ package com.daxiang.init; import com.daxiang.model.UploadFile; -import com.daxiang.service.DataMigrationService; import com.daxiang.service.TestPlanService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; @@ -21,8 +20,6 @@ public class StartupRunner implements ApplicationRunner { @Autowired private TestPlanService testPlanService; - @Autowired - private DataMigrationService dataMigrationService; @Value("${static-location}/") private String staticLocation; @@ -67,8 +64,5 @@ public void run(ApplicationArguments args) { // 启动server时,按cron表达式执行所有开启的定时任务 testPlanService.scheduleEnabledTasks(); - - // v0.7.5 数据迁移 todo 后续删除 - dataMigrationService.actionStepParamValuesToArgs(); } } diff --git a/src/main/java/com/daxiang/mbg/po/DeviceTestTask.java b/src/main/java/com/daxiang/mbg/po/DeviceTestTask.java index 9eeaaa4..2ff4836 100644 --- a/src/main/java/com/daxiang/mbg/po/DeviceTestTask.java +++ b/src/main/java/com/daxiang/mbg/po/DeviceTestTask.java @@ -4,6 +4,9 @@ import com.daxiang.mbg.po.GlobalVar; import com.daxiang.mbg.po.Page; import com.daxiang.model.dto.Testcase; +import com.daxiang.validator.group.UpdateGroup; + +import javax.validation.constraints.NotNull; import java.io.Serializable; import java.util.Date; import java.util.List; @@ -19,6 +22,7 @@ public class DeviceTestTask implements Serializable { /** 完成 */ public static final int FINISHED_STATUS = 2; + @NotNull(message = "id不能为空", groups = {UpdateGroup.class}) private Integer id; /** diff --git a/src/main/java/com/daxiang/model/Page.java b/src/main/java/com/daxiang/model/Page.java deleted file mode 100644 index 6ab0dad..0000000 --- a/src/main/java/com/daxiang/model/Page.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.daxiang.model; - -import com.github.pagehelper.PageInfo; -import lombok.Data; - -import java.util.List; - -/** - * Created by jiangyitao. - */ -@Data -public class Page { - private Long total; - private List data; - - public static long getTotal(List data) { - return new PageInfo(data).getTotal(); - } - - public static Page build(List data, long total) { - Page page = new Page(); - page.setTotal(total); - page.setData(data); - return page; - } -} - diff --git a/src/main/java/com/daxiang/model/PageRequest.java b/src/main/java/com/daxiang/model/PageRequest.java index c954333..07356b6 100644 --- a/src/main/java/com/daxiang/model/PageRequest.java +++ b/src/main/java/com/daxiang/model/PageRequest.java @@ -7,6 +7,7 @@ */ @Data public class PageRequest { + private Integer pageNum; private Integer pageSize; @@ -16,6 +17,6 @@ public class PageRequest { * @return */ public boolean needPaging() { - return pageNum != null && pageNum > 0 && pageSize != null && pageSize > 0; + return (pageNum != null && pageNum > 0) && (pageSize != null && pageSize > 0); } } diff --git a/src/main/java/com/daxiang/model/PagedData.java b/src/main/java/com/daxiang/model/PagedData.java new file mode 100644 index 0000000..ddd5976 --- /dev/null +++ b/src/main/java/com/daxiang/model/PagedData.java @@ -0,0 +1,20 @@ +package com.daxiang.model; + +import lombok.Data; + +import java.util.List; + +/** + * Created by jiangyitao. + */ +@Data +public class PagedData { + private long total; + private List data; + + public PagedData(List data, long total) { + this.data = data; + this.total = total; + } +} + diff --git a/src/main/java/com/daxiang/model/Platform.java b/src/main/java/com/daxiang/model/Platform.java index 572b879..fd1605d 100644 --- a/src/main/java/com/daxiang/model/Platform.java +++ b/src/main/java/com/daxiang/model/Platform.java @@ -4,5 +4,7 @@ * Created by jiangyitao. */ public interface Platform { - Integer ANDROID = 1; + int ANDROID = 1; + int IOS = 2; + int PC_WEB = 3; } diff --git a/src/main/java/com/daxiang/model/Response.java b/src/main/java/com/daxiang/model/Response.java index 88e219b..393baf3 100644 --- a/src/main/java/com/daxiang/model/Response.java +++ b/src/main/java/com/daxiang/model/Response.java @@ -21,8 +21,8 @@ public class Response { private String msg; private T data; - private static Response buildResponse(Integer status, String msg, T data) { - Response response = new Response(); + private static Response createResponse(Integer status, String msg, T data) { + Response response = new Response<>(); response.setStatus(status); response.setMsg(msg); response.setData(data); @@ -32,39 +32,39 @@ private static Response buildResponse(Integer status, String msg, T data) @JsonIgnore @JSONField(serialize = false) public boolean isSuccess() { - return status == SUCCESS; + return SUCCESS.equals(status); } public static Response success() { - return buildResponse(SUCCESS, "success", null); + return createResponse(SUCCESS, "success", null); } public static Response success(T data) { - return buildResponse(SUCCESS, "success", data); + return createResponse(SUCCESS, "success", data); } public static Response success(String msg) { - return buildResponse(SUCCESS, msg, null); + return createResponse(SUCCESS, msg, null); } public static Response success(String msg, T data) { - return buildResponse(SUCCESS, msg, data); + return createResponse(SUCCESS, msg, data); } public static Response fail(String msg) { - return buildResponse(FAIL, msg, null); + return createResponse(FAIL, msg, null); } public static Response error(String msg) { - return buildResponse(ERROR, msg, null); + return createResponse(ERROR, msg, null); } public static Response unauthorized() { - return buildResponse(UNAUTHORIZED, "认证失败", null); + return createResponse(UNAUTHORIZED, "认证失败", null); } public static Response accessDenied() { - return buildResponse(ACCESSDENIED, "权限不足", null); + return createResponse(ACCESSDENIED, "权限不足", null); } } diff --git a/src/main/java/com/daxiang/model/action/ParamValue.java b/src/main/java/com/daxiang/model/action/ParamValue.java deleted file mode 100644 index e2de879..0000000 --- a/src/main/java/com/daxiang/model/action/ParamValue.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.daxiang.model.action; - -import lombok.Data; - -/** - * Created by jiangyitao. - * 步骤传入的参数值 - */ -@Deprecated -// todo 后续删除 -@Data -public class ParamValue { - /** - * 参数名 - */ - private String paramName; - /** - * 参数类型 - */ - private String paramType; - /** - * 参数值 - */ - private String paramValue; -} diff --git a/src/main/java/com/daxiang/model/action/Step.java b/src/main/java/com/daxiang/model/action/Step.java index 981ee80..38f3c05 100644 --- a/src/main/java/com/daxiang/model/action/Step.java +++ b/src/main/java/com/daxiang/model/action/Step.java @@ -1,10 +1,8 @@ package com.daxiang.model.action; -import com.alibaba.fastjson.annotation.JSONField; import com.daxiang.mbg.po.Action; import com.daxiang.validator.group.SaveActionGroup; import com.fasterxml.jackson.annotation.JsonFormat; -import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.Data; import org.springframework.format.annotation.DateTimeFormat; @@ -57,12 +55,6 @@ public class Step { * 调用action传入的值 */ private List args; - @Deprecated - // todo 后续删除 - @JsonIgnore - @JSONField(serialize = false) - private List paramValues; - @NotNull(message = "步骤status不能为空") private Integer status; } diff --git a/src/main/java/com/daxiang/schedule/ScheduledTaskExecutor.java b/src/main/java/com/daxiang/schedule/ScheduledTaskExecutor.java index 5347fc5..a8ce96c 100644 --- a/src/main/java/com/daxiang/schedule/ScheduledTaskExecutor.java +++ b/src/main/java/com/daxiang/schedule/ScheduledTaskExecutor.java @@ -9,6 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import java.util.Comparator; @@ -32,7 +33,8 @@ public class ScheduledTaskExecutor { /** * 统计已完成的测试任务 */ - @Scheduled(fixedRate = 15000) + @Transactional + @Scheduled(fixedRate = 10000) public void statisticsFinishedTestTask() { // 未完成的测试任务 List testTasks = testTaskService.getUnFinishedTestTasks(); diff --git a/src/main/java/com/daxiang/service/ActionService.java b/src/main/java/com/daxiang/service/ActionService.java index 925d536..942cf92 100644 --- a/src/main/java/com/daxiang/service/ActionService.java +++ b/src/main/java/com/daxiang/service/ActionService.java @@ -2,11 +2,11 @@ import com.alibaba.fastjson.JSONObject; import com.daxiang.agent.AgentClient; -import com.daxiang.exception.BusinessException; +import com.daxiang.exception.ServerException; import com.daxiang.mbg.mapper.ActionMapper; import com.daxiang.mbg.po.*; -import com.daxiang.model.Page; import com.daxiang.model.PageRequest; +import com.daxiang.model.PagedData; import com.daxiang.model.Response; import com.daxiang.model.action.Step; import com.daxiang.model.request.ActionDebugRequest; @@ -14,7 +14,9 @@ import com.daxiang.model.vo.ActionVo; import com.daxiang.security.SecurityUtil; import com.github.pagehelper.PageHelper; +import com.github.pagehelper.Page; import com.daxiang.dao.ActionDao; +import com.google.common.collect.ImmutableMap; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; @@ -36,6 +38,12 @@ @Slf4j public class ActionService { + private static final Map ACTION_TYPE_MAP = ImmutableMap.of( + Action.TYPE_BASE, "基础Action", + Action.TYPE_ENCAPSULATION, "Action", + Action.TYPE_TESTCASE, "测试用例" + ); + @Autowired private ActionMapper actionMapper; @Autowired @@ -58,23 +66,24 @@ public class ActionService { @Autowired private UserService userService; - public Response add(Action action) { - action.setCreatorUid(SecurityUtil.getCurrentUserId()); + public void add(Action action) { action.setCreateTime(new Date()); + action.setCreatorUid(SecurityUtil.getCurrentUserId()); - int insertRow; try { - insertRow = actionMapper.insertSelective(action); + int insertCount = actionMapper.insertSelective(action); + if (insertCount != 1) { + throw new ServerException("添加失败,请稍后重试"); + } } catch (DuplicateKeyException e) { - return Response.fail("命名冲突"); + throw new ServerException(action.getName() + "已存在"); } - return insertRow == 1 ? Response.success("添加action成功") : Response.fail("添加action失败,请稍后重试"); } @Transactional - public Response resetBasicAction(List actions) { + public void resetBasicAction(List actions) { if (CollectionUtils.isEmpty(actions)) { - return Response.success(); + return; } // 删除基础action @@ -83,58 +92,49 @@ public Response resetBasicAction(List actions) { actionMapper.deleteByExample(example); actionDao.insertBasicActions(actions); - - return Response.success(); } - public Response delete(Integer actionId) { - if (actionId == null) { - return Response.fail("actionId不能为空"); - } - + public void delete(Integer actionId) { checkAction(actionId); - int deleteRow = actionMapper.deleteByPrimaryKey(actionId); - return deleteRow == 1 ? Response.success("删除成功") : Response.fail("删除失败,请稍后重试"); + int deleteCount = actionMapper.deleteByPrimaryKey(actionId); + if (deleteCount != 1) { + throw new ServerException("删除失败,请稍后重试"); + } } - public Response update(Action action) { + public void update(Action action) { checkStepsNotContainsSelf(action); checkActionImportsNotContainsSelf(action); checkDepensNotContainsSelf(action); // action状态变为草稿或禁用 - if (action.getState() == Action.DRAFT_STATE || action.getState() == Action.DISABLE_STATE) { + if (action.getState() != Action.RELEASE_STATE) { checkAction(action.getId()); } action.setUpdateTime(new Date()); action.setUpdatorUid(SecurityUtil.getCurrentUserId()); - int updateRow; try { - updateRow = actionMapper.updateByPrimaryKeyWithBLOBs(action); + int updateCount = actionMapper.updateByPrimaryKeyWithBLOBs(action); + if (updateCount != 1) { + throw new ServerException("更新失败,请稍后重试"); + } } catch (DuplicateKeyException e) { - return Response.fail("命名冲突"); + throw new ServerException(action.getName() + "已存在"); } - return updateRow == 1 ? Response.success("更新Action成功") : Response.fail("更新Action失败,请稍后重试"); } - public Response list(Action action, PageRequest pageRequest) { - boolean needPaging = pageRequest.needPaging(); - if (needPaging) { - PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); - } - - List actions = selectByAction(action); - List actionVos = convertActionsToActionVos(actions); + public PagedData list(Action query, String orderBy, PageRequest pageRequest) { + Page page = PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); - if (needPaging) { - long total = Page.getTotal(actions); - return Response.success(Page.build(actionVos, total)); - } else { - return Response.success(actionVos); + if (StringUtils.isEmpty(orderBy)) { + orderBy = "create_time desc"; } + + List actionVos = getActionVos(query, orderBy); + return new PagedData<>(actionVos, page.getTotal()); } private List convertActionsToActionVos(List actions) { @@ -149,7 +149,7 @@ private List convertActionsToActionVos(List actions) { .collect(Collectors.toList()); Map userMap = userService.getUserMapByIds(creatorAndUpdatorUids); - return actions.stream().map(action -> { + List actionVos = actions.stream().map(action -> { ActionVo actionVo = new ActionVo(); BeanUtils.copyProperties(action, actionVo); @@ -169,43 +169,57 @@ private List convertActionsToActionVos(List actions) { return actionVo; }).collect(Collectors.toList()); + + return actionVos; + } + + public List getActionVos(Action query, String orderBy) { + List actions = getActions(query, orderBy); + return convertActionsToActionVos(actions); + } + + public List getActions(Action query) { + return getActions(query, null); } - private List selectByAction(Action action) { + public List getActions(Action query, String orderBy) { ActionExample example = new ActionExample(); ActionExample.Criteria criteria = example.createCriteria(); - if (action != null) { - if (action.getId() != null) { - criteria.andIdEqualTo(action.getId()); + if (query != null) { + if (query.getId() != null) { + criteria.andIdEqualTo(query.getId()); } - if (!StringUtils.isEmpty(action.getName())) { - criteria.andNameLike("%" + action.getName() + "%"); + if (!StringUtils.isEmpty(query.getName())) { + criteria.andNameLike("%" + query.getName() + "%"); } - if (action.getProjectId() != null) { - criteria.andProjectIdEqualTo(action.getProjectId()); + if (query.getProjectId() != null) { + criteria.andProjectIdEqualTo(query.getProjectId()); } - if (action.getType() != null) { - criteria.andTypeEqualTo(action.getType()); + if (query.getType() != null) { + criteria.andTypeEqualTo(query.getType()); } - if (action.getPageId() != null) { - criteria.andPageIdEqualTo(action.getPageId()); + if (query.getPageId() != null) { + criteria.andPageIdEqualTo(query.getPageId()); } - if (action.getCategoryId() != null) { - criteria.andCategoryIdEqualTo(action.getCategoryId()); + if (query.getCategoryId() != null) { + criteria.andCategoryIdEqualTo(query.getCategoryId()); } - if (action.getState() != null) { - criteria.andStateEqualTo(action.getState()); + if (query.getState() != null) { + criteria.andStateEqualTo(query.getState()); } } - example.setOrderByClause("create_time desc"); + + if (!StringUtils.isEmpty(orderBy)) { + example.setOrderByClause(orderBy); + } return actionMapper.selectByExampleWithBLOBs(example); } - public Response cascader(Integer projectId, Integer platform, Integer type) { + public List cascader(Integer projectId, Integer platform, Integer type) { if (projectId == null || platform == null) { - return Response.fail("projectId || platform不能为空"); + throw new ServerException("projectId or platform不能为空"); } List tree = new ArrayList<>(); @@ -213,7 +227,7 @@ public Response cascader(Integer projectId, Integer platform, Integer type) { // type可以为空 List actions = actionDao.selectPublishedCascaderData(projectId, platform, type); if (CollectionUtils.isEmpty(actions)) { - return Response.success(tree); + return tree; } List categories = categoryService.getCategoriesWithProjectIdIsNullOrProjectIdEqualsTo(projectId); @@ -231,7 +245,7 @@ public Response cascader(Integer projectId, Integer platform, Integer type) { ActionTreeNode root = rMap.get(actionType); if (root == null) { root = new ActionTreeNode(); - root.setName(getActionTypeName(actionType)); + root.setName(ACTION_TYPE_MAP.get(actionType)); root.setChildren(new ArrayList<>()); rMap.put(actionType, root); tree.add(root); @@ -277,35 +291,21 @@ public Response cascader(Integer projectId, Integer platform, Integer type) { } } - return Response.success(tree); - } - - private String getActionTypeName(Integer actionType) { - switch (actionType) { - case Action.TYPE_BASE: - return "基础Action"; - case Action.TYPE_ENCAPSULATION: - return "Action"; - case Action.TYPE_TESTCASE: - return "测试用例"; - default: - throw new BusinessException("unknow action type: " + actionType); - } + return tree; } public Response debug(ActionDebugRequest actionDebugRequest) { Action action = actionDebugRequest.getAction(); - action.setId(0); - action.setDepends(new ArrayList<>()); - boolean anyEnabledStep = action.getSteps().stream() .anyMatch(step -> step.getStatus() == Step.ENABLE_STATUS); if (!anyEnabledStep) { return Response.fail("至少选择一个启用的步骤"); } - ActionDebugRequest.DebugInfo debugInfo = actionDebugRequest.getDebugInfo(); + action.setId(0); + action.setDepends(new ArrayList<>()); + ActionDebugRequest.DebugInfo debugInfo = actionDebugRequest.getDebugInfo(); Integer projectId = action.getProjectId(); Integer env = debugInfo.getEnv(); @@ -327,8 +327,8 @@ public Response debug(ActionDebugRequest actionDebugRequest) { return agentClient.debugAction(debugInfo.getAgentIp(), debugInfo.getAgentPort(), requestBody); } - public Action getActionById(Integer actioniId) { - return actionMapper.selectByPrimaryKey(actioniId); + public Action getActionById(Integer actionId) { + return actionMapper.selectByPrimaryKey(actionId); } public List getActionsByIds(List actionIds) { @@ -351,7 +351,7 @@ public List getActionsByIds(List actionIds) { private void checkDepensNotContainsSelf(Action action) { List depends = action.getDepends(); if (!CollectionUtils.isEmpty(depends) && depends.contains(action.getId())) { - throw new BusinessException("依赖用例不能包含自身"); + throw new ServerException("依赖用例不能包含自身"); } } @@ -364,7 +364,7 @@ private void checkStepsNotContainsSelf(Action action) { List stepActionIds = action.getSteps().stream() .map(Step::getActionId).collect(Collectors.toList()); if (stepActionIds.contains(action.getId())) { - throw new BusinessException("步骤不能包含自身"); + throw new ServerException("步骤不能包含自身"); } } @@ -376,7 +376,7 @@ private void checkStepsNotContainsSelf(Action action) { private void checkActionImportsNotContainsSelf(Action action) { List actionImports = action.getActionImports(); if (!CollectionUtils.isEmpty(actionImports) && actionImports.contains(action.getId())) { - throw new BusinessException("导入Action不能包含自身"); + throw new ServerException("导入Action不能包含自身"); } } @@ -386,31 +386,35 @@ private void checkActionImportsNotContainsSelf(Action action) { * @param actionId */ private void checkAction(Integer actionId) { + if (actionId == null) { + throw new ServerException("actionId不能为空"); + } + // 检查action是否被steps或depends或actionImports使用 List actions = actionDao.selectByActionIdInStepsOrDependsOrActionImports(actionId); if (!CollectionUtils.isEmpty(actions)) { String actionNames = actions.stream().map(Action::getName).collect(Collectors.joining("、")); - throw new BusinessException("actions: " + actionNames + ", 正在使用此action"); + throw new ServerException("actions: " + actionNames + ", 正在使用此action"); } // 检查action是否被testplan使用 List testPlans = testPlanService.getTestPlansByActionId(actionId); if (!CollectionUtils.isEmpty(testPlans)) { String testPlanNames = testPlans.stream().map(TestPlan::getName).collect(Collectors.joining("、")); - throw new BusinessException("testPlans: " + testPlanNames + ", 正在使用此action"); + throw new ServerException("testPlans: " + testPlanNames + ", 正在使用此action"); } // 检查action是否被testSuite使用 List testSuites = testSuiteService.getTestSuitesByActionId(actionId); if (!CollectionUtils.isEmpty(testSuites)) { String testSuiteNames = testSuites.stream().map(TestSuite::getName).collect(Collectors.joining("、")); - throw new BusinessException("testSuites: " + testSuiteNames + ", 正在使用此action"); + throw new ServerException("testSuites: " + testSuiteNames + ", 正在使用此action"); } } public List getActionsByLocalVarsEnvironmentId(Integer envId) { if (envId == null) { - return new ArrayList<>(); + throw new ServerException("envId不能为空"); } return actionDao.selectByLocalVarsEnvironmentId(envId); } @@ -429,12 +433,12 @@ public List getActionsByCategoryIds(List categoryIds) { public List getActionsByPageId(Integer pageId) { if (pageId == null) { - return new ArrayList<>(); + throw new ServerException("pageId不能为空"); } Action query = new Action(); query.setPageId(pageId); - return selectByAction(query); + return getActions(query); } } diff --git a/src/main/java/com/daxiang/service/AgentService.java b/src/main/java/com/daxiang/service/AgentService.java index fd87621..3923250 100644 --- a/src/main/java/com/daxiang/service/AgentService.java +++ b/src/main/java/com/daxiang/service/AgentService.java @@ -1,9 +1,9 @@ package com.daxiang.service; import com.alibaba.fastjson.JSONObject; +import com.daxiang.exception.ServerException; import com.daxiang.mbg.po.Browser; import com.daxiang.mbg.po.Mobile; -import com.daxiang.model.Response; import com.daxiang.model.vo.AgentVo; import de.codecentric.boot.admin.server.domain.entities.Instance; import de.codecentric.boot.admin.server.domain.values.Endpoint; @@ -37,7 +37,7 @@ public class AgentService { @Autowired private RestTemplate restTemplate; - public Response getOnlineAgents() { + public List getOnlineAgents() { List agentVos = getOnlineAgentsWithoutDevices(); List agentIps = agentVos.stream().map(AgentVo::getIp).collect(Collectors.toList()); @@ -53,7 +53,7 @@ public Response getOnlineAgents() { agentVo.setBrowsers(browserMap.get(ip)); }); - return Response.success(agentVos); + return agentVos; } public List getOnlineAgentsWithoutDevices() { @@ -68,7 +68,7 @@ private AgentVo createAgentVoWithoutDevices(Instance agent) { try { uri = new URI(agent.getRegistration().getServiceUrl()); } catch (URISyntaxException e) { - throw new RuntimeException(e); + throw new ServerException(e); } AgentVo agentVo = new AgentVo(); diff --git a/src/main/java/com/daxiang/service/AppService.java b/src/main/java/com/daxiang/service/AppService.java index 8943b5f..0b94905 100644 --- a/src/main/java/com/daxiang/service/AppService.java +++ b/src/main/java/com/daxiang/service/AppService.java @@ -1,6 +1,7 @@ package com.daxiang.service; import com.daxiang.agent.AgentClient; +import com.daxiang.exception.ServerException; import com.daxiang.mbg.mapper.AppMapper; import com.daxiang.mbg.po.App; import com.daxiang.mbg.po.AppExample; @@ -10,6 +11,7 @@ import com.daxiang.model.vo.AppVo; import com.daxiang.security.SecurityUtil; import com.daxiang.utils.HttpServletUtil; +import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; @@ -40,44 +42,46 @@ public class AppService { @Autowired private UserService userService; - public Response upload(App app, MultipartFile file) { - Response response = uploadService.uploadFile(file, FileType.APP); - if (!response.isSuccess()) { - return response; - } + public void upload(App app, MultipartFile file) { + UploadFile uploadFile = uploadService.upload(file, FileType.APP); - app.setFilePath(response.getData().getFilePath()); + app.setFilePath(uploadFile.getFilePath()); app.setUploadTime(new Date()); app.setUploadorUid(SecurityUtil.getCurrentUserId()); - int insertRow = appMapper.insertSelective(app); - return insertRow == 1 ? Response.success("上传成功") : Response.fail("上传失败"); + int insertCount = appMapper.insertSelective(app); + if (insertCount != 1) { + throw new ServerException("上传失败"); + } } - public Response delete(Integer appId) { + public void delete(Integer appId) { if (appId == null) { - return Response.fail("appId不能为空"); + throw new ServerException("appId不能为空"); } - int delRow = appMapper.deleteByPrimaryKey(appId); - return delRow == 1 ? Response.success("删除成功") : Response.fail("删除失败,请稍后再试"); + int deleteCount = appMapper.deleteByPrimaryKey(appId); + if (deleteCount != 1) { + throw new ServerException("删除失败,请稍后再试"); + } } - public Response list(App app, PageRequest pageRequest) { - boolean needPaging = pageRequest.needPaging(); - if (needPaging) { - PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); + public void update(App app) { + int updateCount = appMapper.updateByPrimaryKey(app); + if (updateCount != 1) { + throw new ServerException("更新失败,请稍后重试"); } + } - List apps = selectByApp(app); - List appVos = convertAppsToAppVos(apps); + public PagedData list(App query, String orderBy, PageRequest pageRequest) { + Page page = PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); - if (needPaging) { - long total = Page.getTotal(apps); - return Response.success(Page.build(appVos, total)); - } else { - return Response.success(appVos); + if (StringUtils.isEmpty(orderBy)) { + orderBy = "upload_time desc"; } + + List appVos = getAppVos(query, orderBy); + return new PagedData<>(appVos, page.getTotal()); } private List convertAppsToAppVos(List apps) { @@ -92,7 +96,7 @@ private List convertAppsToAppVos(List apps) { .collect(Collectors.toList()); Map userMap = userService.getUserMapByIds(uploadorUids); - return apps.stream().map(app -> { + List appVos = apps.stream().map(app -> { AppVo appVo = new AppVo(); BeanUtils.copyProperties(app, appVo); @@ -105,64 +109,74 @@ private List convertAppsToAppVos(List apps) { return appVo; }).collect(Collectors.toList()); + + return appVos; } - private List selectByApp(App app) { + public List getAppVos(App query, String orderBy) { + List apps = getApps(query, orderBy); + return convertAppsToAppVos(apps); + } + + public List getApps(App query, String orderBy) { AppExample example = new AppExample(); AppExample.Criteria criteria = example.createCriteria(); - if (app != null) { - if (app.getId() != null) { - criteria.andIdEqualTo(app.getId()); + if (query != null) { + if (query.getId() != null) { + criteria.andIdEqualTo(query.getId()); } - if (app.getPlatform() != null) { - criteria.andPlatformEqualTo(app.getPlatform()); + if (query.getPlatform() != null) { + criteria.andPlatformEqualTo(query.getPlatform()); } - if (app.getProjectId() != null) { - criteria.andProjectIdEqualTo(app.getProjectId()); + if (query.getProjectId() != null) { + criteria.andProjectIdEqualTo(query.getProjectId()); } } - example.setOrderByClause("upload_time desc"); + + if (!StringUtils.isEmpty(orderBy)) { + example.setOrderByClause(orderBy); + } return appMapper.selectByExample(example); } - public Response aaptDumpBadging(Integer appId) { + public void aaptDumpBadging(Integer appId) { if (appId == null) { - return Response.fail("appId不能为空"); + throw new ServerException("appId不能为空"); } App app = appMapper.selectByPrimaryKey(appId); if (app == null) { - return Response.fail("app不存在"); + throw new ServerException("app不存在"); } if (app.getPlatform() != Platform.ANDROID) { - return Response.fail("只有Android平台才能执行aapt dump"); + throw new ServerException("只有Android平台才能执行aapt dump"); } List onlineAgents = agentService.getOnlineAgentsWithoutDevices(); if (CollectionUtils.isEmpty(onlineAgents)) { - return Response.fail("暂无在线的agent,无法执行aapt dump"); + throw new ServerException("暂无在线的agent,无法执行aapt dump"); } Optional agentVo = onlineAgents.stream().filter(AgentVo::getIsConfigAapt).findAny(); if (!agentVo.isPresent()) { - return Response.fail("暂无配置了aapt的agent,无法执行aapt dump"); + throw new ServerException("暂无配置了aapt的agent,无法执行aapt dump"); } AgentVo agent = agentVo.get(); Response agentResponse = agentClient.aaptDumpBadging(agent.getIp(), agent.getPort(), HttpServletUtil.getStaticResourceUrl(app.getFilePath())); if (!agentResponse.isSuccess()) { - return agentResponse; + throw new ServerException(agentResponse.getMsg()); } String dumpInfo = (String) agentResponse.getData(); if (StringUtils.isEmpty(dumpInfo)) { - return Response.fail("aapt dump信息为空"); + throw new ServerException("aapt dump信息为空"); } - log.info("app: {} => {}", app.getName(), dumpInfo); + log.info("app: {}, dumpInfo: {}", app.getName(), dumpInfo); String version = org.apache.commons.lang3.StringUtils.substringBetween(dumpInfo, "versionName='", "'"); String packageName = org.apache.commons.lang3.StringUtils.substringBetween(dumpInfo, "package: name='", "'"); @@ -172,12 +186,10 @@ public Response aaptDumpBadging(Integer appId) { app.setPackageName(packageName); app.setLaunchActivity(launchActivity); - int updateRow = appMapper.updateByPrimaryKeySelective(app); - return updateRow == 1 ? Response.success("获取成功") : Response.fail("获取失败,请稍后重试"); + int updateCount = appMapper.updateByPrimaryKeySelective(app); + if (updateCount != 1) { + throw new ServerException("更新失败,请稍后重试"); + } } - public Response update(App app) { - int updateRow = appMapper.updateByPrimaryKey(app); - return updateRow == 1 ? Response.success("更新成功") : Response.fail("更新失败,请稍后重试"); - } } diff --git a/src/main/java/com/daxiang/service/BrowserService.java b/src/main/java/com/daxiang/service/BrowserService.java index ec77219..a89fa95 100644 --- a/src/main/java/com/daxiang/service/BrowserService.java +++ b/src/main/java/com/daxiang/service/BrowserService.java @@ -1,12 +1,13 @@ package com.daxiang.service; import com.daxiang.agent.AgentClient; +import com.daxiang.exception.ServerException; import com.daxiang.mbg.mapper.BrowserMapper; import com.daxiang.mbg.po.Browser; import com.daxiang.mbg.po.BrowserExample; -import com.daxiang.model.Page; +import com.daxiang.model.PagedData; import com.daxiang.model.PageRequest; -import com.daxiang.model.Response; +import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; @@ -15,6 +16,7 @@ import org.springframework.util.StringUtils; import java.util.*; +import java.util.function.Function; import java.util.stream.Collectors; @@ -30,73 +32,73 @@ public class BrowserService { @Autowired private AgentClient agentClient; - public Response save(Browser browser) { + public void save(Browser browser) { Browser dbBrowser = browserMapper.selectByPrimaryKey(browser.getId()); - int saveRow; + int saveCount; if (dbBrowser == null) { browser.setCreateTime(new Date()); - saveRow = browserMapper.insertSelective(browser); + saveCount = browserMapper.insertSelective(browser); } else { - saveRow = browserMapper.updateByPrimaryKeySelective(browser); + saveCount = browserMapper.updateByPrimaryKeySelective(browser); } - return saveRow == 1 ? Response.success("保存成功") : Response.fail("保存失败"); - } - - public Response list(Browser browser, PageRequest pageRequest) { - boolean needPaging = pageRequest.needPaging(); - if (needPaging) { - PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); + if (saveCount != 1) { + throw new ServerException("保存失败,请稍后重试"); } + } - List browsers = selectByBrowser(browser); + public PagedData list(Browser query, String orderBy, PageRequest pageRequest) { + Page page = PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); - if (needPaging) { - long total = Page.getTotal(browsers); - return Response.success(Page.build(browsers, total)); - } else { - return Response.success(browsers); + if (StringUtils.isEmpty(orderBy)) { + orderBy = "status desc,create_time desc"; } + + List browsers = getBrowsers(query, orderBy); + return new PagedData<>(browsers, page.getTotal()); } - private List selectByBrowser(Browser browser) { + public List getBrowsers(Browser query, String orderBy) { BrowserExample example = new BrowserExample(); BrowserExample.Criteria criteria = example.createCriteria(); - if (browser != null) { - if (!StringUtils.isEmpty(browser.getId())) { - criteria.andIdEqualTo(browser.getId()); + if (query != null) { + if (!StringUtils.isEmpty(query.getId())) { + criteria.andIdEqualTo(query.getId()); } - if (!StringUtils.isEmpty(browser.getType())) { - criteria.andTypeEqualTo(browser.getType()); + if (!StringUtils.isEmpty(query.getType())) { + criteria.andTypeEqualTo(query.getType()); } - if (!StringUtils.isEmpty(browser.getVersion())) { - criteria.andVersionEqualTo(browser.getVersion()); + if (!StringUtils.isEmpty(query.getVersion())) { + criteria.andVersionEqualTo(query.getVersion()); } - if (browser.getPlatform() != null) { - criteria.andPlatformEqualTo(browser.getPlatform()); + if (query.getPlatform() != null) { + criteria.andPlatformEqualTo(query.getPlatform()); } - if (!StringUtils.isEmpty(browser.getAgentIp())) { - criteria.andAgentIpEqualTo(browser.getAgentIp()); + if (!StringUtils.isEmpty(query.getAgentIp())) { + criteria.andAgentIpEqualTo(query.getAgentIp()); } - if (browser.getStatus() != null) { - criteria.andStatusEqualTo(browser.getStatus()); + if (query.getStatus() != null) { + criteria.andStatusEqualTo(query.getStatus()); } } - example.setOrderByClause("status desc,create_time desc"); + + if (!StringUtils.isEmpty(orderBy)) { + example.setOrderByClause(orderBy); + } return browserMapper.selectByExample(example); } - public Response start(String browserId) { + public Browser start(String browserId) { if (StringUtils.isEmpty(browserId)) { - return Response.fail("浏览器id不能为空"); + throw new ServerException("浏览器id不能为空"); } Browser dbBrowser = browserMapper.selectByPrimaryKey(browserId); if (dbBrowser == null) { - return Response.fail("浏览器不存在"); + throw new ServerException("浏览器不存在"); } // 有时server被强制关闭,导致数据库浏览器状态与实际不一致 @@ -113,24 +115,24 @@ public Response start(String browserId) { dbBrowser.setStatus(Browser.OFFLINE_STATUS); browserMapper.updateByPrimaryKeySelective(dbBrowser); } - return Response.fail("浏览器不在线"); + throw new ServerException("浏览器不在线"); } else { if (agentBrowser.getStatus() == Browser.IDLE_STATUS) { - return Response.success(agentBrowser); + return agentBrowser; } else { // 同步最新状态 browserMapper.updateByPrimaryKeySelective(agentBrowser); - return Response.fail("浏览器未闲置"); + throw new ServerException("浏览器未闲置"); } } } - public Response getOnlineBrowsers() { + public List getOnlineBrowsers() { BrowserExample example = new BrowserExample(); BrowserExample.Criteria criteria = example.createCriteria(); criteria.andStatusNotEqualTo(Browser.OFFLINE_STATUS); - return Response.success(browserMapper.selectByExample(example)); + return browserMapper.selectByExample(example); } public List getOnlineBrowsersByAgentIps(List agentIps) { @@ -156,7 +158,7 @@ public void agentOffline(String agentIp) { browserMapper.updateByExampleSelective(browser, example); } - private List getBrowsersByIds(Set browserIds) { + public List getBrowsersByIds(Set browserIds) { if (CollectionUtils.isEmpty(browserIds)) { return new ArrayList<>(); } @@ -169,6 +171,6 @@ private List getBrowsersByIds(Set browserIds) { public Map getBrowserMapByBrowserIds(Set browserIds) { List browsers = getBrowsersByIds(browserIds); - return browsers.stream().collect(Collectors.toMap(Browser::getId, b -> b, (k1, k2) -> k1)); + return browsers.stream().collect(Collectors.toMap(Browser::getId, Function.identity(), (k1, k2) -> k1)); } } diff --git a/src/main/java/com/daxiang/service/CategoryService.java b/src/main/java/com/daxiang/service/CategoryService.java index 5155fee..f353863 100644 --- a/src/main/java/com/daxiang/service/CategoryService.java +++ b/src/main/java/com/daxiang/service/CategoryService.java @@ -1,15 +1,16 @@ package com.daxiang.service; -import com.daxiang.exception.BusinessException; +import com.daxiang.exception.ServerException; import com.daxiang.mbg.mapper.CategoryMapper; import com.daxiang.mbg.po.*; import com.daxiang.model.PageRequest; -import com.daxiang.model.Response; +import com.daxiang.model.PagedData; import com.daxiang.model.dto.CategoryTreeNode; import com.daxiang.model.vo.CategoryVo; import com.daxiang.security.SecurityUtil; import com.daxiang.utils.Tree; import com.github.pagehelper.PageHelper; +import com.github.pagehelper.Page; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DuplicateKeyException; @@ -19,6 +20,7 @@ import org.springframework.util.StringUtils; import java.util.*; +import java.util.function.Function; import java.util.stream.Collectors; /** @@ -38,113 +40,99 @@ public class CategoryService { @Autowired private UserService userService; - public Response add(Category category) { + public void add(Category category) { category.setCreateTime(new Date()); category.setCreatorUid(SecurityUtil.getCurrentUserId()); - int insertRow; try { - insertRow = categoryMapper.insertSelective(category); + int insertCount = categoryMapper.insertSelective(category); + if (insertCount != 1) { + throw new ServerException("添加失败,请稍后重试"); + } } catch (DuplicateKeyException e) { - return Response.fail("命名冲突"); + throw new ServerException(category.getName() + "已存在"); } - return insertRow == 1 ? Response.success("添加Category成功") : Response.fail("添加Category失败"); } @Transactional - public Response delete(Integer categoryId, Integer type, Integer projectId) { + public void delete(Integer categoryId, Integer type, Integer projectId) { if (categoryId == null || type == null || projectId == null) { - return Response.fail("categoryId || type || projectId 不能为空"); + throw new ServerException("categoryId or type or projectId不能为空"); } Set categoryIds = getDescendantIds(categoryId, type, projectId); // 后代 - categoryIds.add(categoryId); + categoryIds.add(categoryId); // 后代和自己 List cids = new ArrayList<>(categoryIds); switch (type) { case Category.TYPE_PAGE: - List pages = pageService.getPagesWithoutWindowHierarchyByCategoryIds(cids); + List pages = pageService.getPagesWithoutWindowHierarchyByCategoryIds(cids); if (!CollectionUtils.isEmpty(pages)) { - return Response.fail("分类下有page,无法删除"); + throw new ServerException("分类下有page,无法删除"); } break; case Category.TYPE_ACTION: { List actions = actionService.getActionsByCategoryIds(cids); if (!CollectionUtils.isEmpty(actions)) { - return Response.fail("分类下有action,无法删除"); + throw new ServerException("分类下有action,无法删除"); } break; } case Category.TYPE_TESTCASE: { List actions = actionService.getActionsByCategoryIds(cids); if (!CollectionUtils.isEmpty(actions)) { - return Response.fail("分类下有测试用例,无法删除"); + throw new ServerException("分类下有测试用例,无法删除"); } break; } case Category.TYPE_GLOBAL_VAR: List globalVars = globalVarService.getGlobalVarsByCategoryIds(cids); if (!CollectionUtils.isEmpty(globalVars)) { - return Response.fail("分类下有全局变量,无法删除"); + throw new ServerException("分类下有全局变量,无法删除"); } break; default: - return Response.fail("不支持的category type"); + throw new ServerException("不支持的category type"); } CategoryExample example = new CategoryExample(); CategoryExample.Criteria criteria = example.createCriteria(); criteria.andIdIn(cids); - int deleteRow = categoryMapper.deleteByExample(example); - if (deleteRow == categoryIds.size()) { - return Response.success("删除成功"); - } else { - throw new BusinessException("删除失败,请稍后重试"); + int deleteCount = categoryMapper.deleteByExample(example); + if (deleteCount != cids.size()) { + throw new ServerException("删除失败,请稍后重试"); } } - public Response update(Category category) { - int updateRow; + public void update(Category category) { try { - updateRow = categoryMapper.updateByPrimaryKeySelective(category); + int updateCount = categoryMapper.updateByPrimaryKeySelective(category); + if (updateCount != 1) { + throw new ServerException("更新失败,请稍后重试"); + } } catch (DuplicateKeyException e) { - return Response.fail("命名冲突"); + throw new ServerException(category.getName() + "已存在"); } - return updateRow == 1 ? Response.success("保存成功") : Response.fail("保存失败,请稍后重试"); } - public Response list(Category category, PageRequest pageRequest) { - boolean needPaging = pageRequest.needPaging(); - if (needPaging) { - PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); - } - - List categories = selectByCategory(category); - List categoryVos = convertCategoriesToCategoryVos(categories); + public PagedData list(Category query, String orderBy, PageRequest pageRequest) { + Page page = PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); - if (needPaging) { - long total = com.daxiang.model.Page.getTotal(categories); - return Response.success(com.daxiang.model.Page.build(categoryVos, total)); - } else { - return Response.success(categoryVos); - } + List categoryVos = getCategoryVos(query, orderBy); + return new PagedData<>(categoryVos, page.getTotal()); } - public Response getCategoryTreeByProjectIdAndType(Integer projectId, Integer type) { + public List getCategoryTreeByProjectIdAndType(Integer projectId, Integer type) { if (projectId == null || type == null) { - return Response.fail("projectId或type不能为空"); + throw new ServerException("projectId or type不能为空"); } Category query = new Category(); query.setProjectId(projectId); query.setType(type); - List categories = selectByCategory(query); - - return Response.success(buildCategoryTree(categories)); - } + List categories = getCategories(query); - private List buildCategoryTree(List categories) { List categroyTreeNodes = categories.stream() .map(CategoryTreeNode::create).collect(Collectors.toList()); @@ -163,7 +151,7 @@ private List convertCategoriesToCategoryVos(List categorie .collect(Collectors.toList()); Map userMap = userService.getUserMapByIds(creatorUids); - return categories.stream().map(category -> { + List categoryVos = categories.stream().map(category -> { CategoryVo categoryVo = new CategoryVo(); BeanUtils.copyProperties(category, categoryVo); @@ -176,36 +164,51 @@ private List convertCategoriesToCategoryVos(List categorie return categoryVo; }).collect(Collectors.toList()); + + return categoryVos; } - private List selectByCategory(Category category) { + public List getCategoryVos(Category query, String orderBy) { + List categories = getCategories(query, orderBy); + return convertCategoriesToCategoryVos(categories); + } + + public List getCategories(Category query) { + return getCategories(query, null); + } + + public List getCategories(Category query, String orderBy) { CategoryExample example = new CategoryExample(); CategoryExample.Criteria criteria = example.createCriteria(); - if (category != null) { - if (category.getId() != null) { - criteria.andIdEqualTo(category.getId()); + if (query != null) { + if (query.getId() != null) { + criteria.andIdEqualTo(query.getId()); } - if (category.getParentId() != null) { - criteria.andParentIdEqualTo(category.getParentId()); + if (query.getParentId() != null) { + criteria.andParentIdEqualTo(query.getParentId()); } - if (!StringUtils.isEmpty(category.getName())) { - criteria.andNameEqualTo(category.getName()); + if (!StringUtils.isEmpty(query.getName())) { + criteria.andNameEqualTo(query.getName()); } - if (category.getType() != null) { - criteria.andTypeEqualTo(category.getType()); + if (query.getType() != null) { + criteria.andTypeEqualTo(query.getType()); } - if (category.getProjectId() != null) { - criteria.andProjectIdEqualTo(category.getProjectId()); + if (query.getProjectId() != null) { + criteria.andProjectIdEqualTo(query.getProjectId()); } } + if (!StringUtils.isEmpty(orderBy)) { + example.setOrderByClause(orderBy); + } + return categoryMapper.selectByExample(example); } public List getCategoriesWithProjectIdIsNullOrProjectIdEqualsTo(Integer projectId) { if (projectId == null) { - return new ArrayList<>(); + throw new ServerException("projectId不能为空"); } CategoryExample example = new CategoryExample(); @@ -232,7 +235,7 @@ private Set getDescendantIds(Integer parentId, Integer type, Integer pr Category query = new Category(); query.setProjectId(projectId); query.setType(type); - List categories = selectByCategory(query); + List categories = getCategories(query); Map categoryMap = categoriesToMap(categories); Set descendantIds = new HashSet<>(); @@ -258,7 +261,7 @@ private Set getDescendantIds(Integer parentId, Integer type, Integer pr public Map categoriesToMap(List categories) { return categories.stream() - .collect(Collectors.toMap(Category::getId, c -> c, (k1, k2) -> k1)); + .collect(Collectors.toMap(Category::getId, Function.identity(), (k1, k2) -> k1)); } } diff --git a/src/main/java/com/daxiang/service/DataMigrationService.java b/src/main/java/com/daxiang/service/DataMigrationService.java deleted file mode 100644 index 1d2f1fc..0000000 --- a/src/main/java/com/daxiang/service/DataMigrationService.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.daxiang.service; - -import com.daxiang.mbg.mapper.ActionMapper; -import com.daxiang.model.action.ParamValue; -import com.daxiang.model.action.Step; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.util.CollectionUtils; - -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - -/** - * Created by jiangyitao. - * 数据迁移 - */ -@Service -public class DataMigrationService { - - @Autowired - private ActionMapper actionMapper; - - /** - * todo 后续删除 - * v0.7.5 将step.paramValues -> step.args - */ - public void actionStepParamValuesToArgs() { - actionMapper.selectByExampleWithBLOBs(null).stream() - .filter(action -> !CollectionUtils.isEmpty(action.getSteps())) - .forEach(action -> { - List steps = action.getSteps(); - for (Step step : steps) { - List paramValues = step.getParamValues(); - if (paramValues == null) { // 已迁移过 - return; - } - if (paramValues.isEmpty()) { - step.setArgs(new ArrayList<>()); - } else { - List values = paramValues.stream().map(ParamValue::getParamValue).collect(Collectors.toList()); - step.setArgs(values); - } - } - actionMapper.updateByPrimaryKeySelective(action); - }); - } -} diff --git a/src/main/java/com/daxiang/service/DeviceTestTaskService.java b/src/main/java/com/daxiang/service/DeviceTestTaskService.java index c982d0a..e6fadf8 100644 --- a/src/main/java/com/daxiang/service/DeviceTestTaskService.java +++ b/src/main/java/com/daxiang/service/DeviceTestTaskService.java @@ -1,14 +1,15 @@ package com.daxiang.service; +import com.daxiang.exception.ServerException; import com.daxiang.mbg.mapper.DeviceTestTaskMapper; import com.daxiang.mbg.po.DeviceTestTaskExample; import com.daxiang.model.PageRequest; -import com.daxiang.model.Response; +import com.daxiang.model.PagedData; import com.daxiang.model.action.Step; import com.daxiang.model.dto.Testcase; import com.github.pagehelper.PageHelper; +import com.github.pagehelper.Page; import com.daxiang.mbg.po.DeviceTestTask; -import com.daxiang.model.Page; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -27,77 +28,71 @@ public class DeviceTestTaskService { @Autowired private DeviceTestTaskMapper deviceTestTaskMapper; - public Response update(DeviceTestTask deviceTestTask) { - if (deviceTestTask.getId() == null) { - return Response.fail("deviceTestTaskId不能为空"); + public void update(DeviceTestTask deviceTestTask) { + int updateCount = deviceTestTaskMapper.updateByPrimaryKeySelective(deviceTestTask); + if (updateCount != 1) { + throw new ServerException("更新失败,请稍后重试"); } - - int insertRow = deviceTestTaskMapper.updateByPrimaryKeySelective(deviceTestTask); - return insertRow == 1 ? Response.success("更新成功") : Response.fail("更新失败,请稍后重试"); } - public Response list(DeviceTestTask deviceTestTask, PageRequest pageRequest) { - boolean needPaging = pageRequest.needPaging(); - if (needPaging) { - PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); - } + public PagedData list(DeviceTestTask query, String orderBy, PageRequest pageRequest) { + Page page = PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); - List deviceTestTasks = selectByDeviceTestTask(deviceTestTask); + List deviceTestTasks = getDeviceTestTasks(query, orderBy); + return new PagedData<>(deviceTestTasks, page.getTotal()); + } - if (needPaging) { - long total = Page.getTotal(deviceTestTasks); - return Response.success(Page.build(deviceTestTasks, total)); - } else { - return Response.success(deviceTestTasks); - } + public List getDeviceTestTasks(DeviceTestTask query) { + return getDeviceTestTasks(query, null); } - private List selectByDeviceTestTask(DeviceTestTask deviceTestTask) { - DeviceTestTaskExample deviceTestTaskExample = new DeviceTestTaskExample(); - DeviceTestTaskExample.Criteria criteria = deviceTestTaskExample.createCriteria(); + public List getDeviceTestTasks(DeviceTestTask query, String orderBy) { + DeviceTestTaskExample example = new DeviceTestTaskExample(); + DeviceTestTaskExample.Criteria criteria = example.createCriteria(); - if (deviceTestTask != null) { - if (deviceTestTask.getId() != null) { - criteria.andIdEqualTo(deviceTestTask.getId()); + if (query != null) { + if (query.getId() != null) { + criteria.andIdEqualTo(query.getId()); } - if (deviceTestTask.getTestTaskId() != null) { - criteria.andTestTaskIdEqualTo(deviceTestTask.getTestTaskId()); + if (query.getTestTaskId() != null) { + criteria.andTestTaskIdEqualTo(query.getTestTaskId()); } - if (!StringUtils.isEmpty(deviceTestTask.getDeviceId())) { - criteria.andDeviceIdEqualTo(deviceTestTask.getDeviceId()); + if (!StringUtils.isEmpty(query.getDeviceId())) { + criteria.andDeviceIdEqualTo(query.getDeviceId()); } - if (deviceTestTask.getStatus() != null) { - criteria.andStatusEqualTo(deviceTestTask.getStatus()); + if (query.getStatus() != null) { + criteria.andStatusEqualTo(query.getStatus()); } } - return deviceTestTaskMapper.selectByExampleWithBLOBs(deviceTestTaskExample); + if (!StringUtils.isEmpty(orderBy)) { + example.setOrderByClause(orderBy); + } + + return deviceTestTaskMapper.selectByExampleWithBLOBs(example); } - public Response getFirstUnStartDeviceTestTask(String deviceId) { + public DeviceTestTask getFirstUnStartDeviceTestTask(String deviceId) { if (StringUtils.isEmpty(deviceId)) { - return Response.fail("deviceId不能为空"); + throw new ServerException("deviceId不能为空"); } - DeviceTestTaskExample example = new DeviceTestTaskExample(); - DeviceTestTaskExample.Criteria criteria = example.createCriteria(); - - criteria.andDeviceIdEqualTo(deviceId) - .andStatusEqualTo(DeviceTestTask.UNSTART_STATUS); - example.setOrderByClause("id asc limit 1"); + DeviceTestTask query = new DeviceTestTask(); + query.setDeviceId(deviceId); + query.setStatus(DeviceTestTask.UNSTART_STATUS); - List deviceTestTasks = deviceTestTaskMapper.selectByExampleWithBLOBs(example); - return CollectionUtils.isEmpty(deviceTestTasks) ? Response.success() : Response.success(deviceTestTasks.get(0)); + List deviceTestTasks = getDeviceTestTasks(query, "id asc limit 1"); + return CollectionUtils.isEmpty(deviceTestTasks) ? null : deviceTestTasks.get(0); } - public Response updateTestcase(Integer deviceTestTaskId, Testcase sourceTestcase) { + public void updateTestcase(Integer deviceTestTaskId, Testcase sourceTestcase) { if (deviceTestTaskId == null) { - return Response.fail("deviceTestTaskId不能为空"); + throw new ServerException("deviceTestTaskId不能为空"); } DeviceTestTask deviceTestTask = deviceTestTaskMapper.selectByPrimaryKey(deviceTestTaskId); if (deviceTestTask == null) { - return Response.fail("DeviceTestTask不存在"); + throw new ServerException("deviceTestTask不存在"); } deviceTestTask.getTestcases().stream() @@ -118,8 +113,10 @@ public Response updateTestcase(Integer deviceTestTaskId, Testcase sourceTestcase } }); - int updateRow = deviceTestTaskMapper.updateByPrimaryKeySelective(deviceTestTask); - return updateRow == 1 ? Response.success("更新成功") : Response.fail("更新失败"); + int updateCount = deviceTestTaskMapper.updateByPrimaryKeySelective(deviceTestTask); + if (updateCount != 1) { + throw new ServerException("更新失败,请稍后重试"); + } } private void copyStepProperties(Step sourceStep, Step targetStep) { @@ -152,14 +149,17 @@ private void copyTestcaseProperties(Testcase sourceTestcase, Testcase targetTest } } - public int add(DeviceTestTask deviceTestTask) { - return deviceTestTaskMapper.insertSelective(deviceTestTask); + public void add(DeviceTestTask deviceTestTask) { + int insertCount = deviceTestTaskMapper.insertSelective(deviceTestTask); + if (insertCount != 1) { + throw new ServerException("添加失败"); + } } public List getDeviceTestTasksByTestTaskId(Integer testTaskId) { DeviceTestTask query = new DeviceTestTask(); query.setTestTaskId(testTaskId); - return selectByDeviceTestTask(query); + return getDeviceTestTasks(query); } public List getDeviceTestTasksByTestTaskIds(List testTaskIds) { @@ -170,34 +170,39 @@ public List getDeviceTestTasksByTestTaskIds(List testTa return deviceTestTaskMapper.selectByExampleWithBLOBs(example); } - public int deleteBatch(List ids) { + public void deleteBatch(List ids) { if (CollectionUtils.isEmpty(ids)) { - return 0; + return; } DeviceTestTaskExample example = new DeviceTestTaskExample(); DeviceTestTaskExample.Criteria criteria = example.createCriteria(); criteria.andIdIn(ids); - return deviceTestTaskMapper.deleteByExample(example); + int deleteCount = deviceTestTaskMapper.deleteByExample(example); + if (deleteCount != ids.size()) { + throw new ServerException("删除失败"); + } } - public Response delete(Integer deviceTestTaskId) { + public void delete(Integer deviceTestTaskId) { if (deviceTestTaskId == null) { - return Response.fail("deviceTestTaskId不能为空"); + throw new ServerException("deviceTestTaskId不能为空"); } DeviceTestTask deviceTestTask = deviceTestTaskMapper.selectByPrimaryKey(deviceTestTaskId); if (deviceTestTask == null) { - return Response.fail("deviceTestTask不存在"); + throw new ServerException("deviceTestTask不存在"); } if (deviceTestTask.getStatus() == DeviceTestTask.RUNNING_STATUS) { - return Response.fail("deviceTestTask正在执行,无法删除"); + throw new ServerException("deviceTestTask正在执行,无法删除"); } - int deleteRow = deviceTestTaskMapper.deleteByPrimaryKey(deviceTestTaskId); - return deleteRow == 1 ? Response.success("删除成功") : Response.fail("删除失败,请稍后重试"); + int deleteCount = deviceTestTaskMapper.deleteByPrimaryKey(deviceTestTaskId); + if (deleteCount != 1) { + throw new ServerException("删除失败,请稍后重试"); + } } } diff --git a/src/main/java/com/daxiang/service/DriverService.java b/src/main/java/com/daxiang/service/DriverService.java index 7268af1..51e0179 100644 --- a/src/main/java/com/daxiang/service/DriverService.java +++ b/src/main/java/com/daxiang/service/DriverService.java @@ -1,19 +1,19 @@ package com.daxiang.service; import com.daxiang.dao.DriverDao; +import com.daxiang.exception.ServerException; import com.daxiang.mbg.mapper.DriverMapper; import com.daxiang.mbg.po.Driver; import com.daxiang.mbg.po.DriverExample; import com.daxiang.mbg.po.User; -import com.daxiang.model.Page; +import com.daxiang.model.PagedData; import com.daxiang.model.PageRequest; -import com.daxiang.model.Response; import com.daxiang.model.dto.DriverFile; import com.daxiang.model.vo.DriverVo; import com.daxiang.security.SecurityUtil; import com.daxiang.utils.HttpServletUtil; import com.github.pagehelper.PageHelper; -import com.google.common.collect.ImmutableMap; +import com.github.pagehelper.Page; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DuplicateKeyException; @@ -37,55 +37,51 @@ public class DriverService { @Autowired private UserService userService; - public Response add(Driver driver) { + public void add(Driver driver) { driver.setCreateTime(new Date()); driver.setCreatorUid(SecurityUtil.getCurrentUserId()); - int insertRow; try { - insertRow = driverMapper.insertSelective(driver); + int insertCount = driverMapper.insertSelective(driver); + if (insertCount != 1) { + throw new ServerException("添加失败,请稍后重试"); + } } catch (DuplicateKeyException e) { - return Response.fail("版本已存在"); + throw new ServerException(driver.getVersion() + "已存在"); } - - return insertRow == 1 ? Response.success("添加成功") : Response.fail("添加失败,请稍后重试"); } - public Response delete(Integer driverId) { + public void delete(Integer driverId) { if (driverId == null) { - return Response.fail("driverId不能为空"); + throw new ServerException("driverId不能为空"); } - int deleteRow = driverMapper.deleteByPrimaryKey(driverId); - return deleteRow == 1 ? Response.success("删除成功") : Response.fail("删除失败,请稍后重试"); + int deleteCount = driverMapper.deleteByPrimaryKey(driverId); + if (deleteCount != 1) { + throw new ServerException("删除失败,请稍后重试"); + } } - public Response update(Driver driver) { - int updateRow; + public void update(Driver driver) { try { - updateRow = driverMapper.updateByPrimaryKeyWithBLOBs(driver); + int updateCount = driverMapper.updateByPrimaryKeyWithBLOBs(driver); + if (updateCount != 1) { + throw new ServerException("更新失败,请稍后重试"); + } } catch (DuplicateKeyException e) { - return Response.fail("版本已存在"); + throw new ServerException(driver.getVersion() + "已存在"); } - - return updateRow == 1 ? Response.success("更新成功") : Response.fail("更新失败,请稍后重试"); } - public Response list(Driver driver, PageRequest pageRequest) { - boolean needPaging = pageRequest.needPaging(); - if (needPaging) { - PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); - } - - List drivers = selectByDriver(driver); - List driverVos = convertDriversToDriverVos(drivers); + public PagedData list(Driver query, String orderBy, PageRequest pageRequest) { + Page page = PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); - if (needPaging) { - long total = Page.getTotal(drivers); - return Response.success(Page.build(driverVos, total)); - } else { - return Response.success(driverVos); + if (StringUtils.isEmpty(orderBy)) { + orderBy = "create_time desc"; } + + List driverVos = getDriverVos(query, orderBy); + return new PagedData<>(driverVos, page.getTotal()); } private List convertDriversToDriverVos(List drivers) { @@ -100,7 +96,7 @@ private List convertDriversToDriverVos(List drivers) { .collect(Collectors.toList()); Map userMap = userService.getUserMapByIds(creatorUids); - return drivers.stream().map(driver -> { + List driverVos = drivers.stream().map(driver -> { DriverVo driverVo = new DriverVo(); BeanUtils.copyProperties(driver, driverVo); @@ -113,31 +109,41 @@ private List convertDriversToDriverVos(List drivers) { return driverVo; }).collect(Collectors.toList()); + + return driverVos; + } + + public List getDriverVos(Driver query, String orderBy) { + List drivers = getDrivers(query, orderBy); + return convertDriversToDriverVos(drivers); } - private List selectByDriver(Driver driver) { + public List getDrivers(Driver query, String orderBy) { DriverExample example = new DriverExample(); DriverExample.Criteria criteria = example.createCriteria(); - if (driver != null) { - if (driver.getId() != null) { - criteria.andIdEqualTo(driver.getId()); + if (query != null) { + if (query.getId() != null) { + criteria.andIdEqualTo(query.getId()); } - if (driver.getType() != null) { - criteria.andTypeEqualTo(driver.getType()); + if (query.getType() != null) { + criteria.andTypeEqualTo(query.getType()); } - if (!StringUtils.isEmpty(driver.getVersion())) { - criteria.andVersionEqualTo(driver.getVersion()); + if (!StringUtils.isEmpty(query.getVersion())) { + criteria.andVersionEqualTo(query.getVersion()); } } - example.setOrderByClause("create_time desc"); + + if (!StringUtils.isEmpty(orderBy)) { + example.setOrderByClause(orderBy); + } return driverMapper.selectByExampleWithBLOBs(example); } - public Response getDownloadUrl(Integer type, String deviceId, Integer platform) { + public String getDownloadUrl(Integer type, String deviceId, Integer platform) { if (type == null || StringUtils.isEmpty(deviceId) || platform == null) { - return Response.fail("非法参数"); + throw new ServerException("type or deviceId or platform 不能为空"); } List drivers = driverDao.selectByTypeAndDeviceId(type, deviceId); @@ -149,12 +155,12 @@ public Response getDownloadUrl(Integer type, String deviceId, Integer platform) if (driverFile.isPresent()) { String filePath = driverFile.get().getFilePath(); if (!StringUtils.isEmpty(filePath)) { - return Response.success(ImmutableMap.of("downloadUrl", HttpServletUtil.getStaticResourceUrl(filePath))); + return HttpServletUtil.getStaticResourceUrl(filePath); } } } } - return Response.success(); + return ""; } } diff --git a/src/main/java/com/daxiang/service/EnvironmentService.java b/src/main/java/com/daxiang/service/EnvironmentService.java index e7d0c11..9cb9392 100644 --- a/src/main/java/com/daxiang/service/EnvironmentService.java +++ b/src/main/java/com/daxiang/service/EnvironmentService.java @@ -1,15 +1,15 @@ package com.daxiang.service; -import com.daxiang.exception.BusinessException; +import com.daxiang.exception.ServerException; import com.daxiang.mbg.mapper.EnvironmentMapper; import com.daxiang.mbg.po.*; -import com.daxiang.model.Page; +import com.daxiang.model.PagedData; import com.daxiang.model.PageRequest; -import com.daxiang.model.Response; import com.daxiang.model.environment.EnvironmentValue; import com.daxiang.model.vo.EnvironmentVo; import com.daxiang.security.SecurityUtil; import com.github.pagehelper.PageHelper; +import com.github.pagehelper.Page; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DuplicateKeyException; @@ -37,55 +37,49 @@ public class EnvironmentService { @Autowired private UserService userService; - public Response add(Environment environment) { + public void add(Environment environment) { environment.setCreateTime(new Date()); environment.setCreatorUid(SecurityUtil.getCurrentUserId()); - int insertRow; try { - insertRow = environmentMapper.insertSelective(environment); + int insertCount = environmentMapper.insertSelective(environment); + if (insertCount != 1) { + throw new ServerException("添加失败,请稍后重试"); + } } catch (DuplicateKeyException e) { - return Response.fail("命名冲突"); + throw new ServerException(environment.getName() + "已存在"); } - return insertRow == 1 ? Response.success("添加成功") : Response.fail("添加失败,请稍后重试"); } - public Response delete(Integer environmentId) { - if (environmentId == null) { - return Response.fail("环境id不能为空"); - } - + public void delete(Integer environmentId) { check(environmentId); - int deleteRow = environmentMapper.deleteByPrimaryKey(environmentId); - return deleteRow == 1 ? Response.success("删除成功") : Response.fail("删除失败,请稍后重试"); + int deleteCount = environmentMapper.deleteByPrimaryKey(environmentId); + if (deleteCount != 1) { + throw new ServerException("删除失败,请稍后重试"); + } } - public Response update(Environment environment) { - int updateRow; + public void update(Environment environment) { try { - updateRow = environmentMapper.updateByPrimaryKeySelective(environment); + int updateCount = environmentMapper.updateByPrimaryKeySelective(environment); + if (updateCount != 1) { + throw new ServerException("更新失败,请稍后重试"); + } } catch (DuplicateKeyException e) { - return Response.fail("命名冲突"); + throw new ServerException(environment.getName() + "已存在"); } - return updateRow == 1 ? Response.success("更新成功") : Response.fail("修改失败,请稍后重试"); } - public Response list(Environment environment, PageRequest pageRequest) { - boolean needPaging = pageRequest.needPaging(); - if (needPaging) { - PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); - } - - List environments = selectByEnvironment(environment); - List environmentVos = convertEnvironmentsToEnvironmentVos(environments); + public PagedData list(Environment query, String orderBy, PageRequest pageRequest) { + Page page = PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); - if (needPaging) { - long total = Page.getTotal(environments); - return Response.success(Page.build(environmentVos, total)); - } else { - return Response.success(environmentVos); + if (StringUtils.isEmpty(orderBy)) { + orderBy = "create_time desc"; } + + List environmentVos = getEnvironmentVos(query, orderBy); + return new PagedData<>(environmentVos, page.getTotal()); } private List convertEnvironmentsToEnvironmentVos(List environments) { @@ -100,7 +94,7 @@ private List convertEnvironmentsToEnvironmentVos(List userMap = userService.getUserMapByIds(creatorUids); - return environments.stream().map(env -> { + List environmentVos = environments.stream().map(env -> { EnvironmentVo environmentVo = new EnvironmentVo(); BeanUtils.copyProperties(env, environmentVo); @@ -113,24 +107,34 @@ private List convertEnvironmentsToEnvironmentVos(List selectByEnvironment(Environment environment) { + public List getEnvironmentVos(Environment query, String orderBy) { + List environments = getEnvironments(query, orderBy); + return convertEnvironmentsToEnvironmentVos(environments); + } + + public List getEnvironments(Environment query, String orderBy) { EnvironmentExample example = new EnvironmentExample(); EnvironmentExample.Criteria criteria = example.createCriteria(); - if (environment != null) { - if (environment.getId() != null) { - criteria.andIdEqualTo(environment.getId()); + if (query != null) { + if (query.getId() != null) { + criteria.andIdEqualTo(query.getId()); } - if (!StringUtils.isEmpty(environment.getName())) { - criteria.andNameEqualTo(environment.getName()); + if (!StringUtils.isEmpty(query.getName())) { + criteria.andNameEqualTo(query.getName()); } - if (environment.getProjectId() != null) { - criteria.andProjectIdEqualTo(environment.getProjectId()); + if (query.getProjectId() != null) { + criteria.andProjectIdEqualTo(query.getProjectId()); } } - example.setOrderByClause("create_time desc"); + + if (!StringUtils.isEmpty(orderBy)) { + example.setOrderByClause(orderBy); + } return environmentMapper.selectByExample(example); } @@ -145,28 +149,24 @@ private void check(Integer envId) { List actions = actionService.getActionsByLocalVarsEnvironmentId(envId); if (!CollectionUtils.isEmpty(actions)) { String actionNames = actions.stream().map(Action::getName).collect(Collectors.joining("、")); - throw new BusinessException("actions: " + actionNames + ", 正在使用此环境"); + throw new ServerException("actions: " + actionNames + ", 正在使用此环境"); } // 检查env是否被globalVar使用 List globalVars = globalVarService.getGlobalVarsByEnvironmentId(envId); if (!CollectionUtils.isEmpty(globalVars)) { String globalVarNames = globalVars.stream().map(GlobalVar::getName).collect(Collectors.joining("、")); - throw new BusinessException("globalVars: " + globalVarNames + ", 正在使用此环境"); + throw new ServerException("globalVars: " + globalVarNames + ", 正在使用此环境"); } // 检查env是否被testplan使用 List testPlans = testPlanService.getTestPlansByEnvironmentId(envId); if (!CollectionUtils.isEmpty(testPlans)) { String testPlanNames = testPlans.stream().map(TestPlan::getName).collect(Collectors.joining("、")); - throw new BusinessException("testPlans: " + testPlanNames + ", 正在使用此环境"); + throw new ServerException("testPlans: " + testPlanNames + ", 正在使用此环境"); } } - public Environment getEnvironmentById(Integer id) { - return environmentMapper.selectByPrimaryKey(id); - } - /** * 在environmentValues中找到与envId匹配的value */ @@ -184,4 +184,17 @@ public String getValueInEnvironmentValues(List environmentValu return defaultValue; } + + public String getEnvironmentNameById(Integer envId) { + if (envId == EnvironmentValue.DEFAULT_ENVIRONMENT_ID) { + return "默认"; + } + + Environment environment = environmentMapper.selectByPrimaryKey(envId); + if (environment != null) { + return environment.getName(); + } + + return ""; + } } diff --git a/src/main/java/com/daxiang/service/GlobalVarService.java b/src/main/java/com/daxiang/service/GlobalVarService.java index 9b059c7..e92da99 100644 --- a/src/main/java/com/daxiang/service/GlobalVarService.java +++ b/src/main/java/com/daxiang/service/GlobalVarService.java @@ -1,16 +1,17 @@ package com.daxiang.service; import com.daxiang.dao.GlobalVarDao; +import com.daxiang.exception.ServerException; import com.daxiang.mbg.po.GlobalVarExample; import com.daxiang.mbg.po.User; +import com.daxiang.model.PagedData; import com.daxiang.security.SecurityUtil; import com.github.pagehelper.PageHelper; +import com.github.pagehelper.Page; import com.daxiang.mbg.mapper.GlobalVarMapper; import com.daxiang.mbg.po.GlobalVar; import com.daxiang.model.PageRequest; -import com.daxiang.model.Response; import com.daxiang.model.vo.GlobalVarVo; -import com.daxiang.model.Page; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DuplicateKeyException; @@ -36,20 +37,21 @@ public class GlobalVarService { @Autowired private EnvironmentService environmentService; - public Response add(GlobalVar globalVar) { + public void add(GlobalVar globalVar) { globalVar.setCreateTime(new Date()); globalVar.setCreatorUid(SecurityUtil.getCurrentUserId()); - int insertRow; try { - insertRow = globalVarMapper.insertSelective(globalVar); + int insertCount = globalVarMapper.insertSelective(globalVar); + if (insertCount != 1) { + throw new ServerException("添加失败,请稍后重试"); + } } catch (DuplicateKeyException e) { - return Response.fail("命名冲突"); + throw new ServerException(globalVar.getName() + "已存在"); } - return insertRow == 1 ? Response.success("添加GlobalVar成功") : Response.fail("添加GlobalVar失败,请稍后重试"); } - public Response addBatch(List globalVars) { + public void addBatch(List globalVars) { Integer currentUserId = SecurityUtil.getCurrentUserId(); Date now = new Date(); @@ -58,53 +60,49 @@ public Response addBatch(List globalVars) { globalVar.setCreatorUid(currentUserId); }); - int insertRow; try { - insertRow = globalVarDao.insertBatch(globalVars); + int insertCount = globalVarDao.insertBatch(globalVars); + if (insertCount != globalVars.size()) { + throw new ServerException("添加失败,请稍后重试"); + } } catch (DuplicateKeyException e) { - return Response.fail("命名冲突"); + throw new ServerException("命名冲突"); } - return insertRow == globalVars.size() ? Response.success("添加成功") : Response.fail("添加失败,请稍后重试"); } - public Response delete(Integer globalVarId) { + public void delete(Integer globalVarId) { if (globalVarId == null) { - return Response.fail("globalVarId不能为空"); + throw new ServerException("globalVarId不能为空"); } // todo 检查全局变量是否被action使用 - int deleteRow = globalVarMapper.deleteByPrimaryKey(globalVarId); - return deleteRow == 1 ? Response.success("删除成功") : Response.fail("删除失败,请稍后重试"); + int deleteCount = globalVarMapper.deleteByPrimaryKey(globalVarId); + if (deleteCount != 1) { + throw new ServerException("删除失败,请稍后重试"); + } } - public Response update(GlobalVar globalVar) { + public void update(GlobalVar globalVar) { // todo 检查全局变量是否被action使用 - - int updateRow; try { - updateRow = globalVarMapper.updateByPrimaryKeyWithBLOBs(globalVar); + int updateCount = globalVarMapper.updateByPrimaryKeyWithBLOBs(globalVar); + if (updateCount != 1) { + throw new ServerException("更新失败,请稍后重试"); + } } catch (DuplicateKeyException e) { - return Response.fail("命名冲突"); + throw new ServerException(globalVar.getName() + "已存在"); } - - return updateRow == 1 ? Response.success("更新GlobalVar成功") : Response.fail("更新GlobalVar失败,请稍后重试"); } - public Response list(GlobalVar globalVar, PageRequest pageRequest) { - boolean needPaging = pageRequest.needPaging(); - if (needPaging) { - PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); - } - - List globalVars = selectByGlobalVar(globalVar); - List globalVarVos = convertGlobalVarsToGlobalVarVos(globalVars); + public PagedData list(GlobalVar query, String orderBy, PageRequest pageRequest) { + Page page = PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); - if (needPaging) { - long total = Page.getTotal(globalVars); - return Response.success(Page.build(globalVarVos, total)); - } else { - return Response.success(globalVarVos); + if (StringUtils.isEmpty(orderBy)) { + orderBy = "create_time desc"; } + + List globalVarVos = getGlobalVarVos(query, orderBy); + return new PagedData<>(globalVarVos, page.getTotal()); } private List convertGlobalVarsToGlobalVarVos(List globalVars) { @@ -119,7 +117,7 @@ private List convertGlobalVarsToGlobalVarVos(List global .collect(Collectors.toList()); Map userMap = userService.getUserMapByIds(creatorUids); - return globalVars.stream().map(globalVar -> { + List globalVarVos = globalVars.stream().map(globalVar -> { GlobalVarVo globalVarVo = new GlobalVarVo(); BeanUtils.copyProperties(globalVar, globalVarVo); @@ -132,37 +130,51 @@ private List convertGlobalVarsToGlobalVarVos(List global return globalVarVo; }).collect(Collectors.toList()); + + return globalVarVos; + } + + public List getGlobalVarVos(GlobalVar query, String orderBy) { + List globalVars = getGlobalVars(query, orderBy); + return convertGlobalVarsToGlobalVarVos(globalVars); + } + + public List getGlobalVars(GlobalVar query) { + return getGlobalVars(query, null); } - private List selectByGlobalVar(GlobalVar globalVar) { + public List getGlobalVars(GlobalVar query, String orderBy) { GlobalVarExample example = new GlobalVarExample(); GlobalVarExample.Criteria criteria = example.createCriteria(); - if (globalVar != null) { - if (globalVar.getId() != null) { - criteria.andIdEqualTo(globalVar.getId()); + if (query != null) { + if (query.getId() != null) { + criteria.andIdEqualTo(query.getId()); } - if (globalVar.getType() != null) { - criteria.andTypeEqualTo(globalVar.getType()); + if (query.getType() != null) { + criteria.andTypeEqualTo(query.getType()); } - if (globalVar.getProjectId() != null) { - criteria.andProjectIdEqualTo(globalVar.getProjectId()); + if (query.getProjectId() != null) { + criteria.andProjectIdEqualTo(query.getProjectId()); } - if (globalVar.getCategoryId() != null) { - criteria.andCategoryIdEqualTo(globalVar.getCategoryId()); + if (query.getCategoryId() != null) { + criteria.andCategoryIdEqualTo(query.getCategoryId()); } - if (!StringUtils.isEmpty(globalVar.getName())) { - criteria.andNameEqualTo(globalVar.getName()); + if (!StringUtils.isEmpty(query.getName())) { + criteria.andNameEqualTo(query.getName()); } } - example.setOrderByClause("create_time desc"); + + if (!StringUtils.isEmpty(orderBy)) { + example.setOrderByClause(orderBy); + } return globalVarMapper.selectByExampleWithBLOBs(example); } public List getGlobalVarsByEnvironmentId(Integer envId) { if (envId == null) { - return new ArrayList<>(); + throw new ServerException("envId不能为空"); } return globalVarDao.selectByEnvironmentId(envId); @@ -170,12 +182,12 @@ public List getGlobalVarsByEnvironmentId(Integer envId) { public List getGlobalVarsByProjectIdAndEnv(Integer projectId, Integer env) { if (projectId == null || env == null) { - return new ArrayList<>(); + throw new ServerException("projectId or env不能为空"); } GlobalVar query = new GlobalVar(); query.setProjectId(projectId); - List globalVars = selectByGlobalVar(query); + List globalVars = getGlobalVars(query); globalVars.forEach(globalVar -> { String value = environmentService.getValueInEnvironmentValues(globalVar.getEnvironmentValues(), env); diff --git a/src/main/java/com/daxiang/service/MobileService.java b/src/main/java/com/daxiang/service/MobileService.java index d978b35..cfd1435 100644 --- a/src/main/java/com/daxiang/service/MobileService.java +++ b/src/main/java/com/daxiang/service/MobileService.java @@ -1,14 +1,15 @@ package com.daxiang.service; import com.daxiang.agent.AgentClient; +import com.daxiang.exception.ServerException; import com.daxiang.mbg.mapper.MobileMapper; import com.daxiang.mbg.po.Mobile; import com.daxiang.mbg.po.MobileExample; import com.daxiang.model.PageRequest; -import com.daxiang.model.Response; import com.daxiang.model.vo.MobileVo; import com.github.pagehelper.PageHelper; -import com.daxiang.model.Page; +import com.github.pagehelper.Page; +import com.daxiang.model.PagedData; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; @@ -17,6 +18,7 @@ import org.springframework.util.StringUtils; import java.util.*; +import java.util.function.Function; import java.util.stream.Collectors; /** @@ -31,89 +33,90 @@ public class MobileService { @Autowired private AgentClient agentClient; - public Response save(Mobile mobile) { + public void save(Mobile mobile) { Mobile dbMobile = mobileMapper.selectByPrimaryKey(mobile.getId()); - int saveRow; + + int saveCount; if (dbMobile == null) { // 首次接入的mobile - saveRow = mobileMapper.insertSelective(mobile); + saveCount = mobileMapper.insertSelective(mobile); } else { // 更新Mobile - saveRow = mobileMapper.updateByPrimaryKeySelective(mobile); + saveCount = mobileMapper.updateByPrimaryKeySelective(mobile); + } + + if (saveCount != 1) { + throw new ServerException("保存失败,请稍后重试"); } - return saveRow == 1 ? Response.success("保存成功") : Response.fail("保存失败,请稍后重试"); } - public Response list(Mobile mobile, PageRequest pageRequest) { - boolean needPaging = pageRequest.needPaging(); - if (needPaging) { - PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); + public PagedData list(Mobile query, String orderBy, PageRequest pageRequest) { + Page page = PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); + + if (StringUtils.isEmpty(orderBy)) { + orderBy = "status desc,create_time desc"; } - List mobiles = selectByMobile(mobile); - List mobileVos = mobiles.stream().map(d -> { + List mobileVos = getMobileVos(query, orderBy); + return new PagedData<>(mobileVos, page.getTotal()); + } + + public List getMobileVos(Mobile query, String orderBy) { + List mobiles = getMobiles(query, orderBy); + List mobileVos = mobiles.stream().map(mobile -> { MobileVo mobileVo = new MobileVo(); - BeanUtils.copyProperties(d, mobileVo); + BeanUtils.copyProperties(mobile, mobileVo); return mobileVo; }).collect(Collectors.toList()); - - if (needPaging) { - long total = Page.getTotal(mobiles); - return Response.success(Page.build(mobileVos, total)); - } else { - return Response.success(mobileVos); - } + return mobileVos; } - private List selectByMobile(Mobile mobile) { + public List getMobiles(Mobile query, String orderBy) { MobileExample example = new MobileExample(); MobileExample.Criteria criteria = example.createCriteria(); - if (mobile != null) { - if (!StringUtils.isEmpty(mobile.getId())) { - criteria.andIdEqualTo(mobile.getId()); + if (query != null) { + if (!StringUtils.isEmpty(query.getId())) { + criteria.andIdEqualTo(query.getId()); } - if (!StringUtils.isEmpty(mobile.getName())) { - criteria.andNameLike("%" + mobile.getName() + "%"); + if (!StringUtils.isEmpty(query.getName())) { + criteria.andNameLike("%" + query.getName() + "%"); } - if (mobile.getEmulator() != null) { - criteria.andEmulatorEqualTo(mobile.getEmulator()); + if (query.getEmulator() != null) { + criteria.andEmulatorEqualTo(query.getEmulator()); } - if (!StringUtils.isEmpty(mobile.getSystemVersion())) { - criteria.andSystemVersionEqualTo(mobile.getSystemVersion()); + if (!StringUtils.isEmpty(query.getSystemVersion())) { + criteria.andSystemVersionEqualTo(query.getSystemVersion()); } - if (!StringUtils.isEmpty(mobile.getAgentIp())) { - criteria.andAgentIpEqualTo(mobile.getAgentIp()); + if (!StringUtils.isEmpty(query.getAgentIp())) { + criteria.andAgentIpEqualTo(query.getAgentIp()); } - if (mobile.getAgentPort() != null) { - criteria.andAgentPortEqualTo(mobile.getAgentPort()); + if (query.getAgentPort() != null) { + criteria.andAgentPortEqualTo(query.getAgentPort()); } - if (mobile.getPlatform() != null) { - criteria.andPlatformEqualTo(mobile.getPlatform()); + if (query.getPlatform() != null) { + criteria.andPlatformEqualTo(query.getPlatform()); } - if (mobile.getStatus() != null) { - criteria.andStatusEqualTo(mobile.getStatus()); + if (query.getStatus() != null) { + criteria.andStatusEqualTo(query.getStatus()); } } - example.setOrderByClause("status desc,create_time desc"); + + if (!StringUtils.isEmpty(orderBy)) { + example.setOrderByClause(orderBy); + } return mobileMapper.selectByExample(example); } - /** - * 前端点击"立即使用" - * - * @param mobileId - * @return - */ - public Response start(String mobileId) { + public Mobile start(String mobileId) { if (StringUtils.isEmpty(mobileId)) { - return Response.fail("mobileId不能为空"); + throw new ServerException("mobileId不能为空"); } Mobile dbMobile = mobileMapper.selectByPrimaryKey(mobileId); if (dbMobile == null) { - return Response.fail("mobile不存在"); + throw new ServerException("mobile不存在"); } // 有时server被强制关闭,导致agent下mobile的状态无法同步到server @@ -131,19 +134,19 @@ public Response start(String mobileId) { dbMobile.setStatus(Mobile.OFFLINE_STATUS); mobileMapper.updateByPrimaryKeySelective(dbMobile); } - return Response.fail("mobile不在线"); + throw new ServerException("mobile不在线"); } else { if (agentMobile.getStatus() == Mobile.IDLE_STATUS) { - return Response.success(agentMobile); + return agentMobile; } else { // 同步最新状态 mobileMapper.updateByPrimaryKeySelective(agentMobile); - return Response.fail("mobile未闲置"); + throw new ServerException("mobile未闲置"); } } } - public Response getOnlineMobiles(Integer platform) { + public List getOnlineMobiles(Integer platform) { MobileExample example = new MobileExample(); MobileExample.Criteria criteria = example.createCriteria(); @@ -151,7 +154,7 @@ public Response getOnlineMobiles(Integer platform) { if (platform != null) { criteria.andPlatformEqualTo(platform); } - return Response.success(mobileMapper.selectByExample(example)); + return mobileMapper.selectByExample(example); } public List getOnlineMobilesByAgentIps(List agentIps) { @@ -177,7 +180,7 @@ public void agentOffline(String agentIp) { mobileMapper.updateByExampleSelective(mobile, example); } - private List getMobilesByIds(Set mobileIds) { + public List getMobilesByIds(Set mobileIds) { if (CollectionUtils.isEmpty(mobileIds)) { return new ArrayList<>(); } @@ -190,6 +193,6 @@ private List getMobilesByIds(Set mobileIds) { public Map getMobileMapByIds(Set mobileIds) { List mobiles = getMobilesByIds(mobileIds); - return mobiles.stream().collect(Collectors.toMap(Mobile::getId, m -> m, (k1, k2) -> k1)); + return mobiles.stream().collect(Collectors.toMap(Mobile::getId, Function.identity(), (k1, k2) -> k1)); } } diff --git a/src/main/java/com/daxiang/service/PageService.java b/src/main/java/com/daxiang/service/PageService.java index 24771a5..5779888 100644 --- a/src/main/java/com/daxiang/service/PageService.java +++ b/src/main/java/com/daxiang/service/PageService.java @@ -1,7 +1,9 @@ package com.daxiang.service; import com.daxiang.dao.PageDao; +import com.daxiang.exception.ServerException; import com.daxiang.mbg.po.*; +import com.daxiang.model.PagedData; import com.daxiang.security.SecurityUtil; import com.github.pagehelper.PageHelper; import com.daxiang.mbg.mapper.PageMapper; @@ -13,6 +15,7 @@ import org.springframework.dao.DuplicateKeyException; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; import java.util.*; import java.util.stream.Collectors; @@ -30,78 +33,70 @@ public class PageService { @Autowired private ActionService actionService; @Autowired - private CategoryService categoryService; - @Autowired private UserService userService; - public Response add(Page page) { + public void add(Page page) { page.setCreateTime(new Date()); page.setCreatorUid(SecurityUtil.getCurrentUserId()); - int insertRow; try { - insertRow = pageMapper.insertSelective(page); + int insertCount = pageMapper.insertSelective(page); + if (insertCount != 1) { + throw new ServerException("添加失败,请稍后重试"); + } } catch (DuplicateKeyException e) { - return Response.fail("命名冲突"); + throw new ServerException(page.getName() + "已存在"); } - return insertRow == 1 ? Response.success("添加Page成功", page) : Response.fail("添加Page失败,请稍后重试"); } - public Response delete(Integer pageId) { - if (pageId == null) { - return Response.fail("pageId不能为空"); - } - + public void delete(Integer pageId) { // 检查Page名下是否有action List actions = actionService.getActionsByPageId(pageId); if (!CollectionUtils.isEmpty(actions)) { String actionNames = actions.stream().map(Action::getName).collect(Collectors.joining("、")); - return Response.fail("actions: " + actionNames + ",已绑定该page,无法删除"); + throw new ServerException("actions: " + actionNames + ",已绑定该page,无法删除"); } - int delRow = pageMapper.deleteByPrimaryKey(pageId); - return delRow == 1 ? Response.success("删除Page成功") : Response.fail("删除Page失败,请稍后重试"); + int deleteCount = pageMapper.deleteByPrimaryKey(pageId); + if (deleteCount != 1) { + throw new ServerException("删除失败,请稍后重试"); + } } - public Response update(Page page) { - int updateRow; + public void update(Page page) { try { - updateRow = pageMapper.updateByPrimaryKeyWithBLOBs(page); + int updateCount = pageMapper.updateByPrimaryKeyWithBLOBs(page); + if (updateCount != 1) { + throw new ServerException("删除失败,请稍后重试"); + } } catch (DuplicateKeyException e) { - return Response.fail("命名冲突"); + throw new ServerException(page.getName() + "已存在"); } - return updateRow == 1 ? Response.success("保存Page成功") : Response.fail("保存Page失败,请稍后重试"); } - public Response list(Page page, PageRequest pageRequest) { - boolean needPaging = pageRequest.needPaging(); - if (needPaging) { - PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); - } - - List pages = selectPagesWithoutWindowHierarchyByPage(page); - List pageVos = convertPagesToPageVos(pages); + public PagedData listWithoutWindowHierarchy(Page query, String orderBy, PageRequest pageRequest) { + com.github.pagehelper.Page page = PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); - if (needPaging) { - long total = com.daxiang.model.Page.getTotal(pages); - return Response.success(com.daxiang.model.Page.build(pageVos, total)); - } else { - return Response.success(pageVos); + if (StringUtils.isEmpty(orderBy)) { + orderBy = "create_time desc"; } + + List pageVos = getPageVosWithoutWindowHierarchy(query, orderBy); + return new PagedData<>(pageVos, page.getTotal()); } - public Response getPageVoById(Integer pageId) { + public PageVo getPageVoById(Integer pageId) { if (pageId == null) { - return Response.fail("pageId不能为空"); + throw new ServerException("pageId不能为空"); } Page page = pageMapper.selectByPrimaryKey(pageId); if (page == null) { - return Response.fail("page不存在"); + throw new ServerException("page不存在"); } List pageVos = convertPagesToPageVos(Arrays.asList(page)); - return Response.success(pageVos.get(0)); + return pageVos.get(0); } private List convertPagesToPageVos(List pages) { @@ -116,7 +111,7 @@ private List convertPagesToPageVos(List pages) { .collect(Collectors.toList()); Map userMap = userService.getUserMapByIds(creatorUids); - return pages.stream().map(page -> { + List pageVos = pages.stream().map(page -> { PageVo pageVo = new PageVo(); BeanUtils.copyProperties(page, pageVo); @@ -129,36 +124,50 @@ private List convertPagesToPageVos(List pages) { return pageVo; }).collect(Collectors.toList()); + + return pageVos; } - private List selectPagesWithoutWindowHierarchyByPage(Page page) { + public List getPageVosWithoutWindowHierarchy(Page query, String orderBy) { + List pages = getPagesWithoutWindowHierarchy(query, orderBy); + return convertPagesToPageVos(pages); + } + + public List getPagesWithoutWindowHierarchy(Page query) { + return getPagesWithoutWindowHierarchy(query, null); + } + + public List getPagesWithoutWindowHierarchy(Page query, String orderBy) { PageExample example = new PageExample(); PageExample.Criteria criteria = example.createCriteria(); - if (page != null) { - if (page.getId() != null) { - criteria.andIdEqualTo(page.getId()); + if (query != null) { + if (query.getId() != null) { + criteria.andIdEqualTo(query.getId()); } - if (page.getCategoryId() != null) { - criteria.andCategoryIdEqualTo(page.getCategoryId()); + if (query.getCategoryId() != null) { + criteria.andCategoryIdEqualTo(query.getCategoryId()); } - if (page.getProjectId() != null) { - criteria.andProjectIdEqualTo(page.getProjectId()); + if (query.getProjectId() != null) { + criteria.andProjectIdEqualTo(query.getProjectId()); } } - example.setOrderByClause("create_time desc"); + + if (!StringUtils.isEmpty(orderBy)) { + example.setOrderByClause(orderBy); + } return pageDao.selectPagesWithoutWindowHierarchyByExample(example); } public List getPagesWithoutWindowHierarchyByProjectId(Integer projectId) { if (projectId == null) { - return new ArrayList<>(); + throw new ServerException("projectId不能为空"); } Page query = new Page(); query.setProjectId(projectId); - return selectPagesWithoutWindowHierarchyByPage(query); + return getPagesWithoutWindowHierarchy(query); } public List getPagesWithoutWindowHierarchyByCategoryIds(List categoryIds) { diff --git a/src/main/java/com/daxiang/service/ProjectService.java b/src/main/java/com/daxiang/service/ProjectService.java index ea950b2..c2faaff 100644 --- a/src/main/java/com/daxiang/service/ProjectService.java +++ b/src/main/java/com/daxiang/service/ProjectService.java @@ -1,14 +1,15 @@ package com.daxiang.service; +import com.daxiang.exception.ServerException; import com.daxiang.mbg.mapper.ProjectMapper; import com.daxiang.mbg.po.User; import com.daxiang.model.PageRequest; -import com.daxiang.model.Response; import com.daxiang.mbg.po.ProjectExample; import com.daxiang.security.SecurityUtil; import com.github.pagehelper.PageHelper; +import com.github.pagehelper.Page; import com.daxiang.mbg.po.Project; -import com.daxiang.model.Page; +import com.daxiang.model.PagedData; import com.daxiang.model.vo.ProjectVo; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; @@ -31,53 +32,51 @@ public class ProjectService { @Autowired private UserService userService; - public Response add(Project project) { + public void add(Project project) { project.setCreateTime(new Date()); project.setCreatorUid(SecurityUtil.getCurrentUserId()); - int insertRow; try { - insertRow = projectMapper.insertSelective(project); + int insertCount = projectMapper.insertSelective(project); + if (insertCount != 1) { + throw new ServerException("添加失败,请稍后重试"); + } } catch (DuplicateKeyException e) { - return Response.fail("命名冲突"); + throw new ServerException(project.getName() + "已存在"); } - return insertRow == 1 ? Response.success("添加Project成功") : Response.fail("添加Project失败,请稍后重试"); } - public Response delete(Integer projectId) { + public void delete(Integer projectId) { if (projectId == null) { - return Response.fail("项目id不能为空"); + throw new ServerException("projectId不能为空"); } - int deleteRow = projectMapper.deleteByPrimaryKey(projectId); - return deleteRow == 1 ? Response.success("删除Project成功") : Response.fail("删除Project失败,请稍后重试"); + int deleteCount = projectMapper.deleteByPrimaryKey(projectId); + if (deleteCount != 1) { + throw new ServerException("删除失败,请稍后重试"); + } } - public Response update(Project project) { - int updateRow; + public void update(Project project) { try { - updateRow = projectMapper.updateByPrimaryKeySelective(project); + int updateCount = projectMapper.updateByPrimaryKeySelective(project); + if (updateCount != 1) { + throw new ServerException("更新失败,请稍后重试"); + } } catch (DuplicateKeyException e) { - return Response.fail("命名冲突"); + throw new ServerException(project.getName() + "已存在"); } - return updateRow == 1 ? Response.success("更新Project成功") : Response.fail("修改Project失败,请稍后重试"); } - public Response list(Project project, PageRequest pageRequest) { - boolean needPaging = pageRequest.needPaging(); - if (needPaging) { - PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); - } - - List projects = selectByProject(project); - List projectVos = convertProjectsToProjectVos(projects); + public PagedData list(Project query, String orderBy, PageRequest pageRequest) { + Page page = PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); - if (needPaging) { - long total = Page.getTotal(projects); - return Response.success(Page.build(projectVos, total)); - } else { - return Response.success(projectVos); + if (StringUtils.isEmpty(orderBy)) { + orderBy = "create_time desc"; } + + List projectVos = getProjectVos(query, orderBy); + return new PagedData<>(projectVos, page.getTotal()); } private List convertProjectsToProjectVos(List projects) { @@ -92,7 +91,7 @@ private List convertProjectsToProjectVos(List projects) { .collect(Collectors.toList()); Map userMap = userService.getUserMapByIds(creatorUids); - return projects.stream().map(project -> { + List projectVos = projects.stream().map(project -> { ProjectVo projectVo = new ProjectVo(); BeanUtils.copyProperties(project, projectVo); @@ -105,24 +104,34 @@ private List convertProjectsToProjectVos(List projects) { return projectVo; }).collect(Collectors.toList()); + + return projectVos; + } + + public List getProjectVos(Project query, String orderBy) { + List projects = getProjects(query, orderBy); + return convertProjectsToProjectVos(projects); } - private List selectByProject(Project project) { + public List getProjects(Project query, String orderBy) { ProjectExample example = new ProjectExample(); ProjectExample.Criteria criteria = example.createCriteria(); - if (project != null) { - if (project.getId() != null) { - criteria.andIdEqualTo(project.getId()); + if (query != null) { + if (query.getId() != null) { + criteria.andIdEqualTo(query.getId()); } - if (!StringUtils.isEmpty(project.getName())) { - criteria.andNameEqualTo(project.getName()); + if (!StringUtils.isEmpty(query.getName())) { + criteria.andNameEqualTo(query.getName()); } - if (project.getPlatform() != null) { - criteria.andPlatformEqualTo(project.getPlatform()); + if (query.getPlatform() != null) { + criteria.andPlatformEqualTo(query.getPlatform()); } } - example.setOrderByClause("create_time desc"); + + if (!StringUtils.isEmpty(orderBy)) { + example.setOrderByClause(orderBy); + } return projectMapper.selectByExampleWithBLOBs(example); } diff --git a/src/main/java/com/daxiang/service/RoleService.java b/src/main/java/com/daxiang/service/RoleService.java index f9b160f..a7b3fce 100644 --- a/src/main/java/com/daxiang/service/RoleService.java +++ b/src/main/java/com/daxiang/service/RoleService.java @@ -1,10 +1,12 @@ package com.daxiang.service; import com.daxiang.mbg.mapper.RoleMapper; -import com.daxiang.model.Response; +import com.daxiang.mbg.po.Role; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.util.List; + /** * Created by jiangyitao. */ @@ -14,9 +16,8 @@ public class RoleService { @Autowired private RoleMapper roleMapper; - public Response list() { - // select all - return Response.success(roleMapper.selectByExample(null)); + public List list() { + return roleMapper.selectByExample(null); } } diff --git a/src/main/java/com/daxiang/service/TestPlanService.java b/src/main/java/com/daxiang/service/TestPlanService.java index 17b35f7..10e2de9 100644 --- a/src/main/java/com/daxiang/service/TestPlanService.java +++ b/src/main/java/com/daxiang/service/TestPlanService.java @@ -1,16 +1,17 @@ package com.daxiang.service; +import com.daxiang.exception.ServerException; import com.daxiang.mbg.po.TestPlan; import com.daxiang.mbg.po.TestPlanExample; import com.daxiang.mbg.po.User; -import com.daxiang.model.Page; +import com.daxiang.model.PagedData; import com.daxiang.model.PageRequest; import com.daxiang.dao.TestPlanDao; import com.daxiang.model.vo.TestPlanVo; import com.daxiang.security.SecurityUtil; import com.github.pagehelper.PageHelper; +import com.github.pagehelper.Page; import com.daxiang.mbg.mapper.TestPlanMapper; -import com.daxiang.model.Response; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; @@ -52,52 +53,54 @@ public class TestPlanService { private UserService userService; @Transactional - public Response add(TestPlan testPlan) { - if (testPlan.getEnableSchedule() == TestPlan.ENABLE_SCHEDULE && StringUtils.isEmpty(testPlan.getCronExpression())) { - // 开启定时任务,表达式不能为空 - return Response.fail("cron表达式不能为空"); + public void add(TestPlan testPlan) { + if (testPlan.getEnableSchedule() == TestPlan.ENABLE_SCHEDULE + && StringUtils.isEmpty(testPlan.getCronExpression())) { + // 若开启定时任务,表达式不能为空 + throw new ServerException("cron表达式不能为空"); } testPlan.setCreateTime(new Date()); testPlan.setCreatorUid(SecurityUtil.getCurrentUserId()); - int insertRow; try { - insertRow = testPlanMapper.insertSelective(testPlan); + int insertCount = testPlanMapper.insertSelective(testPlan); + if (insertCount != 1) { + throw new ServerException("添加失败,请稍后重试"); + } } catch (DuplicateKeyException e) { - return Response.fail("重复命名"); + throw new ServerException(testPlan.getName() + "已存在"); } if (testPlan.getEnableSchedule() == TestPlan.ENABLE_SCHEDULE) { addOrUpdateScheduleTask(testPlan); } - - return insertRow == 1 ? Response.success("添加TestPlan成功") : Response.fail("添加TestPlan失败,请稍后重试"); } - public Response delete(Integer testPlanId) { - if (testPlanId == null) { - return Response.fail("测试计划id不能为空"); + @Transactional + public void delete(Integer testPlanId) { + int deleteCount = testPlanMapper.deleteByPrimaryKey(testPlanId); + if (deleteCount != 1) { + throw new ServerException("删除失败,请稍后重试"); } - cancelScheduleTask(testPlanId); - - int deleteRow = testPlanMapper.deleteByPrimaryKey(testPlanId); - return deleteRow == 1 ? Response.success("删除TestPlan成功") : Response.fail("删除TestPlan失败,请稍后重试"); } @Transactional - public Response update(TestPlan testPlan) { - if (testPlan.getEnableSchedule() == TestPlan.ENABLE_SCHEDULE && StringUtils.isEmpty(testPlan.getCronExpression())) { - // 开启定时任务,表达式不能为空 - return Response.fail("cron表达式不能为空"); + public void update(TestPlan testPlan) { + if (testPlan.getEnableSchedule() == TestPlan.ENABLE_SCHEDULE + && StringUtils.isEmpty(testPlan.getCronExpression())) { + // 若开启定时任务,表达式不能为空 + throw new ServerException("cron表达式不能为空"); } - int updateRow; try { - updateRow = testPlanMapper.updateByPrimaryKeyWithBLOBs(testPlan); + int updateCount = testPlanMapper.updateByPrimaryKeyWithBLOBs(testPlan); + if (updateCount != 1) { + throw new ServerException("更新失败,请稍后重试"); + } } catch (DuplicateKeyException e) { - return Response.fail("命名冲突"); + throw new ServerException(testPlan.getName() + "已存在"); } if (testPlan.getEnableSchedule() == TestPlan.ENABLE_SCHEDULE) { @@ -105,25 +108,17 @@ public Response update(TestPlan testPlan) { } else { cancelScheduleTask(testPlan.getId()); } - - return updateRow == 1 ? Response.success("更新TestPlan成功") : Response.fail("更新TestPlan失败,请稍后重试"); } - public Response list(TestPlan testPlan, PageRequest pageRequest) { - boolean needPaging = pageRequest.needPaging(); - if (needPaging) { - PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); - } - - List testPlans = selectByTestPlan(testPlan); - List testPlanVos = convertTestPlansToTestPlanVos(testPlans); + public PagedData list(TestPlan query, String orderBy, PageRequest pageRequest) { + Page page = PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); - if (needPaging) { - long total = Page.getTotal(testPlans); - return Response.success(Page.build(testPlanVos, total)); - } else { - return Response.success(testPlanVos); + if (StringUtils.isEmpty(orderBy)) { + orderBy = "create_time desc"; } + + List testPlanVos = getTestPlanVos(query, orderBy); + return new PagedData<>(testPlanVos, page.getTotal()); } private List convertTestPlansToTestPlanVos(List testPlans) { @@ -138,7 +133,7 @@ private List convertTestPlansToTestPlanVos(List testPlans) .collect(Collectors.toList()); Map userMap = userService.getUserMapByIds(creatorUids); - return testPlans.stream().map(testPlan -> { + List testPlanVos = testPlans.stream().map(testPlan -> { TestPlanVo testPlanVo = new TestPlanVo(); BeanUtils.copyProperties(testPlan, testPlanVo); @@ -151,54 +146,62 @@ private List convertTestPlansToTestPlanVos(List testPlans) return testPlanVo; }).collect(Collectors.toList()); + + return testPlanVos; } - private List selectByTestPlan(TestPlan testPlan) { + public List getTestPlanVos(TestPlan query, String orderBy) { + List testPlans = getTestPlans(query, orderBy); + return convertTestPlansToTestPlanVos(testPlans); + } + + public List getTestPlans(TestPlan query) { + return getTestPlans(query, null); + } + + public List getTestPlans(TestPlan query, String orderBy) { TestPlanExample example = new TestPlanExample(); TestPlanExample.Criteria criteria = example.createCriteria(); - if (testPlan != null) { - if (testPlan.getId() != null) { - criteria.andIdEqualTo(testPlan.getId()); + if (query != null) { + if (query.getId() != null) { + criteria.andIdEqualTo(query.getId()); } - if (testPlan.getProjectId() != null) { - criteria.andProjectIdEqualTo(testPlan.getProjectId()); + if (query.getProjectId() != null) { + criteria.andProjectIdEqualTo(query.getProjectId()); } - if (!StringUtils.isEmpty(testPlan.getName())) { - criteria.andNameEqualTo(testPlan.getName()); + if (!StringUtils.isEmpty(query.getName())) { + criteria.andNameEqualTo(query.getName()); } - if (testPlan.getRunMode() != null) { - criteria.andRunModeEqualTo(testPlan.getRunMode()); + if (query.getRunMode() != null) { + criteria.andRunModeEqualTo(query.getRunMode()); } - if (testPlan.getEnableSchedule() != null) { - criteria.andEnableScheduleEqualTo(testPlan.getEnableSchedule()); + if (query.getEnableSchedule() != null) { + criteria.andEnableScheduleEqualTo(query.getEnableSchedule()); } - if (testPlan.getEnvironmentId() != null) { - criteria.andEnvironmentIdEqualTo(testPlan.getEnvironmentId()); + if (query.getEnvironmentId() != null) { + criteria.andEnvironmentIdEqualTo(query.getEnvironmentId()); } - if (testPlan.getEnableRecordVideo() != null) { - criteria.andEnableRecordVideoEqualTo(testPlan.getEnableRecordVideo()); + if (query.getEnableRecordVideo() != null) { + criteria.andEnableRecordVideoEqualTo(query.getEnableRecordVideo()); } } - example.setOrderByClause("create_time desc"); + + if (!StringUtils.isEmpty(orderBy)) { + example.setOrderByClause(orderBy); + } return testPlanMapper.selectByExampleWithBLOBs(example); } - /** - * 首次启动server,按计划去执行所有开启的定时任务 - */ public void scheduleEnabledTasks() { TestPlan query = new TestPlan(); query.setEnableSchedule(TestPlan.ENABLE_SCHEDULE); - List testPlans = selectByTestPlan(query); - testPlans.forEach(testPlan -> addOrUpdateScheduleTask(testPlan)); + List testPlans = getTestPlans(query); + testPlans.forEach(this::addOrUpdateScheduleTask); } - /** - * 添加或更新定时任务 - */ private synchronized void addOrUpdateScheduleTask(TestPlan testPlan) { ScheduledFuture future = TEST_PLAN_SCHEDULED_FUTURE_MAP.get(testPlan.getId()); if (future != null) { @@ -206,17 +209,18 @@ private synchronized void addOrUpdateScheduleTask(TestPlan testPlan) { log.info("cancel schedule, testPlan: {}", testPlan.getName()); future.cancel(true); } + log.info("add schedule, testPlan: {}", testPlan.getName()); - future = TASK_SCHEDULER.schedule(() -> testTaskService.commit(testPlan.getId(), testPlan.getCreatorUid()), new CronTrigger(testPlan.getCronExpression())); + CronTrigger cronTrigger = new CronTrigger(testPlan.getCronExpression()); + future = TASK_SCHEDULER.schedule(() -> testTaskService.commit(testPlan.getId(), testPlan.getCreatorUid()), cronTrigger); TEST_PLAN_SCHEDULED_FUTURE_MAP.put(testPlan.getId(), future); } - /** - * 取消定时任务 - * - * @param testPlanId - */ private synchronized void cancelScheduleTask(Integer testPlanId) { + if (testPlanId == null) { + throw new ServerException("testPlanId不能为空"); + } + ScheduledFuture future = TEST_PLAN_SCHEDULED_FUTURE_MAP.get(testPlanId); if (future != null) { log.info("cancel schedule, testPlanId: {}", testPlanId); @@ -230,6 +234,9 @@ public TestPlan getTestPlanById(Integer testPlanId) { } public List getTestPlansByTestSuiteId(Integer testSuiteId) { + if (testSuiteId == null) { + throw new ServerException("testSuiteId不能为空"); + } return testPlanDao.selectByTestSuiteId(testSuiteId); } @@ -238,8 +245,12 @@ public List getTestPlansByActionId(Integer actionId) { } public List getTestPlansByEnvironmentId(Integer envId) { + if (envId == null) { + throw new ServerException("envId不能为空"); + } + TestPlan query = new TestPlan(); query.setEnvironmentId(envId); - return selectByTestPlan(query); + return getTestPlans(query); } } \ No newline at end of file diff --git a/src/main/java/com/daxiang/service/TestSuiteService.java b/src/main/java/com/daxiang/service/TestSuiteService.java index 6977ada..8f485a4 100644 --- a/src/main/java/com/daxiang/service/TestSuiteService.java +++ b/src/main/java/com/daxiang/service/TestSuiteService.java @@ -1,13 +1,14 @@ package com.daxiang.service; import com.daxiang.dao.TestSuiteDao; +import com.daxiang.exception.ServerException; import com.daxiang.mbg.po.*; import com.daxiang.model.PageRequest; -import com.daxiang.model.Response; +import com.daxiang.model.PagedData; import com.daxiang.security.SecurityUtil; import com.github.pagehelper.PageHelper; +import com.github.pagehelper.Page; import com.daxiang.mbg.mapper.TestSuiteMapper; -import com.daxiang.model.Page; import com.daxiang.model.vo.TestSuiteVo; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; @@ -34,60 +35,54 @@ public class TestSuiteService { @Autowired private UserService userService; - public Response add(TestSuite testSuite) { + public void add(TestSuite testSuite) { testSuite.setCreateTime(new Date()); testSuite.setCreatorUid(SecurityUtil.getCurrentUserId()); - int insertRow; try { - insertRow = testSuiteMapper.insertSelective(testSuite); + int insertCount = testSuiteMapper.insertSelective(testSuite); + if (insertCount != 1) { + throw new ServerException("添加失败,请稍后重试"); + } } catch (DuplicateKeyException e) { - return Response.fail("命名冲突"); + throw new ServerException(testSuite.getName() + "已存在"); } - return insertRow == 1 ? Response.success("添加TestSuite成功") : Response.fail("添加TestSuite失败"); } - public Response delete(Integer testSuiteId) { - if (testSuiteId == null) { - return Response.fail("testSuiteId不能为空"); - } - + public void delete(Integer testSuiteId) { // 检查该测试集是否被testplan使用 List testPlans = testPlanService.getTestPlansByTestSuiteId(testSuiteId); if (!CollectionUtils.isEmpty(testPlans)) { String testPlanNames = testPlans.stream().map(TestPlan::getName).collect(Collectors.joining("、")); - return Response.fail("测试计划: " + testPlanNames + ",正在使用,无法删除"); + throw new ServerException("测试计划: " + testPlanNames + ",正在使用,无法删除"); } - int deleteRow = testSuiteMapper.deleteByPrimaryKey(testSuiteId); - return deleteRow == 1 ? Response.success("删除TestSuite成功") : Response.fail("删除TestSuite失败,请稍后重试"); + int deleteCount = testSuiteMapper.deleteByPrimaryKey(testSuiteId); + if (deleteCount != 1) { + throw new ServerException("删除失败,请稍后重试"); + } } - public Response update(TestSuite testSuite) { - int updateRow; + public void update(TestSuite testSuite) { try { - updateRow = testSuiteMapper.updateByPrimaryKeySelective(testSuite); + int updateCount = testSuiteMapper.updateByPrimaryKeySelective(testSuite); + if (updateCount != 1) { + throw new ServerException("更新失败,请稍后重试"); + } } catch (DuplicateKeyException e) { - return Response.fail("命名冲突"); + throw new ServerException(testSuite.getName() + "已存在"); } - return updateRow == 1 ? Response.success("更新TestSuite成功") : Response.fail("更新TestSuite失败"); } - public Response list(TestSuite testSuite, PageRequest pageRequest) { - boolean needPaging = pageRequest.needPaging(); - if (needPaging) { - PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); - } - - List testSuites = selectByTestSuite(testSuite); - List testSuiteVos = convertTestSuitesToTestSuiteVos(testSuites); + public PagedData list(TestSuite query, String orderBy, PageRequest pageRequest) { + Page page = PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); - if (needPaging) { - long total = Page.getTotal(testSuites); - return Response.success(Page.build(testSuiteVos, total)); - } else { - return Response.success(testSuiteVos); + if (StringUtils.isEmpty(orderBy)) { + orderBy = "create_time desc"; } + + List testSuiteVos = getTestSuiteVos(query, orderBy); + return new PagedData<>(testSuiteVos, page.getTotal()); } private List convertTestSuitesToTestSuiteVos(List testSuites) { @@ -102,7 +97,7 @@ private List convertTestSuitesToTestSuiteVos(List testSu .collect(Collectors.toList()); Map userMap = userService.getUserMapByIds(creatorUids); - return testSuites.stream().map(testSuite -> { + List testSuiteVos = testSuites.stream().map(testSuite -> { TestSuiteVo testSuiteVo = new TestSuiteVo(); BeanUtils.copyProperties(testSuite, testSuiteVo); @@ -115,24 +110,34 @@ private List convertTestSuitesToTestSuiteVos(List testSu return testSuiteVo; }).collect(Collectors.toList()); + + return testSuiteVos; + } + + public List getTestSuiteVos(TestSuite query, String orderBy) { + List testSuites = getTestSuites(query, orderBy); + return convertTestSuitesToTestSuiteVos(testSuites); } - private List selectByTestSuite(TestSuite testSuite) { + public List getTestSuites(TestSuite query, String orderBy) { TestSuiteExample example = new TestSuiteExample(); TestSuiteExample.Criteria criteria = example.createCriteria(); - if (testSuite != null) { - if (testSuite.getId() != null) { - criteria.andIdEqualTo(testSuite.getId()); + if (query != null) { + if (query.getId() != null) { + criteria.andIdEqualTo(query.getId()); } - if (testSuite.getProjectId() != null) { - criteria.andProjectIdEqualTo(testSuite.getProjectId()); + if (query.getProjectId() != null) { + criteria.andProjectIdEqualTo(query.getProjectId()); } - if (!StringUtils.isEmpty(testSuite.getName())) { - criteria.andNameEqualTo(testSuite.getName()); + if (!StringUtils.isEmpty(query.getName())) { + criteria.andNameEqualTo(query.getName()); } } - example.setOrderByClause("create_time desc"); + + if (!StringUtils.isEmpty(orderBy)) { + example.setOrderByClause(orderBy); + } return testSuiteMapper.selectByExampleWithBLOBs(example); } diff --git a/src/main/java/com/daxiang/service/TestTaskService.java b/src/main/java/com/daxiang/service/TestTaskService.java index 1856b63..016d030 100644 --- a/src/main/java/com/daxiang/service/TestTaskService.java +++ b/src/main/java/com/daxiang/service/TestTaskService.java @@ -1,16 +1,15 @@ package com.daxiang.service; import com.alibaba.fastjson.JSONObject; +import com.daxiang.exception.ServerException; import com.daxiang.mbg.mapper.TestTaskMapper; import com.daxiang.mbg.po.*; -import com.daxiang.model.environment.EnvironmentValue; import com.daxiang.model.vo.TestTaskVo; import com.daxiang.model.vo.TestTaskSummary; import com.github.pagehelper.PageHelper; -import com.daxiang.exception.BusinessException; -import com.daxiang.model.Page; +import com.github.pagehelper.Page; +import com.daxiang.model.PagedData; import com.daxiang.model.PageRequest; -import com.daxiang.model.Response; import com.daxiang.model.dto.Testcase; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; @@ -18,9 +17,11 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; import java.text.NumberFormat; import java.util.*; +import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -64,14 +65,14 @@ public class TestTaskService { * @return */ @Transactional - public Response commit(Integer testPlanId, Integer commitorUid) { + public void commit(Integer testPlanId, Integer commitorUid) { if (testPlanId == null || commitorUid == null) { - return Response.fail("testPlanId || commitorUid 不能为空"); + throw new ServerException("testPlanId or commitorUid 不能为空"); } TestPlan testPlan = testPlanService.getTestPlanById(testPlanId); if (testPlan == null) { - return Response.fail("测试计划不存在"); + throw new ServerException("测试计划不存在"); } // 待测试的测试用例 @@ -83,7 +84,7 @@ public Response commit(Integer testPlanId, Integer commitorUid) { .filter(action -> action.getState() == Action.RELEASE_STATE).collect(Collectors.toList()); if (CollectionUtils.isEmpty(testcases)) { - return Response.fail("测试集内没有已发布的测试用例"); + throw new ServerException("测试集内没有已发布的测试用例"); } testcaseIds = testcases.stream().map(Action::getId).collect(Collectors.toList()); @@ -91,7 +92,7 @@ public Response commit(Integer testPlanId, Integer commitorUid) { for (Action testcase : testcases) { List depends = testcase.getDepends(); if (!CollectionUtils.isEmpty(depends) && !testcaseIds.containsAll(depends)) { - return Response.fail("测试用例: " + testcase.getName() + ", 依赖的用例不在当前提测的所有用例中"); + throw new ServerException("测试用例: " + testcase.getName() + ", 依赖的用例不在当前提测的所有用例中"); } } @@ -99,7 +100,7 @@ public Response commit(Integer testPlanId, Integer commitorUid) { List beforeAndAfterActionIds = Stream.of(testPlan.getBeforeClass(), testPlan.getBeforeMethod(), testPlan.getAfterClass(), testPlan.getAfterMethod()) .filter(Objects::nonNull).distinct().collect(Collectors.toList()); Map beforeAndAfterActionMap = actionService.getActionsByIds(beforeAndAfterActionIds).stream() - .collect(Collectors.toMap(Action::getId, a -> a)); + .collect(Collectors.toMap(Action::getId, Function.identity())); // 待处理的所有action List actions = new ArrayList<>(testcases); @@ -162,13 +163,8 @@ public Response commit(Integer testPlanId, Integer commitorUid) { deviceTestTask.setTestcases(cases); deviceTestTask.setStatus(DeviceTestTask.UNSTART_STATUS); - int insertRow = deviceTestTaskService.add(deviceTestTask); - if (insertRow != 1) { - throw new BusinessException(deviceId + "保存测试任务失败"); - } + deviceTestTaskService.add(deviceTestTask); }); - - return Response.success("提交测试成功"); } /** @@ -183,7 +179,7 @@ private Map> allocateTestcaseToDevice(List deviceId Map> result = new HashMap<>(); // deviceId : List if (runMode == TestPlan.RUN_MODE_COMPATIBLE) { // 兼容模式:所有device都运行同一份用例 - result = deviceIds.stream().collect(Collectors.toMap(deviceId -> deviceId, v -> testcases)); + result = deviceIds.stream().collect(Collectors.toMap(Function.identity(), v -> testcases)); } else if (runMode == TestPlan.RUN_MODE_EFFICIENCY) { // 高效模式:平均分配用例给device int i = 0; // 分配到第几个device for (Action testcase : testcases) { @@ -215,25 +211,19 @@ private TestTask saveTestTask(TestPlan testPlan, Integer commitorUid) { if (insertRow == 1) { return testTask; } else { - throw new BusinessException("保存TestTask失败"); + throw new ServerException("保存TestTask失败"); } } - public Response list(TestTask testTask, PageRequest pageRequest) { - boolean needPaging = pageRequest.needPaging(); - if (needPaging) { - PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); - } - - List testTasks = selectByTestTask(testTask); - List testTaskVos = convertTestTasksToTestTaskVos(testTasks); + public PagedData list(TestTask query, String orderBy, PageRequest pageRequest) { + Page page = PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); - if (needPaging) { - long total = Page.getTotal(testTasks); - return Response.success(Page.build(testTaskVos, total)); - } else { - return Response.success(testTaskVos); + if (StringUtils.isEmpty(orderBy)) { + orderBy = "commit_time desc"; } + + List testTaskVos = getTestTaskVos(query, orderBy); + return new PagedData<>(testTaskVos, page.getTotal()); } private List convertTestTasksToTestTaskVos(List testTasks) { @@ -248,7 +238,7 @@ private List convertTestTasksToTestTaskVos(List testTasks) .collect(Collectors.toList()); Map userMap = userService.getUserMapByIds(creatorUids); - return testTasks.stream().map(testTask -> { + List testTaskVos = testTasks.stream().map(testTask -> { TestTaskVo testTaskVo = new TestTaskVo(); BeanUtils.copyProperties(testTask, testTaskVo); @@ -261,54 +251,71 @@ private List convertTestTasksToTestTaskVos(List testTasks) return testTaskVo; }).collect(Collectors.toList()); + + return testTaskVos; + } + + public List getTestTaskVos(TestTask query, String orderBy) { + List testTasks = getTestTasks(query, orderBy); + return convertTestTasksToTestTaskVos(testTasks); + } + + public List getTestTasks(TestTask query) { + return getTestTasks(query, null); } - private List selectByTestTask(TestTask testTask) { + public List getTestTasks(TestTask query, String orderBy) { TestTaskExample example = new TestTaskExample(); TestTaskExample.Criteria criteria = example.createCriteria(); - if (testTask != null) { - if (testTask.getId() != null) { - criteria.andIdEqualTo(testTask.getId()); + if (query != null) { + if (query.getId() != null) { + criteria.andIdEqualTo(query.getId()); } - if (testTask.getProjectId() != null) { - criteria.andProjectIdEqualTo(testTask.getProjectId()); + if (query.getProjectId() != null) { + criteria.andProjectIdEqualTo(query.getProjectId()); } - if (testTask.getTestPlanId() != null) { - criteria.andTestPlanIdEqualTo(testTask.getTestPlanId()); + if (query.getTestPlanId() != null) { + criteria.andTestPlanIdEqualTo(query.getTestPlanId()); } - if (testTask.getStatus() != null) { - criteria.andStatusEqualTo(testTask.getStatus()); + if (query.getStatus() != null) { + criteria.andStatusEqualTo(query.getStatus()); } } - example.setOrderByClause("commit_time desc"); + + if (!StringUtils.isEmpty(orderBy)) { + example.setOrderByClause(orderBy); + } return testTaskMapper.selectByExampleWithBLOBs(example); } public List getUnFinishedTestTasks() { - TestTask testTask = new TestTask(); - testTask.setStatus(TestTask.UNFINISHED_STATUS); - return selectByTestTask(testTask); + TestTask query = new TestTask(); + query.setStatus(TestTask.UNFINISHED_STATUS); + return getTestTasks(query); } - public int update(TestTask testTask) { - return testTaskMapper.updateByPrimaryKeySelective(testTask); + public void update(TestTask testTask) { + int updateCount = testTaskMapper.updateByPrimaryKeySelective(testTask); + if (updateCount != 1) { + throw new ServerException("更新失败"); + } } - public Response getTestTaskSummary(Integer testTaskId) { + public TestTaskSummary getTestTaskSummary(Integer testTaskId) { if (testTaskId == null) { - return Response.fail("testTaskId不能为空"); + throw new ServerException("testTaskId不能为空"); } TestTask testTask = testTaskMapper.selectByPrimaryKey(testTaskId); if (testTask == null) { - return Response.fail("测试任务不存在"); + throw new ServerException("测试任务不存在"); } Project project = projectService.getProjectById(testTask.getProjectId()); if (project == null) { - return Response.fail("项目不存在"); + throw new ServerException("项目不存在"); } TestTaskSummary summary = new TestTaskSummary(); @@ -331,29 +338,23 @@ public Response getTestTaskSummary(Integer testTaskId) { summary.setPassPercent(passPercent); if (testTask.getTestPlan() != null) { - Integer environmentId = testTask.getTestPlan().getEnvironmentId(); - if (environmentId == EnvironmentValue.DEFAULT_ENVIRONMENT_ID) { - summary.setEnvironmentName("默认"); - } else { - Environment environment = environmentService.getEnvironmentById(environmentId); - if (environment != null) { - summary.setEnvironmentName(environment.getName()); - } - } + Integer envId = testTask.getTestPlan().getEnvironmentId(); + String envName = environmentService.getEnvironmentNameById(envId); + summary.setEnvironmentName(envName); } - return Response.success(summary); + return summary; } @Transactional - public Response delete(Integer testTaskId) { + public void delete(Integer testTaskId) { if (testTaskId == null) { - return Response.fail("testTaskId不能为空"); + throw new ServerException("testTaskId不能为空"); } TestTask testTask = testTaskMapper.selectByPrimaryKey(testTaskId); if (testTask == null) { - return Response.fail("testTask不存在"); + throw new ServerException("testTask不存在"); } List deviceTestTasks = deviceTestTaskService.getDeviceTestTasksByTestTaskId(testTaskId); @@ -366,23 +367,17 @@ public Response delete(Integer testTaskId) { // 有device还在运行,不让删除testTask String deviceIdsInRunning = deviceTestTasksInRunning.stream() .map(DeviceTestTask::getDeviceId).collect(Collectors.joining("、")); - return Response.fail(deviceIdsInRunning + ",正在运行,无法删除"); + throw new ServerException(deviceIdsInRunning + ",正在运行,无法删除"); } else { // 批量删除deviceTestTask List deviceTestTaskIds = deviceTestTasks.stream().map(DeviceTestTask::getId).collect(Collectors.toList()); - int deleteRow = deviceTestTaskService.deleteBatch(deviceTestTaskIds); - if (deleteRow != deviceTestTasks.size()) { - throw new BusinessException(String.format("删除deviceTestTask失败,deviceTestTasks: %d, deleteRow: %d", deviceTestTasks.size(), deleteRow)); - } + deviceTestTaskService.deleteBatch(deviceTestTaskIds); } } - // 删除testTask - int deleteTestTaskRow = testTaskMapper.deleteByPrimaryKey(testTaskId); - if (deleteTestTaskRow == 1) { - return Response.success("删除成功"); - } else { - throw new BusinessException("删除失败,请稍后重试"); + int deleteCount = testTaskMapper.deleteByPrimaryKey(testTaskId); + if (deleteCount != 1) { + throw new ServerException("删除失败,请稍后重试"); } } } diff --git a/src/main/java/com/daxiang/service/UploadService.java b/src/main/java/com/daxiang/service/UploadService.java index 610b2ac..3161dec 100644 --- a/src/main/java/com/daxiang/service/UploadService.java +++ b/src/main/java/com/daxiang/service/UploadService.java @@ -1,14 +1,13 @@ package com.daxiang.service; +import com.daxiang.exception.ServerException; import com.daxiang.model.FileType; -import com.daxiang.model.Response; import com.daxiang.model.UploadFile; import com.daxiang.utils.HttpServletUtil; import com.daxiang.utils.UUIDUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; -import org.springframework.util.StringUtils; import org.springframework.web.multipart.MultipartFile; import java.io.File; @@ -24,9 +23,9 @@ public class UploadService { @Value("${static-location}/") private String staticLocation; - public Response uploadFile(MultipartFile file, Integer fileType) { + public UploadFile upload(MultipartFile file, Integer fileType) { if (file == null || fileType == null) { - return Response.fail("file || fileType不能为空"); + throw new ServerException("file or fileType不能为空"); } String uploadFilePath; @@ -47,13 +46,9 @@ public Response uploadFile(MultipartFile file, Integer fileType) { uploadFilePath = UploadFile.OTHER_FILE_PATH; } - String destFileName = UUIDUtil.getUUID(); String originalFilename = file.getOriginalFilename(); - if (originalFilename.contains(".")) { - destFileName = destFileName + "." + StringUtils.unqualify(originalFilename); - } - - String destFilePath = uploadFilePath + "/" + destFileName; + String destFilename = UUIDUtil.getUUIDFilename(originalFilename); + String destFilePath = uploadFilePath + "/" + destFilename; try { String destFileAbsolutePath = new File(staticLocation + destFilePath).getAbsolutePath(); // 不用绝对路径transferTo会报错 @@ -61,13 +56,13 @@ public Response uploadFile(MultipartFile file, Integer fileType) { file.transferTo(new File(destFileAbsolutePath)); } catch (IOException e) { log.error("transfer err", e); - return Response.fail(e.getMessage()); + throw new ServerException(e.getMessage()); } UploadFile uploadFile = new UploadFile(); uploadFile.setFilePath(destFilePath); uploadFile.setDownloadUrl(HttpServletUtil.getStaticResourceUrl(destFilePath)); - return Response.success("上传成功", uploadFile); + return uploadFile; } } diff --git a/src/main/java/com/daxiang/service/UserProjectService.java b/src/main/java/com/daxiang/service/UserProjectService.java index b26fde4..4f5388b 100644 --- a/src/main/java/com/daxiang/service/UserProjectService.java +++ b/src/main/java/com/daxiang/service/UserProjectService.java @@ -1,6 +1,7 @@ package com.daxiang.service; import com.daxiang.dao.UserProjectDao; +import com.daxiang.exception.ServerException; import com.daxiang.mbg.mapper.UserProjectMapper; import com.daxiang.mbg.po.Project; import com.daxiang.mbg.po.UserProject; @@ -10,6 +11,7 @@ import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; +import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; @@ -24,31 +26,41 @@ public class UserProjectService { @Autowired private UserProjectDao userProjectDao; - public int addBatch(List userProjects) { + public void addBatch(List userProjects) { if (CollectionUtils.isEmpty(userProjects)) { - return 0; + return; + } + + int insertCount = userProjectDao.insertBatch(userProjects); + if (insertCount != userProjects.size()) { + throw new ServerException("添加失败"); } - return userProjectDao.insertBatch(userProjects); } - public int addBatch(Integer userId, List projects) { + public void addBatch(Integer userId, List projects) { List userProjects = projects.stream().map(project -> { UserProject userProject = new UserProject(); userProject.setUserId(userId); userProject.setProjectId(project.getId()); return userProject; }).collect(Collectors.toList()); - return addBatch(userProjects); + + addBatch(userProjects); } public int deleteByUserId(Integer userId) { UserProjectExample example = new UserProjectExample(); UserProjectExample.Criteria criteria = example.createCriteria(); criteria.andUserIdEqualTo(userId); + return userProjectMapper.deleteByExample(example); } public List getUserProjectDtosByUserIds(List userIds) { + if (CollectionUtils.isEmpty(userIds)) { + return new ArrayList<>(); + } + return userProjectDao.selectUserProjectDtosByUserIds(userIds); } } diff --git a/src/main/java/com/daxiang/service/UserRoleService.java b/src/main/java/com/daxiang/service/UserRoleService.java index 9705365..19352e9 100644 --- a/src/main/java/com/daxiang/service/UserRoleService.java +++ b/src/main/java/com/daxiang/service/UserRoleService.java @@ -1,6 +1,7 @@ package com.daxiang.service; import com.daxiang.dao.UserRoleDao; +import com.daxiang.exception.ServerException; import com.daxiang.mbg.mapper.UserRoleMapper; import com.daxiang.mbg.po.Role; import com.daxiang.mbg.po.UserRole; @@ -8,7 +9,9 @@ import com.daxiang.model.dto.UserRoleDto; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; +import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; @@ -23,18 +26,22 @@ public class UserRoleService { @Autowired private UserRoleMapper userRoleMapper; - public int addBatch(List userRoles) { - return userRoleDao.insertBatch(userRoles); + public void addBatch(List userRoles) { + int insertCount = userRoleDao.insertBatch(userRoles); + if (insertCount != userRoles.size()) { + throw new ServerException("添加失败"); + } } - public int addBatch(Integer userId, List roles) { + public void addBatch(Integer userId, List roles) { List userRoles = roles.stream().map(role -> { UserRole userRole = new UserRole(); userRole.setUserId(userId); userRole.setRoleId(role.getId()); return userRole; }).collect(Collectors.toList()); - return addBatch(userRoles); + + addBatch(userRoles); } public int deleteByUserId(Integer userId) { @@ -45,6 +52,10 @@ public int deleteByUserId(Integer userId) { } public List getUserRoleDtosByUserIds(List userIds) { + if (CollectionUtils.isEmpty(userIds)) { + return new ArrayList<>(); + } + return userRoleDao.selectUserRoleDtosByUserIds(userIds); } } diff --git a/src/main/java/com/daxiang/service/UserService.java b/src/main/java/com/daxiang/service/UserService.java index c8ce29d..8b7baa3 100644 --- a/src/main/java/com/daxiang/service/UserService.java +++ b/src/main/java/com/daxiang/service/UserService.java @@ -1,10 +1,10 @@ package com.daxiang.service; -import com.daxiang.exception.BusinessException; +import com.daxiang.exception.ServerException; import com.daxiang.mbg.mapper.UserMapper; import com.daxiang.mbg.po.Project; import com.daxiang.mbg.po.Role; -import com.daxiang.model.Page; +import com.daxiang.model.PagedData; import com.daxiang.model.PageRequest; import com.daxiang.model.dto.UserDto; import com.daxiang.model.dto.UserProjectDto; @@ -12,10 +12,8 @@ import com.daxiang.security.JwtTokenUtil; import com.daxiang.mbg.po.User; import com.daxiang.mbg.po.UserExample; -import com.daxiang.model.Response; -import com.daxiang.security.SecurityUtil; import com.github.pagehelper.PageHelper; -import com.google.common.collect.ImmutableMap; +import com.github.pagehelper.Page; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DuplicateKeyException; @@ -30,6 +28,7 @@ import org.springframework.util.StringUtils; import java.util.*; +import java.util.function.Function; import java.util.stream.Collectors; @@ -55,7 +54,7 @@ public class UserService { private PasswordEncoder passwordEncoder; @Transactional - public Response add(UserDto userDto) { + public void add(UserDto userDto) { User user = new User(); BeanUtils.copyProperties(userDto, user); @@ -63,107 +62,70 @@ public Response add(UserDto userDto) { user.setCreateTime(new Date()); // 用户 - int insertRow; + int insertCount; try { - insertRow = userMapper.insertSelective(user); + insertCount = userMapper.insertSelective(user); } catch (DuplicateKeyException e) { - return Response.fail("用户名已存在"); + throw new ServerException(user.getUsername() + "已存在"); } - if (insertRow != 1) { - return Response.fail("添加用户失败,请稍后重试"); + if (insertCount != 1) { + throw new ServerException("添加用户失败,请稍后重试"); } - // 用户角色 - insertRow = userRoleService.addBatch(user.getId(), userDto.getRoles()); - if (insertRow != userDto.getRoles().size()) { - throw new BusinessException("添加角色失败,请稍后重试"); - } - - // 用户项目 - insertRow = userProjectService.addBatch(user.getId(), userDto.getProjects()); - if (insertRow != userDto.getProjects().size()) { - throw new BusinessException("添加用户项目失败,请稍后重试"); - } - - return Response.success("添加用户成功"); + userRoleService.addBatch(user.getId(), userDto.getRoles()); + userProjectService.addBatch(user.getId(), userDto.getProjects()); } - @Transactional - public Response delete(Integer userId) { + public void delete(Integer userId) { if (userId == null) { - return Response.fail("userId不能为空"); + throw new ServerException("userId不能为空"); } - // 删除用户角色 userRoleService.deleteByUserId(userId); - // 删除用户项目 userProjectService.deleteByUserId(userId); - // 删除用户 userMapper.deleteByPrimaryKey(userId); - - return Response.success("删除成功"); } @Transactional - public Response update(UserDto userDto) { + public void update(UserDto userDto) { User user = new User(); BeanUtils.copyProperties(userDto, user); User originalUser = userMapper.selectByPrimaryKey(user.getId()); if (originalUser == null) { - return Response.fail("用户不存在"); + throw new ServerException("用户不存在"); } if (!originalUser.getPassword().equals(user.getPassword())) { // 修改了密码,需要重新encode user.setPassword(passwordEncoder.encode(user.getPassword())); } - int updateRow; try { - updateRow = userMapper.updateByPrimaryKeySelective(user); + int updateCount = userMapper.updateByPrimaryKeySelective(user); + if (updateCount != 1) { + throw new ServerException("更新用户失败,请稍后重试"); + } } catch (DuplicateKeyException e) { - return Response.fail("命名冲突"); - } - if (updateRow != 1) { - return Response.fail("更新用户失败,请稍后重试"); + throw new ServerException(user.getUsername() + "已存在"); } - // 删除用户角色 userRoleService.deleteByUserId(user.getId()); + userRoleService.addBatch(user.getId(), userDto.getRoles()); - // 添加用户角色 - int insertRow = userRoleService.addBatch(user.getId(), userDto.getRoles()); - if (insertRow != userDto.getRoles().size()) { - throw new BusinessException("添加用户角色失败"); - } - - // 删除用户项目 userProjectService.deleteByUserId(user.getId()); - - // 添加用户项目 - insertRow = userProjectService.addBatch(user.getId(), userDto.getProjects()); - if (insertRow != userDto.getProjects().size()) { - throw new BusinessException("添加用户项目失败"); - } - - return Response.success("更新用户成功"); + userProjectService.addBatch(user.getId(), userDto.getProjects()); } - public Response list(User user, PageRequest pageRequest) { - boolean needPaging = pageRequest.needPaging(); - if (needPaging) { - PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); - } - - List users = selectByUser(user); - List userDtos = convertUsersToUserDtos(users); + public PagedData list(User query, String orderBy, PageRequest pageRequest) { + Page page = PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); - if (needPaging) { - return Response.success(Page.build(userDtos, Page.getTotal(users))); - } else { - return Response.success(userDtos); + if (StringUtils.isEmpty(orderBy)) { + orderBy = "create_time desc"; } + + List userDtos = getUserDtos(query, orderBy); + return new PagedData<>(userDtos, page.getTotal()); } private List convertUsersToUserDtos(List users) { @@ -178,7 +140,7 @@ private List convertUsersToUserDtos(List users) { Map> userProjectDtosMap = userProjectService.getUserProjectDtosByUserIds(userIds).stream() .collect(Collectors.groupingBy(UserProjectDto::getUserId)); - return users.stream().map(user -> { + List userDtos = users.stream().map(user -> { UserDto userDto = new UserDto(); BeanUtils.copyProperties(user, userDto); @@ -200,54 +162,55 @@ private List convertUsersToUserDtos(List users) { return userDto; }).collect(Collectors.toList()); + + return userDtos; } - public Response login(User user) { + public String login(User user) { try { authenticationManager .authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword())); } catch (DisabledException e) { - return Response.fail("账户已禁用"); + throw new ServerException("账户已禁用"); } catch (AuthenticationException e) { - return Response.fail("用户名或密码错误"); + throw new ServerException("用户名或密码错误"); } - String token = JwtTokenUtil.createToken(user.getUsername()); - return Response.success("登陆成功", ImmutableMap.of("token", token)); - } - - public Response getInfo() { - return Response.success(SecurityUtil.getCurrentUserDto()); + return JwtTokenUtil.createToken(user.getUsername()); } - public Response logout() { - return Response.success(); + public List getUserDtos(User query, String orderBy) { + List users = getUsers(query, orderBy); + return convertUsersToUserDtos(users); } - private List selectByUser(User user) { + public List getUsers(User query, String orderBy) { UserExample example = new UserExample(); UserExample.Criteria criteria = example.createCriteria(); - if (user != null) { - if (user.getId() != null) { - criteria.andIdEqualTo(user.getId()); + if (query != null) { + if (query.getId() != null) { + criteria.andIdEqualTo(query.getId()); } - if (!StringUtils.isEmpty(user.getUsername())) { - criteria.andUsernameLike("%" + user.getUsername() + "%"); + if (!StringUtils.isEmpty(query.getUsername())) { + criteria.andUsernameLike("%" + query.getUsername() + "%"); } - if (!StringUtils.isEmpty(user.getNickName())) { - criteria.andNickNameEqualTo(user.getNickName()); + if (!StringUtils.isEmpty(query.getNickName())) { + criteria.andNickNameEqualTo(query.getNickName()); } - if (user.getStatus() != null) { - criteria.andStatusEqualTo(user.getStatus()); + if (query.getStatus() != null) { + criteria.andStatusEqualTo(query.getStatus()); } } - example.setOrderByClause("create_time desc"); + + if (!StringUtils.isEmpty(orderBy)) { + example.setOrderByClause(orderBy); + } return userMapper.selectByExample(example); } - private User getUserByUsername(String username) { + public User getUserByUsername(String username) { UserExample example = new UserExample(); example.createCriteria().andUsernameEqualTo(username); List users = userMapper.selectByExample(example); @@ -283,7 +246,7 @@ public UserDto getUserDtoByUsername(String username) { return userDto; } - private List getUsersByIds(List userIds) { + public List getUsersByIds(List userIds) { if (CollectionUtils.isEmpty(userIds)) { return new ArrayList<>(); } @@ -296,7 +259,7 @@ private List getUsersByIds(List userIds) { public Map getUserMapByIds(List userIds) { List users = getUsersByIds(userIds); - return users.stream().collect(Collectors.toMap(User::getId, u -> u, (k1, k2) -> k1)); + return users.stream().collect(Collectors.toMap(User::getId, Function.identity(), (k1, k2) -> k1)); } public User getUserById(Integer userId) { diff --git a/src/main/java/com/daxiang/utils/Tree.java b/src/main/java/com/daxiang/utils/Tree.java index bb359f9..3da6c77 100644 --- a/src/main/java/com/daxiang/utils/Tree.java +++ b/src/main/java/com/daxiang/utils/Tree.java @@ -5,6 +5,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.function.Function; import java.util.stream.Collectors; /** @@ -30,7 +31,7 @@ public static List build(List nodes) { } Map nodeMap = nodes.stream() - .collect(Collectors.toMap(TreeNode::getId, v -> v, (k1, k2) -> k1)); + .collect(Collectors.toMap(TreeNode::getId, Function.identity(), (k1, k2) -> k1)); for (TreeNode node : nodes) { TreeNode parent = nodeMap.get(node.getParentId()); diff --git a/src/main/java/com/daxiang/utils/UUIDUtil.java b/src/main/java/com/daxiang/utils/UUIDUtil.java index cd0f2c3..f89bbf1 100644 --- a/src/main/java/com/daxiang/utils/UUIDUtil.java +++ b/src/main/java/com/daxiang/utils/UUIDUtil.java @@ -1,5 +1,8 @@ package com.daxiang.utils; +import org.springframework.util.Assert; +import org.springframework.util.StringUtils; + import java.util.UUID; /** @@ -10,4 +13,9 @@ public class UUIDUtil { public static String getUUID() { return UUID.randomUUID().toString().replace("-", "").toLowerCase(); } + + public static String getUUIDFilename(String filename) { + Assert.hasText(filename, "filename不能为空"); + return filename.contains(".") ? getUUID() + "." + StringUtils.unqualify(filename) : getUUID(); + } }